Merge pull request #18 from Solovyov1796/remove_das

Remove das
This commit is contained in:
Solovyov1796 2024-05-22 16:08:05 +08:00 committed by GitHub
commit 5db21cba18
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
101 changed files with 791 additions and 7152 deletions

View File

@ -78,7 +78,7 @@ print-machine-info:
BUILD_DIR := build# build files BUILD_DIR := build# build files
BIN_DIR := $(BUILD_DIR)/bin# for binary dev dependencies BIN_DIR := $(BUILD_DIR)/bin# for binary dev dependencies
BUILD_CACHE_DIR := $(BUILD_DIR)/.cache# caching for non-artifact outputs BUILD_CACHE_DIR := $(BUILD_DIR)/.cache# caching for non-artifact outputs
OUT_DIR := out# for artifact intermediates and outputs OUT_DIR := ./.build# for artifact intermediates and outputs
ROOT_DIR := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))# absolute path to root ROOT_DIR := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))# absolute path to root
export PATH := $(ROOT_DIR)/$(BIN_DIR):$(PATH)# add local bin first in path export PATH := $(ROOT_DIR)/$(BIN_DIR):$(PATH)# add local bin first in path

View File

@ -8,8 +8,8 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
sdkmath "cosmossdk.io/math"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -62,11 +62,11 @@ func (suite *SimulateRequestTestSuite) TestSimulateRequest() {
bank.MsgSend{ bank.MsgSend{
FromAddress: fromAddr, FromAddress: fromAddr,
ToAddress: toAddr, ToAddress: toAddr,
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e6)),
}, },
}, },
Fee: auth.StdFee{ Fee: auth.StdFee{
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(5e4))), Amount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(5e4)),
Gas: 1e6, Gas: 1e6,
}, },
Memo: "test memo", Memo: "test memo",

View File

@ -66,7 +66,7 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) {
chainID, chainID,
app.NewFundedGenStateWithSameCoins( app.NewFundedGenStateWithSameCoins(
tApp.AppCodec(), tApp.AppCodec(),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 1e9)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e9)),
testAddresses, testAddresses,
), ),
newBep3GenStateMulti(tApp.AppCodec(), deputy), newBep3GenStateMulti(tApp.AppCodec(), deputy),
@ -114,7 +114,7 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) {
banktypes.NewMsgSend( banktypes.NewMsgSend(
tc.address, tc.address,
testAddresses[0], testAddresses[0],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 1_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1_000_000)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee

View File

@ -12,6 +12,7 @@ import (
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/ante" "github.com/0glabs/0g-chain/app/ante"
"github.com/0glabs/0g-chain/chaincfg"
) )
var _ sdk.AnteHandler = (&MockAnteHandler{}).AnteHandle var _ sdk.AnteHandler = (&MockAnteHandler{}).AnteHandle
@ -45,7 +46,7 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_NotCheckTx(t *testing.T) {
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100_000_000)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee
@ -80,12 +81,12 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Pass(t *testing.T) {
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[2], testAddresses[2],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee
@ -121,7 +122,7 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Reject(t *testing.T) {
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee

View File

@ -16,6 +16,7 @@ import (
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/ante" "github.com/0glabs/0g-chain/app/ante"
"github.com/0glabs/0g-chain/chaincfg"
) )
func newMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a authz.Authorization, expiration time.Time) *authz.MsgGrant { func newMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a authz.Authorization, expiration time.Time) *authz.MsgGrant {
@ -58,7 +59,7 @@ func TestAuthzLimiterDecorator(t *testing.T) {
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100e6)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100e6)),
), ),
}, },
checkTx: false, checkTx: false,
@ -128,7 +129,7 @@ func TestAuthzLimiterDecorator(t *testing.T) {
[]sdk.Msg{banktypes.NewMsgSend( []sdk.Msg{banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[3], testAddresses[3],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100e6)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100e6)),
)}), )}),
}, },
checkTx: false, checkTx: false,
@ -161,7 +162,7 @@ func TestAuthzLimiterDecorator(t *testing.T) {
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[3], testAddresses[3],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100e6)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100e6)),
), ),
&evmtypes.MsgEthereumTx{}, &evmtypes.MsgEthereumTx{},
}, },

View File

@ -34,6 +34,7 @@ import (
"github.com/tendermint/tendermint/version" "github.com/tendermint/tendermint/version"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
evmutiltestutil "github.com/0glabs/0g-chain/x/evmutil/testutil" evmutiltestutil "github.com/0glabs/0g-chain/x/evmutil/testutil"
evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
@ -155,7 +156,7 @@ func (suite *EIP712TestSuite) SetupTest() {
// Genesis states // Genesis states
evmGs := evmtypes.NewGenesisState( evmGs := evmtypes.NewGenesisState(
evmtypes.NewParams( evmtypes.NewParams(
"neuron", // evmDenom chaincfg.EvmDenom, // evmDenom
false, // allowedUnprotectedTxs false, // allowedUnprotectedTxs
true, // enableCreate true, // enableCreate
true, // enableCall true, // enableCall
@ -221,10 +222,10 @@ func (suite *EIP712TestSuite) SetupTest() {
pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState), pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState),
} }
// funds our test accounts with some ua0gi // funds our test accounts with some gas denom
coinsGenState := app.NewFundedGenStateWithSameCoins( coinsGenState := app.NewFundedGenStateWithSameCoins(
tApp.AppCodec(), tApp.AppCodec(),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 1e9)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e9)),
[]sdk.AccAddress{suite.testAddr, suite.testAddr2}, []sdk.AccAddress{suite.testAddr, suite.testAddr2},
) )
@ -306,17 +307,17 @@ func (suite *EIP712TestSuite) SetupTest() {
params := evmKeeper.GetParams(suite.ctx) params := evmKeeper.GetParams(suite.ctx)
params.EIP712AllowedMsgs = []evmtypes.EIP712AllowedMsg{ params.EIP712AllowedMsgs = []evmtypes.EIP712AllowedMsg{
{ {
MsgTypeUrl: "/0g-chain.evmutil.v1beta1.MsgConvertERC20ToCoin", MsgTypeUrl: "/zgc.evmutil.v1beta1.MsgConvertERC20ToCoin",
MsgValueTypeName: "MsgValueEVMConvertERC20ToCoin", MsgValueTypeName: "MsgValueEVMConvertERC20ToCoin",
ValueTypes: []evmtypes.EIP712MsgAttrType{ ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "initiator", Type: "string"}, {Name: "initiator", Type: "string"},
{Name: "receiver", Type: "string"}, {Name: "receiver", Type: "string"},
{Name: "0gchain_erc20_address", Type: "string"}, {Name: "zgchain_erc20_address", Type: "string"},
{Name: "amount", Type: "string"}, {Name: "amount", Type: "string"},
}, },
}, },
{ {
MsgTypeUrl: "/0g-chain.evmutil.v1beta1.MsgConvertCoinToERC20", MsgTypeUrl: "/zgc.evmutil.v1beta1.MsgConvertCoinToERC20",
MsgValueTypeName: "MsgValueEVMConvertCoinToERC20", MsgValueTypeName: "MsgValueEVMConvertCoinToERC20",
ValueTypes: []evmtypes.EIP712MsgAttrType{ ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "initiator", Type: "string"}, {Name: "initiator", Type: "string"},
@ -369,7 +370,7 @@ func (suite *EIP712TestSuite) deployUSDCERC20(app app.TestApp, ctx sdk.Context)
suite.tApp.FundModuleAccount( suite.tApp.FundModuleAccount(
suite.ctx, suite.ctx,
evmutiltypes.ModuleName, evmutiltypes.ModuleName,
sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(0))), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(0)),
) )
contractAddr, err := suite.evmutilKeeper.DeployTestMintableERC20Contract(suite.ctx, "USDC", "USDC", uint8(18)) contractAddr, err := suite.evmutilKeeper.DeployTestMintableERC20Contract(suite.ctx, "USDC", "USDC", uint8(18))
@ -469,7 +470,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
errMsg: "insufficient funds", errMsg: "insufficient funds",
updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder { updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder {
bk := suite.tApp.GetBankKeeper() bk := suite.tApp.GetBankKeeper()
gasCoins := bk.GetBalance(suite.ctx, suite.testAddr, "ua0gi") gasCoins := bk.GetBalance(suite.ctx, suite.testAddr, chaincfg.GasDenom)
suite.tApp.GetBankKeeper().SendCoins(suite.ctx, suite.testAddr, suite.testAddr2, sdk.NewCoins(gasCoins)) suite.tApp.GetBankKeeper().SendCoins(suite.ctx, suite.testAddr, suite.testAddr2, sdk.NewCoins(gasCoins))
return txBuilder return txBuilder
}, },
@ -481,7 +482,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx: true, failCheckTx: true,
errMsg: "invalid chain-id", errMsg: "invalid chain-id",
updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder { updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder {
gasAmt := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(20))) gasAmt := sdk.NewCoins(chaincfg.MakeCoinForGasDenom(20))
return suite.createTestEIP712CosmosTxBuilder( return suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, "kavatest_12-1", uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs, suite.testAddr, suite.testPrivKey, "kavatest_12-1", uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs,
) )
@ -494,7 +495,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx: true, failCheckTx: true,
errMsg: "invalid pubkey", errMsg: "invalid pubkey",
updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder { updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder {
gasAmt := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(20))) gasAmt := sdk.NewCoins(chaincfg.MakeCoinForGasDenom(20))
return suite.createTestEIP712CosmosTxBuilder( return suite.createTestEIP712CosmosTxBuilder(
suite.testAddr2, suite.testPrivKey2, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs, suite.testAddr2, suite.testPrivKey2, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs,
) )
@ -522,7 +523,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
msgs = tc.updateMsgs(msgs) msgs = tc.updateMsgs(msgs)
} }
gasAmt := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(20))) gasAmt := sdk.NewCoins(chaincfg.MakeCoinForGasDenom(20))
txBuilder := suite.createTestEIP712CosmosTxBuilder( txBuilder := suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs, suite.testAddr, suite.testPrivKey, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs,
) )
@ -596,7 +597,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
} }
// deliver deposit msg // deliver deposit msg
gasAmt := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(20))) gasAmt := sdk.NewCoins(chaincfg.MakeCoinForGasDenom(20))
txBuilder := suite.createTestEIP712CosmosTxBuilder( txBuilder := suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, depositMsgs, suite.testAddr, suite.testPrivKey, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, depositMsgs,
) )

View File

@ -13,6 +13,7 @@ import (
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/ante" "github.com/0glabs/0g-chain/app/ante"
"github.com/0glabs/0g-chain/chaincfg"
) )
func mustParseDecCoins(value string) sdk.DecCoins { func mustParseDecCoins(value string) sdk.DecCoins {
@ -30,7 +31,7 @@ func TestEvmMinGasFilter(t *testing.T) {
ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()})
tApp.GetEvmKeeper().SetParams(ctx, evmtypes.Params{ tApp.GetEvmKeeper().SetParams(ctx, evmtypes.Params{
EvmDenom: "neuron", EvmDenom: chaincfg.EvmDenom,
}) })
testCases := []struct { testCases := []struct {

View File

@ -14,6 +14,7 @@ import (
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/ante" "github.com/0glabs/0g-chain/app/ante"
"github.com/0glabs/0g-chain/chaincfg"
) )
func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing.T) { func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing.T) {
@ -33,7 +34,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing
"MsgCreateVestingAccount", "MsgCreateVestingAccount",
vesting.NewMsgCreateVestingAccount( vesting.NewMsgCreateVestingAccount(
testAddresses[0], testAddresses[1], testAddresses[0], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC).Unix(),
false, false,
), ),
@ -44,7 +45,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing
"MsgCreateVestingAccount", "MsgCreateVestingAccount",
vesting.NewMsgCreatePermanentLockedAccount( vesting.NewMsgCreatePermanentLockedAccount(
testAddresses[0], testAddresses[1], testAddresses[0], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
true, true,
"MsgTypeURL /cosmos.vesting.v1beta1.MsgCreatePermanentLockedAccount not supported", "MsgTypeURL /cosmos.vesting.v1beta1.MsgCreatePermanentLockedAccount not supported",
@ -63,7 +64,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing
"other messages not affected", "other messages not affected",
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[1], testAddresses[0], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
false, false,
"", "",

View File

@ -109,9 +109,6 @@ import (
council "github.com/0glabs/0g-chain/x/council/v1" council "github.com/0glabs/0g-chain/x/council/v1"
councilkeeper "github.com/0glabs/0g-chain/x/council/v1/keeper" councilkeeper "github.com/0glabs/0g-chain/x/council/v1/keeper"
counciltypes "github.com/0glabs/0g-chain/x/council/v1/types" counciltypes "github.com/0glabs/0g-chain/x/council/v1/types"
das "github.com/0glabs/0g-chain/x/das/v1"
daskeeper "github.com/0glabs/0g-chain/x/das/v1/keeper"
dastypes "github.com/0glabs/0g-chain/x/das/v1/types"
dasigners "github.com/0glabs/0g-chain/x/dasigners/v1" dasigners "github.com/0glabs/0g-chain/x/dasigners/v1"
dasignerskeeper "github.com/0glabs/0g-chain/x/dasigners/v1/keeper" dasignerskeeper "github.com/0glabs/0g-chain/x/dasigners/v1/keeper"
dasignerstypes "github.com/0glabs/0g-chain/x/dasigners/v1/types" dasignerstypes "github.com/0glabs/0g-chain/x/dasigners/v1/types"
@ -169,7 +166,6 @@ var (
evmutil.AppModuleBasic{}, evmutil.AppModuleBasic{},
mint.AppModuleBasic{}, mint.AppModuleBasic{},
council.AppModuleBasic{}, council.AppModuleBasic{},
das.AppModuleBasic{},
dasigners.AppModuleBasic{}, dasigners.AppModuleBasic{},
) )
@ -248,7 +244,6 @@ type App struct {
evidenceKeeper evidencekeeper.Keeper evidenceKeeper evidencekeeper.Keeper
transferKeeper ibctransferkeeper.Keeper transferKeeper ibctransferkeeper.Keeper
CouncilKeeper councilkeeper.Keeper CouncilKeeper councilkeeper.Keeper
DasKeeper daskeeper.Keeper
issuanceKeeper issuancekeeper.Keeper issuanceKeeper issuancekeeper.Keeper
bep3Keeper bep3keeper.Keeper bep3Keeper bep3keeper.Keeper
pricefeedKeeper pricefeedkeeper.Keeper pricefeedKeeper pricefeedkeeper.Keeper
@ -303,7 +298,6 @@ func NewApp(
committeetypes.StoreKey, evmutiltypes.StoreKey, committeetypes.StoreKey, evmutiltypes.StoreKey,
minttypes.StoreKey, minttypes.StoreKey,
counciltypes.StoreKey, counciltypes.StoreKey,
dastypes.StoreKey,
dasignerstypes.StoreKey, dasignerstypes.StoreKey,
) )
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey)
@ -576,7 +570,6 @@ func NewApp(
app.CouncilKeeper = councilkeeper.NewKeeper( app.CouncilKeeper = councilkeeper.NewKeeper(
keys[counciltypes.StoreKey], appCodec, app.stakingKeeper, keys[counciltypes.StoreKey], appCodec, app.stakingKeeper,
) )
app.DasKeeper = daskeeper.NewKeeper(keys[dastypes.StoreKey], appCodec, app.stakingKeeper)
// create the module manager (Note: Any module instantiated in the module manager that is later modified // create the module manager (Note: Any module instantiated in the module manager that is later modified
// must be passed by reference here.) // must be passed by reference here.)
@ -608,7 +601,6 @@ func NewApp(
// nil InflationCalculationFn, use SDK's default inflation function // nil InflationCalculationFn, use SDK's default inflation function
mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper, nil), mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper, nil),
council.NewAppModule(app.CouncilKeeper, app.stakingKeeper), council.NewAppModule(app.CouncilKeeper, app.stakingKeeper),
das.NewAppModule(app.DasKeeper),
dasigners.NewAppModule(app.dasignersKeeper, app.stakingKeeper), dasigners.NewAppModule(app.dasignersKeeper, app.stakingKeeper),
) )
@ -653,7 +645,6 @@ func NewApp(
evmutiltypes.ModuleName, evmutiltypes.ModuleName,
counciltypes.ModuleName, counciltypes.ModuleName,
dastypes.ModuleName,
dasignerstypes.ModuleName, dasignerstypes.ModuleName,
) )
@ -687,7 +678,6 @@ func NewApp(
evmutiltypes.ModuleName, evmutiltypes.ModuleName,
minttypes.ModuleName, minttypes.ModuleName,
counciltypes.ModuleName, counciltypes.ModuleName,
dastypes.ModuleName,
dasignerstypes.ModuleName, dasignerstypes.ModuleName,
) )
@ -720,7 +710,6 @@ func NewApp(
upgradetypes.ModuleName, upgradetypes.ModuleName,
validatorvestingtypes.ModuleName, validatorvestingtypes.ModuleName,
counciltypes.ModuleName, counciltypes.ModuleName,
dastypes.ModuleName,
dasignerstypes.ModuleName, dasignerstypes.ModuleName,
) )

View File

@ -149,7 +149,7 @@ func GenesisStateWithSingleValidator(
balances := []banktypes.Balance{ balances := []banktypes.Balance{
{ {
Address: acc.GetAddress().String(), Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(100000000000000))), Coins: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100000000000000)),
}, },
} }
@ -212,7 +212,7 @@ func genesisStateWithValSet(
} }
// set validators and delegations // set validators and delegations
currentStakingGenesis := stakingtypes.GetGenesisStateFromAppState(app.appCodec, genesisState) currentStakingGenesis := stakingtypes.GetGenesisStateFromAppState(app.appCodec, genesisState)
currentStakingGenesis.Params.BondDenom = "ua0gi" currentStakingGenesis.Params.BondDenom = chaincfg.GasDenom // TODO:
stakingGenesis := stakingtypes.NewGenesisState( stakingGenesis := stakingtypes.NewGenesisState(
currentStakingGenesis.Params, currentStakingGenesis.Params,
@ -232,13 +232,13 @@ func genesisStateWithValSet(
for range delegations { for range delegations {
// add delegated tokens to total supply // add delegated tokens to total supply
totalSupply = totalSupply.Add(sdk.NewCoin("ua0gi", bondAmt)) totalSupply = totalSupply.Add(chaincfg.MakeCoinForGasDenom(bondAmt))
} }
// add bonded amount to bonded pool module account // add bonded amount to bonded pool module account
balances = append(balances, banktypes.Balance{ balances = append(balances, banktypes.Balance{
Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(),
Coins: sdk.Coins{sdk.NewCoin("ua0gi", bondAmt)}, Coins: sdk.Coins{chaincfg.MakeCoinForGasDenom(bondAmt)},
}) })
bankGenesis := banktypes.NewGenesisState( bankGenesis := banktypes.NewGenesisState(

57
chaincfg/coin_helper.go Normal file
View File

@ -0,0 +1,57 @@
package chaincfg
import (
"fmt"
"math/big"
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/shopspring/decimal"
)
func toBigInt(amount any) *big.Int {
if amount == nil {
return big.NewInt(0)
}
var val *big.Int
switch amount.(type) {
case int:
val = big.NewInt(int64(amount.(int)))
case int32:
val = big.NewInt(int64(amount.(int32)))
case int64:
val = big.NewInt(amount.(int64))
case string:
var ok bool
val, ok = new(big.Int).SetString(amount.(string), 0)
if !ok {
panic(fmt.Sprintf("invalid amount string: %s", amount.(string)))
}
case math.Int:
val = amount.(math.Int).BigInt()
case *big.Int:
val = amount.(*big.Int)
case float64:
val = decimal.NewFromFloat(amount.(float64)).BigInt()
default:
panic(fmt.Sprintf("invalid amount type: %T", amount))
}
return val
}
func MakeCoinForStandardDenom(amount any) sdk.Coin {
return makeCoin(StandardDenom, toBigInt(amount))
}
func MakeCoinForGasDenom(amount any) sdk.Coin {
return makeCoin(GasDenom, toBigInt(amount))
}
func MakeCoinForEvmDenom(amount any) sdk.Coin {
return makeCoin(EvmDenom, toBigInt(amount))
}
func makeCoin(denom string, amount *big.Int) sdk.Coin {
return sdk.NewCoin(denom, math.NewIntFromBigInt(amount))
}

37
chaincfg/denoms.go Normal file
View File

@ -0,0 +1,37 @@
package chaincfg
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
StandardDenom = "a0gi"
GasDenom = "ua0gi"
EvmDenom = "neuron"
BondDenom = EvmDenom
GasDenomUnit = 6
EvmDenomUnit = 18
GasDenomConversionMultiplier = 1e12
EvmDenomConversionMultiplier = 1e18
)
// RegisterDenoms registers the base and gas denominations to the SDK.
func RegisterDenoms() {
if err := sdk.RegisterDenom(StandardDenom, sdk.OneDec()); err != nil {
panic(err)
}
if err := sdk.RegisterDenom(GasDenom, sdk.NewDecWithPrec(1, GasDenomUnit)); err != nil {
panic(err)
}
if err := sdk.RegisterDenom(EvmDenom, sdk.NewDecWithPrec(1, EvmDenomUnit)); err != nil {
panic(err)
}
}

80
chaincfg/denoms_test.go Normal file
View File

@ -0,0 +1,80 @@
package chaincfg
import (
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/assert"
)
func TestRegisterDenoms(t *testing.T) {
RegisterDenoms()
tests := []struct {
name string
from sdk.Coin
targetDenom string
expCoin sdk.Coin
expErr error
}{
{
"standard to gas",
MakeCoinForStandardDenom(99),
GasDenom,
MakeCoinForGasDenom(99 * (EvmDenomConversionMultiplier / GasDenomConversionMultiplier)),
nil,
},
{
"gas to standard",
MakeCoinForGasDenom(5e7),
StandardDenom,
MakeCoinForStandardDenom(50),
nil,
},
{
"standard to base",
MakeCoinForStandardDenom(22),
EvmDenom,
MakeCoinForEvmDenom(22 * EvmDenomConversionMultiplier),
nil,
},
{
"base to standard",
MakeCoinForEvmDenom("97000000000000000000"),
StandardDenom,
MakeCoinForStandardDenom(97),
nil,
},
{
"gas to base",
MakeCoinForGasDenom(33),
EvmDenom,
MakeCoinForEvmDenom(33 * GasDenomConversionMultiplier),
nil,
},
{
"base to gas",
MakeCoinForEvmDenom("770000000000000"),
GasDenom,
MakeCoinForGasDenom(770000000000000 / GasDenomConversionMultiplier),
nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ret, err := sdk.ConvertCoin(tt.from, tt.targetDenom)
if tt.expErr != nil {
if err == nil {
t.Errorf("expErr is not nil, but got nil")
return
}
} else {
if err != nil {
t.Errorf("expErr is nil, but got %v", err)
return
}
}
assert.Equal(t, tt.expCoin, ret)
})
}
}

View File

@ -73,7 +73,7 @@ func TestKvCLIKeysAddRecover(t *testing.T) {
f.Cleanup() f.Cleanup()
} }
func TestKavaCLIKeysAddRecoverHDPath(t *testing.T) { func TestZgChainCLIKeysAddRecoverHDPath(t *testing.T) {
t.Parallel() t.Parallel()
f := InitFixtures(t) f := InitFixtures(t)

View File

@ -3121,7 +3121,7 @@ paths:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit base represents the evm denom (should be the DenomUnit
with exponent = 0). with exponent = 0).
display: display:
type: string type: string
@ -3328,7 +3328,7 @@ paths:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit base represents the evm denom (should be the DenomUnit
with exponent = 0). with exponent = 0).
display: display:
type: string type: string
@ -35597,7 +35597,7 @@ definitions:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit with exponent base represents the evm denom (should be the DenomUnit with exponent
= 0). = 0).
display: display:
type: string type: string
@ -35764,7 +35764,7 @@ definitions:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit with base represents the evm denom (should be the DenomUnit with
exponent = 0). exponent = 0).
display: display:
type: string type: string
@ -35920,7 +35920,7 @@ definitions:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit with base represents the evm denom (should be the DenomUnit with
exponent = 0). exponent = 0).
display: display:
type: string type: string

View File

@ -129,9 +129,9 @@ paths:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible DenomTrace contains the evm denomination for ICS20 fungible
tokens and the tokens and the
source tracing information path. source tracing information path.
@ -265,9 +265,9 @@ paths:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible DenomTrace contains the evm denomination for ICS20 fungible
tokens and the tokens and the
source tracing information path. source tracing information path.
@ -13499,9 +13499,9 @@ definitions:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible tokens and DenomTrace contains the evm denomination for ICS20 fungible tokens and
the the
source tracing information path. source tracing information path.
@ -13557,9 +13557,9 @@ definitions:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible tokens DenomTrace contains the evm denomination for ICS20 fungible tokens
and the and the
source tracing information path. source tracing information path.
@ -13583,9 +13583,9 @@ definitions:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible tokens DenomTrace contains the evm denomination for ICS20 fungible tokens
and the and the
source tracing information path. source tracing information path.

View File

@ -16331,7 +16331,7 @@ paths:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit base represents the evm denom (should be the DenomUnit
with exponent = 0). with exponent = 0).
display: display:
type: string type: string
@ -16538,7 +16538,7 @@ paths:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit base represents the evm denom (should be the DenomUnit
with exponent = 0). with exponent = 0).
display: display:
type: string type: string
@ -39228,9 +39228,9 @@ paths:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible DenomTrace contains the evm denomination for ICS20 fungible
tokens and the tokens and the
source tracing information path. source tracing information path.
@ -39364,9 +39364,9 @@ paths:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible DenomTrace contains the evm denomination for ICS20 fungible
tokens and the tokens and the
source tracing information path. source tracing information path.
@ -58047,7 +58047,7 @@ definitions:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit with exponent base represents the evm denom (should be the DenomUnit with exponent
= 0). = 0).
display: display:
type: string type: string
@ -58214,7 +58214,7 @@ definitions:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit with base represents the evm denom (should be the DenomUnit with
exponent = 0). exponent = 0).
display: display:
type: string type: string
@ -58370,7 +58370,7 @@ definitions:
base: base:
type: string type: string
description: >- description: >-
base represents the base denom (should be the DenomUnit with base represents the evm denom (should be the DenomUnit with
exponent = 0). exponent = 0).
display: display:
type: string type: string
@ -81239,9 +81239,9 @@ definitions:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible tokens and DenomTrace contains the evm denomination for ICS20 fungible tokens and
the the
source tracing information path. source tracing information path.
@ -81297,9 +81297,9 @@ definitions:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible tokens DenomTrace contains the evm denomination for ICS20 fungible tokens
and the and the
source tracing information path. source tracing information path.
@ -81323,9 +81323,9 @@ definitions:
source of the fungible token. source of the fungible token.
base_denom: base_denom:
type: string type: string
description: base denomination of the relayed fungible token. description: evm denomination of the relayed fungible token.
description: >- description: >-
DenomTrace contains the base denomination for ICS20 fungible tokens DenomTrace contains the evm denomination for ICS20 fungible tokens
and the and the
source tracing information path. source tracing information path.

View File

@ -31,8 +31,8 @@ import (
func customKeyringOptions() keyring.Option { func customKeyringOptions() keyring.Option {
return func(options *keyring.Options) { return func(options *keyring.Options) {
options.SupportedAlgos = append(hd.SupportedAlgorithms, vrf.VrfAlgo) options.SupportedAlgos = append(options.SupportedAlgos, vrf.VrfAlgo, hd.EthSecp256k1)
options.SupportedAlgosLedger = append(hd.SupportedAlgorithmsLedger, vrf.VrfAlgo) options.SupportedAlgosLedger = append(options.SupportedAlgosLedger, vrf.VrfAlgo, hd.EthSecp256k1)
} }
} }
@ -72,7 +72,7 @@ func NewRootCmd() *cobra.Command {
return err return err
} }
customAppTemplate, customAppConfig := servercfg.AppConfig("ua0gi") customAppTemplate, customAppConfig := servercfg.AppConfig(chaincfg.GasDenom)
return server.InterceptConfigsPreRunHandler( return server.InterceptConfigsPreRunHandler(
cmd, cmd,
@ -123,7 +123,7 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de
ac.addStartCmdFlags, ac.addStartCmdFlags,
) )
// add keybase, auxiliary RPC, query, and tx child commands // add keybase, gas RPC, query, and tx child commands
rootCmd.AddCommand( rootCmd.AddCommand(
newQueryCmd(), newQueryCmd(),
newTxCmd(), newTxCmd(),

2
go.mod
View File

@ -136,6 +136,7 @@ require (
github.com/klauspost/compress v1.15.15 // indirect github.com/klauspost/compress v1.15.15 // indirect
github.com/lib/pq v1.10.7 // indirect github.com/lib/pq v1.10.7 // indirect
github.com/libp2p/go-buffer-pool v0.1.0 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect
github.com/lukehoban/go-outline v0.0.0-20161011150102-e78556874252 // indirect
github.com/magiconair/properties v1.8.7 // indirect github.com/magiconair/properties v1.8.7 // indirect
github.com/manifoldco/promptui v0.9.0 // indirect github.com/manifoldco/promptui v0.9.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-colorable v0.1.13 // indirect
@ -168,6 +169,7 @@ require (
github.com/rs/zerolog v1.29.0 // indirect github.com/rs/zerolog v1.29.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/spf13/afero v1.9.3 // indirect github.com/spf13/afero v1.9.3 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect

4
go.sum
View File

@ -865,6 +865,8 @@ github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0U
github.com/linxGnu/grocksdb v1.8.0 h1:H4L/LhP7GOMf1j17oQAElHgVlbEje2h14A8Tz9cM2BE= github.com/linxGnu/grocksdb v1.8.0 h1:H4L/LhP7GOMf1j17oQAElHgVlbEje2h14A8Tz9cM2BE=
github.com/linxGnu/grocksdb v1.8.0/go.mod h1:09CeBborffXhXdNpEcOeZrLKEnRtrZFEpFdPNI9Zjjg= github.com/linxGnu/grocksdb v1.8.0/go.mod h1:09CeBborffXhXdNpEcOeZrLKEnRtrZFEpFdPNI9Zjjg=
github.com/lucasjones/reggen v0.0.0-20180717132126-cdb49ff09d77/go.mod h1:5ELEyG+X8f+meRWHuqUOewBOhvHkl7M76pdGEansxW4= github.com/lucasjones/reggen v0.0.0-20180717132126-cdb49ff09d77/go.mod h1:5ELEyG+X8f+meRWHuqUOewBOhvHkl7M76pdGEansxW4=
github.com/lukehoban/go-outline v0.0.0-20161011150102-e78556874252 h1:D2VNityLQ1srKF+MSllSGQ4NwMci20llMkvVAmU2aCk=
github.com/lukehoban/go-outline v0.0.0-20161011150102-e78556874252/go.mod h1:O9bIJ6BRFBmP3AKTW8cqESVbauSmifSrRB/n9zq6x9Q=
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
@ -1093,6 +1095,8 @@ github.com/segmentio/kafka-go v0.2.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfP
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU= github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU=
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=

View File

@ -1,61 +0,0 @@
package client
import (
"context"
"time"
"github.com/0glabs/0g-chain/helper/da/light"
"github.com/pkg/errors"
)
type DaLightRpcClient interface {
Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error)
Destroy()
GetInstanceCount() int
}
type daLightClient struct {
maxInstance int
pool ConnectionPool
}
func NewDaLightClient(address string, instanceLimit int) DaLightRpcClient {
return &daLightClient{
maxInstance: instanceLimit,
pool: NewConnectionPool(address, instanceLimit, 10*time.Minute),
}
}
func (c *daLightClient) Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error) {
connection, err := c.pool.GetConnection()
if err != nil {
return false, errors.Wrap(err, "failed to connect to da light server")
}
defer c.pool.ReleaseConnection(connection)
req := &light.SampleRequest{
StreamId: streamId,
BatchHeaderHash: headerHash,
BlobIndex: blobIdx,
Times: times,
}
client := light.NewLightClient(connection)
reply, err := client.Sample(ctx, req)
if err != nil {
return false, errors.Wrap(err, "failed to sample from da light server")
}
return reply.Success, nil
}
func (c *daLightClient) Destroy() {
if c.pool != nil {
c.pool.Close()
c.pool = nil
}
}
func (c *daLightClient) GetInstanceCount() int {
return c.maxInstance
}

View File

@ -1,101 +0,0 @@
package client
import (
"errors"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials/insecure"
)
type ConnectionPool interface {
GetConnection() (*grpc.ClientConn, error)
ReleaseConnection(*grpc.ClientConn)
Close()
}
type connectionPoolImpl struct {
address string
maxSize int
timeout time.Duration
param grpc.ConnectParams
mu sync.Mutex
pool []*grpc.ClientConn
}
func NewConnectionPool(address string, maxSize int, timeout time.Duration) ConnectionPool {
return &connectionPoolImpl{
address: address,
maxSize: maxSize,
timeout: timeout,
param: grpc.ConnectParams{
Backoff: backoff.Config{
BaseDelay: 1.0 * time.Second,
Multiplier: 1.5,
Jitter: 0.2,
MaxDelay: 30 * time.Second,
},
MinConnectTimeout: 30 * time.Second,
},
pool: make([]*grpc.ClientConn, 0, maxSize),
}
}
func (p *connectionPoolImpl) GetConnection() (*grpc.ClientConn, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool == nil {
return nil, errors.New("connection pool is closed")
}
// Check if there's any available connection in the pool
if len(p.pool) > 0 {
conn := p.pool[0]
p.pool = p.pool[1:]
return conn, nil
}
// If the pool is empty, create a new connection
conn, err := grpc.Dial(p.address, grpc.WithBlock(),
grpc.WithConnectParams(p.param),
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, err
}
return conn, nil
}
func (p *connectionPoolImpl) ReleaseConnection(conn *grpc.ClientConn) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool != nil {
// If the pool is full, close the connection
if len(p.pool) >= p.maxSize {
conn.Close()
return
}
// Add the connection back to the pool
p.pool = append(p.pool, conn)
} else {
conn.Close()
}
}
func (p *connectionPoolImpl) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool != nil {
for _, conn := range p.pool {
conn.Close()
}
p.pool = nil
}
}

View File

@ -1,26 +0,0 @@
module github.com/0glabs/0g-chain/helper/da
go 1.20
require (
github.com/json-iterator/go v1.1.12
github.com/lesismal/nbio v1.5.4
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.32.0
google.golang.org/grpc v1.63.2
google.golang.org/protobuf v1.33.0
)
require (
github.com/lesismal/llib v1.1.13 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/stretchr/testify v1.8.4 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect
)

View File

@ -1,60 +0,0 @@
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/lesismal/llib v1.1.13 h1:+w1+t0PykXpj2dXQck0+p6vdC9/mnbEXHgUy/HXDGfE=
github.com/lesismal/llib v1.1.13/go.mod h1:70tFXXe7P1FZ02AU9l8LgSOK7d7sRrpnkUr3rd3gKSg=
github.com/lesismal/nbio v1.5.4 h1:fZ6FOVZOBm7nFuudYsq+WyHJuM2UNuPdlvF/1LVa6lo=
github.com/lesismal/nbio v1.5.4/go.mod h1:mvfYBAA1jmrafXf2XvkM28jWkMTfA5jGks+HKDBMmOc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.0.0-20210513122933-cd7d49e622d5/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY=
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View File

@ -1,397 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v4.25.3
// source: light/light.proto
package light
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// SampleRequest contains the blob to sample (by batch and blob index) and required sample times
type SampleRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
StreamId []byte `protobuf:"bytes,1,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
BatchHeaderHash []byte `protobuf:"bytes,2,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"`
BlobIndex uint32 `protobuf:"varint,3,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"`
Times uint32 `protobuf:"varint,4,opt,name=times,proto3" json:"times,omitempty"`
}
func (x *SampleRequest) Reset() {
*x = SampleRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SampleRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SampleRequest) ProtoMessage() {}
func (x *SampleRequest) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SampleRequest.ProtoReflect.Descriptor instead.
func (*SampleRequest) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{0}
}
func (x *SampleRequest) GetStreamId() []byte {
if x != nil {
return x.StreamId
}
return nil
}
func (x *SampleRequest) GetBatchHeaderHash() []byte {
if x != nil {
return x.BatchHeaderHash
}
return nil
}
func (x *SampleRequest) GetBlobIndex() uint32 {
if x != nil {
return x.BlobIndex
}
return 0
}
func (x *SampleRequest) GetTimes() uint32 {
if x != nil {
return x.Times
}
return 0
}
// SampleReply contains the sample result
type SampleReply struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`
}
func (x *SampleReply) Reset() {
*x = SampleReply{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SampleReply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SampleReply) ProtoMessage() {}
func (x *SampleReply) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SampleReply.ProtoReflect.Descriptor instead.
func (*SampleReply) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{1}
}
func (x *SampleReply) GetSuccess() bool {
if x != nil {
return x.Success
}
return false
}
type RetrieveRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
BatchHeaderHash []byte `protobuf:"bytes,1,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"`
BlobIndex uint32 `protobuf:"varint,2,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"`
}
func (x *RetrieveRequest) Reset() {
*x = RetrieveRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RetrieveRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RetrieveRequest) ProtoMessage() {}
func (x *RetrieveRequest) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RetrieveRequest.ProtoReflect.Descriptor instead.
func (*RetrieveRequest) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{2}
}
func (x *RetrieveRequest) GetBatchHeaderHash() []byte {
if x != nil {
return x.BatchHeaderHash
}
return nil
}
func (x *RetrieveRequest) GetBlobIndex() uint32 {
if x != nil {
return x.BlobIndex
}
return 0
}
type RetrieveReply struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Status bool `protobuf:"varint,1,opt,name=status,proto3" json:"status,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
}
func (x *RetrieveReply) Reset() {
*x = RetrieveReply{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RetrieveReply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RetrieveReply) ProtoMessage() {}
func (x *RetrieveReply) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RetrieveReply.ProtoReflect.Descriptor instead.
func (*RetrieveReply) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{3}
}
func (x *RetrieveReply) GetStatus() bool {
if x != nil {
return x.Status
}
return false
}
func (x *RetrieveReply) GetData() []byte {
if x != nil {
return x.Data
}
return nil
}
var File_light_light_proto protoreflect.FileDescriptor
var file_light_light_proto_rawDesc = []byte{
0x0a, 0x11, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x12, 0x05, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x22, 0x8d, 0x01, 0x0a, 0x0d, 0x53,
0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09,
0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52,
0x08, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74,
0x63, 0x68, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65,
0x72, 0x48, 0x61, 0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e,
0x64, 0x65, 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49,
0x6e, 0x64, 0x65, 0x78, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x18, 0x04, 0x20,
0x01, 0x28, 0x0d, 0x52, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x22, 0x27, 0x0a, 0x0b, 0x53, 0x61,
0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x63,
0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75, 0x63, 0x63,
0x65, 0x73, 0x73, 0x22, 0x5c, 0x0a, 0x0f, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f,
0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28,
0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x48, 0x61,
0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78,
0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49, 0x6e, 0x64, 0x65,
0x78, 0x22, 0x3b, 0x0a, 0x0d, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x70,
0x6c, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01,
0x28, 0x08, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61,
0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x79,
0x0a, 0x05, 0x4c, 0x69, 0x67, 0x68, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x53, 0x61, 0x6d, 0x70, 0x6c,
0x65, 0x12, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e,
0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x12, 0x3a, 0x0a,
0x08, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x12, 0x16, 0x2e, 0x6c, 0x69, 0x67, 0x68,
0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x1a, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65,
0x76, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74,
0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x67, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x30,
0x67, 0x2d, 0x64, 0x61, 0x74, 0x61, 0x2d, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x2f, 0x72, 0x75, 0x6e,
0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var (
file_light_light_proto_rawDescOnce sync.Once
file_light_light_proto_rawDescData = file_light_light_proto_rawDesc
)
func file_light_light_proto_rawDescGZIP() []byte {
file_light_light_proto_rawDescOnce.Do(func() {
file_light_light_proto_rawDescData = protoimpl.X.CompressGZIP(file_light_light_proto_rawDescData)
})
return file_light_light_proto_rawDescData
}
var file_light_light_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_light_light_proto_goTypes = []interface{}{
(*SampleRequest)(nil), // 0: light.SampleRequest
(*SampleReply)(nil), // 1: light.SampleReply
(*RetrieveRequest)(nil), // 2: light.RetrieveRequest
(*RetrieveReply)(nil), // 3: light.RetrieveReply
}
var file_light_light_proto_depIdxs = []int32{
0, // 0: light.Light.Sample:input_type -> light.SampleRequest
2, // 1: light.Light.Retrieve:input_type -> light.RetrieveRequest
1, // 2: light.Light.Sample:output_type -> light.SampleReply
3, // 3: light.Light.Retrieve:output_type -> light.RetrieveReply
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_light_light_proto_init() }
func file_light_light_proto_init() {
if File_light_light_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_light_light_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SampleRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SampleReply); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RetrieveRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RetrieveReply); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_light_light_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_light_light_proto_goTypes,
DependencyIndexes: file_light_light_proto_depIdxs,
MessageInfos: file_light_light_proto_msgTypes,
}.Build()
File_light_light_proto = out.File
file_light_light_proto_rawDesc = nil
file_light_light_proto_goTypes = nil
file_light_light_proto_depIdxs = nil
}

View File

@ -1,141 +0,0 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v4.25.3
// source: light/light.proto
package light
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// LightClient is the client API for Light service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type LightClient interface {
Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error)
Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error)
}
type lightClient struct {
cc grpc.ClientConnInterface
}
func NewLightClient(cc grpc.ClientConnInterface) LightClient {
return &lightClient{cc}
}
func (c *lightClient) Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error) {
out := new(SampleReply)
err := c.cc.Invoke(ctx, "/light.Light/Sample", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *lightClient) Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error) {
out := new(RetrieveReply)
err := c.cc.Invoke(ctx, "/light.Light/Retrieve", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LightServer is the server API for Light service.
// All implementations must embed UnimplementedLightServer
// for forward compatibility
type LightServer interface {
Sample(context.Context, *SampleRequest) (*SampleReply, error)
Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error)
mustEmbedUnimplementedLightServer()
}
// UnimplementedLightServer must be embedded to have forward compatible implementations.
type UnimplementedLightServer struct {
}
func (UnimplementedLightServer) Sample(context.Context, *SampleRequest) (*SampleReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Sample not implemented")
}
func (UnimplementedLightServer) Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Retrieve not implemented")
}
func (UnimplementedLightServer) mustEmbedUnimplementedLightServer() {}
// UnsafeLightServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to LightServer will
// result in compilation errors.
type UnsafeLightServer interface {
mustEmbedUnimplementedLightServer()
}
func RegisterLightServer(s grpc.ServiceRegistrar, srv LightServer) {
s.RegisterService(&Light_ServiceDesc, srv)
}
func _Light_Sample_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SampleRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LightServer).Sample(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/light.Light/Sample",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LightServer).Sample(ctx, req.(*SampleRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Light_Retrieve_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RetrieveRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LightServer).Retrieve(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/light.Light/Retrieve",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LightServer).Retrieve(ctx, req.(*RetrieveRequest))
}
return interceptor(ctx, in, info, handler)
}
// Light_ServiceDesc is the grpc.ServiceDesc for Light service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Light_ServiceDesc = grpc.ServiceDesc{
ServiceName: "light.Light",
HandlerType: (*LightServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Sample",
Handler: _Light_Sample_Handler,
},
{
MethodName: "Retrieve",
Handler: _Light_Retrieve_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "light/light.proto",
}

View File

@ -1,89 +0,0 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/0glabs/0g-chain/helper/da/service"
"github.com/0glabs/0g-chain/helper/da/types"
"github.com/lesismal/nbio/nbhttp"
"github.com/lesismal/nbio/nbhttp/websocket"
)
const (
subscribeMsg = "{\"jsonrpc\":\"2.0\",\"method\":\"subscribe\",\"id\":1,\"params\":{\"query\":\"tm.event='Tx'\"}}"
)
var (
rpcAddress = flag.String("rpc-address", "34.214.2.28:32001", "address of da-light rpc server")
wsAddress = flag.String("ws-address", "127.0.0.1:26657", "address of emvos ws server")
relativePath = flag.String("relative-path", "", "relative path of evmosd")
account = flag.String("account", "", "account to run evmosd cli")
keyring = flag.String("keyring", "", "keyring to run evmosd cli")
homePath = flag.String("home", "", "home path of evmosd node")
)
func newUpgrader() *websocket.Upgrader {
u := websocket.NewUpgrader()
u.OnMessage(func(c *websocket.Conn, messageType websocket.MessageType, data []byte) {
log.Println("onEcho:", string(data))
ctx := context.WithValue(context.Background(), types.DA_RPC_ADDRESS, *rpcAddress)
ctx = context.WithValue(ctx, types.NODE_CLI_RELATIVE_PATH, *relativePath)
ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_ACCOUNT, *account)
ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_KEYRING, *keyring)
ctx = context.WithValue(ctx, types.NODE_HOME_PATH, *homePath)
go func() { service.OnMessage(ctx, c, messageType, data) }()
})
u.OnClose(func(c *websocket.Conn, err error) {
fmt.Println("OnClose:", c.RemoteAddr().String(), err)
service.OnClose()
})
return u
}
func main() {
flag.Parse()
engine := nbhttp.NewEngine(nbhttp.Config{})
err := engine.Start()
if err != nil {
fmt.Printf("nbio.Start failed: %v\n", err)
return
}
go func() {
u := url.URL{Scheme: "ws", Host: *wsAddress, Path: "/websocket"}
dialer := &websocket.Dialer{
Engine: engine,
Upgrader: newUpgrader(),
DialTimeout: time.Second * 3,
}
c, res, err := dialer.Dial(u.String(), nil)
if err != nil {
if res != nil && res.Body != nil {
bReason, _ := io.ReadAll(res.Body)
fmt.Printf("dial failed: %v, reason: %v\n", err, string(bReason))
} else {
fmt.Printf("dial failed: %v\n", err)
}
return
}
c.WriteMessage(websocket.TextMessage, []byte(subscribeMsg))
}()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
<-interrupt
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
engine.Shutdown(ctx)
}

View File

@ -1,33 +0,0 @@
syntax = "proto3";
package light;
option go_package = "proto/light";
service Light {
rpc Sample(SampleRequest) returns (SampleReply) {}
rpc Retrieve(RetrieveRequest) returns (RetrieveReply) {}
}
// SampleRequest contains the blob to sample (by batch and blob index) and required sample times
message SampleRequest {
bytes stream_id = 1;
bytes batch_header_hash = 2;
uint32 blob_index = 3;
uint32 times = 4;
}
// SampleReply contains the sample result
message SampleReply {
bool success = 1;
}
message RetrieveRequest {
bytes batch_header_hash = 1;
uint32 blob_index = 2;
}
message RetrieveReply {
bool status = 1;
bytes data = 2;
}

View File

@ -1,186 +0,0 @@
package service
import (
"context"
"encoding/hex"
"os"
"os/exec"
"strconv"
"strings"
"github.com/0glabs/0g-chain/helper/da/client"
"github.com/0glabs/0g-chain/helper/da/types"
"github.com/0glabs/0g-chain/helper/da/utils/sizedw8grp"
jsoniter "github.com/json-iterator/go"
"github.com/lesismal/nbio/nbhttp/websocket"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
const (
defaultClientInstance = 10
)
var rpcClient client.DaLightRpcClient
func OnMessage(ctx context.Context, c *websocket.Conn, messageType websocket.MessageType, data []byte) {
if messageType == websocket.TextMessage {
rawMsg := unwrapJsonRpc(data)
if verifyQuery(rawMsg) {
eventStr := jsoniter.Get(rawMsg, "events").ToString()
events := map[string][]string{}
if err := jsoniter.UnmarshalFromString(eventStr, &events); err == nil {
dasRequestMap := make(map[string]string, 4)
for key, val := range events {
if strings.HasPrefix(key, "das_request.") {
dasRequestMap[strings.ReplaceAll(key, "das_request.", "")] = val[0]
}
}
if len(dasRequestMap) == 4 {
rid, _ := strconv.ParseUint(dasRequestMap["request_id"], 10, 64)
numBlobs, _ := strconv.ParseUint(dasRequestMap["num_blobs"], 10, 64)
req := types.DASRequest{
RequestId: rid,
StreamId: dasRequestMap["stream_id"],
BatchHeaderHash: dasRequestMap["batch_header_hash"],
NumBlobs: numBlobs,
}
err := handleDasRequest(ctx, req)
if err != nil {
log.Err(err).Msgf("failed to handle das request: %v, %v", req, err)
} else {
log.Info().Msgf("successfully handled das request: %v", req)
}
}
}
}
} else {
// TODO: handle other message
}
}
func OnClose() {
if rpcClient != nil {
rpcClient.Destroy()
rpcClient = nil
}
}
func unwrapJsonRpc(data []byte) []byte {
result := jsoniter.Get(data, "result")
if 0 < len(result.Keys()) {
return []byte(result.ToString())
}
return []byte{}
}
func verifyQuery(data []byte) bool {
if len(data) > 0 {
return jsoniter.Get(data, "query").ToString() == "tm.event='Tx'"
}
return false
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func handleDasRequest(ctx context.Context, request types.DASRequest) error {
if rpcClient == nil {
addrVal := ctx.Value(types.DA_RPC_ADDRESS)
if addrVal == nil {
return errors.New("da light service address not found in context")
}
limit := ctx.Value(types.INSTANCE_LIMIT)
if limit == nil {
limit = defaultClientInstance
}
rpcClient = client.NewDaLightClient(addrVal.(string), limit.(int))
}
streamID, err := hex.DecodeString(request.StreamId)
if err != nil {
return err
}
batchHeaderHash, err := hex.DecodeString(request.BatchHeaderHash)
if err != nil {
return err
}
result := make(chan bool, request.NumBlobs)
taskCnt := min(rpcClient.GetInstanceCount(), int(request.NumBlobs))
wg := sizedw8grp.New(taskCnt)
for i := uint64(0); i < request.NumBlobs; i++ {
wg.Add()
go func(idx uint64) {
defer wg.Done()
ret, err := rpcClient.Sample(ctx, streamID, batchHeaderHash, uint32(idx), 1)
if err != nil {
log.Err(err).Msgf("failed to sample data availability with blob index %d", idx)
result <- false
} else {
log.Info().Msgf("sample result for blob index %d: %v", idx, ret)
result <- ret
}
}(i)
}
wg.Wait()
close(result)
finalResult := true
for val := range result {
if !val {
finalResult = false
break
}
}
return runEvmosdCliReportDasResult(ctx, request.RequestId, finalResult)
}
func runEvmosdCliReportDasResult(ctx context.Context, requestId uint64, result bool) error {
relativePath := ctx.Value(types.NODE_CLI_RELATIVE_PATH)
if relativePath == nil {
return errors.New("relativePath not found in context")
}
account := ctx.Value(types.NODE_CLI_EXEC_ACCOUNT)
if account == nil {
return errors.New("account not found in context")
}
args := []string{
"tx",
"das",
"report-das-result",
strconv.FormatUint(requestId, 10),
strconv.FormatBool(result),
"--from", account.(string),
"--gas-prices", "7678500neuron", // TODO: use args to set gas prices
}
homePath := ctx.Value(types.NODE_HOME_PATH)
if len(homePath.(string)) > 0 {
args = append(args, "--home", homePath.(string))
}
keyring := ctx.Value(types.NODE_CLI_EXEC_KEYRING)
if len(keyring.(string)) > 0 {
args = append(args, "--keyring-backend", keyring.(string))
}
cmdStr := relativePath.(string) + "0gchaind"
cmd := exec.Command(cmdStr, append(args, "-y")...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

View File

@ -1,8 +0,0 @@
package types
type DASRequest struct {
RequestId uint64 `json:"request_id"`
StreamId string `json:"stream_id"`
BatchHeaderHash string `json:"batch_header_hash"`
NumBlobs uint64 `json:"num_blobs"`
}

View File

@ -1,10 +0,0 @@
package types
const (
DA_RPC_ADDRESS = "rpc_address"
INSTANCE_LIMIT = "instance_limit"
NODE_CLI_RELATIVE_PATH = "relative_path"
NODE_CLI_EXEC_ACCOUNT = "node_exec_account"
NODE_CLI_EXEC_KEYRING = "node_exec_keyring"
NODE_HOME_PATH = "home_path"
)

View File

@ -1,51 +0,0 @@
package sizedw8grp
import (
"context"
"math"
"sync"
)
type SizedWaitGroup struct {
Size int
current chan struct{}
wg sync.WaitGroup
}
func New(limit int) SizedWaitGroup {
size := math.MaxInt32
if limit > 0 {
size = limit
}
return SizedWaitGroup{
Size: size,
current: make(chan struct{}, size),
wg: sync.WaitGroup{},
}
}
func (s *SizedWaitGroup) Add() {
_ = s.AddWithContext(context.Background())
}
func (s *SizedWaitGroup) AddWithContext(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case s.current <- struct{}{}:
break
}
s.wg.Add(1)
return nil
}
func (s *SizedWaitGroup) Done() {
<-s.current
s.wg.Done()
}
func (s *SizedWaitGroup) Wait() {
s.wg.Wait()
}

View File

@ -24,7 +24,7 @@ DATA=~/.0gchain
# remove any old state and config # remove any old state and config
rm -rf $DATA rm -rf $DATA
BINARY=0gchaind BINARY=./.build/0gchaind
# Create new data directory, overwriting any that alread existed # Create new data directory, overwriting any that alread existed
chainID="zgchain_8888-1" chainID="zgchain_8888-1"

View File

@ -5,6 +5,7 @@ import (
"time" "time"
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -41,7 +42,7 @@ func TestResetPeriodVestingAccount_NoVestingPeriods(t *testing.T) {
} }
func TestResetPeriodVestingAccount_SingleVestingPeriod_Vested(t *testing.T) { func TestResetPeriodVestingAccount_SingleVestingPeriod_Vested(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))) balance := sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{ periods := vestingtypes.Periods{
@ -64,7 +65,7 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_Vested(t *testing.T) {
} }
func TestResetPeriodVestingAccount_SingleVestingPeriod_Vesting(t *testing.T) { func TestResetPeriodVestingAccount_SingleVestingPeriod_Vesting(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))) balance := sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{ periods := vestingtypes.Periods{
@ -97,7 +98,7 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_Vesting(t *testing.T) {
} }
func TestResetPeriodVestingAccount_SingleVestingPeriod_ExactStartTime(t *testing.T) { func TestResetPeriodVestingAccount_SingleVestingPeriod_ExactStartTime(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))) balance := sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{ periods := vestingtypes.Periods{
@ -125,25 +126,25 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_ExactStartTime(t *testing
} }
func TestResetPeriodVestingAccount_MultiplePeriods(t *testing.T) { func TestResetPeriodVestingAccount_MultiplePeriods(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(4e6))) balance := sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(4e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{ periods := vestingtypes.Periods{
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // -15 days - vested Length: 15 * 24 * 60 * 60, // -15 days - vested
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +15 days - vesting Length: 15 * 24 * 60 * 60, // +15 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +30 days - vesting Length: 15 * 24 * 60 * 60, // +30 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
} }
@ -159,36 +160,36 @@ func TestResetPeriodVestingAccount_MultiplePeriods(t *testing.T) {
expectedPeriods := []vestingtypes.Period{ expectedPeriods := []vestingtypes.Period{
{ {
Length: 15 * 24 * 60 * 60, // 15 days Length: 15 * 24 * 60 * 60, // 15 days
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
{ {
Length: 15 * 24 * 60 * 60, // 15 days Length: 15 * 24 * 60 * 60, // 15 days
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
} }
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(2e6))), vacc.OriginalVesting, "expected original vesting to be updated") assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(2e6))), vacc.OriginalVesting, "expected original vesting to be updated")
assert.Equal(t, newVestingStartTime.Unix(), vacc.StartTime, "expected vesting start time to be updated") assert.Equal(t, newVestingStartTime.Unix(), vacc.StartTime, "expected vesting start time to be updated")
assert.Equal(t, expectedEndtime, vacc.EndTime, "expected vesting end time end at last period") assert.Equal(t, expectedEndtime, vacc.EndTime, "expected vesting end time end at last period")
assert.Equal(t, expectedPeriods, vacc.VestingPeriods, "expected vesting periods to be updated") assert.Equal(t, expectedPeriods, vacc.VestingPeriods, "expected vesting periods to be updated")
} }
func TestResetPeriodVestingAccount_DelegatedVesting_GreaterThanVesting(t *testing.T) { func TestResetPeriodVestingAccount_DelegatedVesting_GreaterThanVesting(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(3e6))) balance := sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(3e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{ periods := vestingtypes.Periods{
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // -15 days - vested Length: 15 * 24 * 60 * 60, // -15 days - vested
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +15 days - vesting Length: 15 * 24 * 60 * 60, // +15 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
} }
@ -198,35 +199,35 @@ func TestResetPeriodVestingAccount_DelegatedVesting_GreaterThanVesting(t *testin
newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour) newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour)
ResetPeriodicVestingAccount(vacc, newVestingStartTime) ResetPeriodicVestingAccount(vacc, newVestingStartTime)
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(2e6))), vacc.DelegatedFree, "expected delegated free to be updated") assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(2e6))), vacc.DelegatedFree, "expected delegated free to be updated")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be updated") assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be updated")
} }
func TestResetPeriodVestingAccount_DelegatedVesting_LessThanVested(t *testing.T) { func TestResetPeriodVestingAccount_DelegatedVesting_LessThanVested(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(3e6))) balance := sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(3e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{ periods := vestingtypes.Periods{
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // -15 days - vested Length: 15 * 24 * 60 * 60, // -15 days - vested
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
vestingtypes.Period{ vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +15 days - vesting Length: 15 * 24 * 60 * 60, // +15 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))),
}, },
} }
vacc := createVestingAccount(balance, vestingStartTime, periods) vacc := createVestingAccount(balance, vestingStartTime, periods)
vacc.TrackDelegation(vestingStartTime, balance, sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6)))) vacc.TrackDelegation(vestingStartTime, balance, sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))))
newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour) newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour)
ResetPeriodicVestingAccount(vacc, newVestingStartTime) ResetPeriodicVestingAccount(vacc, newVestingStartTime)
assert.Equal(t, sdk.Coins(nil), vacc.DelegatedFree, "expected delegrated free to be unmodified") assert.Equal(t, sdk.Coins(nil), vacc.DelegatedFree, "expected delegrated free to be unmodified")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be unmodified") assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be unmodified")
} }

View File

@ -1,37 +0,0 @@
syntax = "proto3";
package zgc.das.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
option go_package = "github.com/0glabs/0g-chain/x/das/v1/types";
message Params {}
// GenesisState defines the das module's genesis state.
message GenesisState {
option (gogoproto.goproto_getters) = false;
Params params = 1 [(gogoproto.nullable) = false];
uint64 next_request_id = 2 [(gogoproto.customname) = "NextRequestID"];
repeated DASRequest requests = 3 [(gogoproto.nullable) = false];
repeated DASResponse responses = 4 [(gogoproto.nullable) = false];
}
message DASRequest {
uint64 id = 1 [(gogoproto.customname) = "ID"];
bytes stream_id = 2 [(gogoproto.customname) = "StreamID"];
bytes batch_header_hash = 3;
uint32 num_blobs = 4;
}
message DASResponse {
uint64 id = 1 [(gogoproto.customname) = "ID"];
bytes sampler = 2 [
(cosmos_proto.scalar) = "cosmos.AddressBytes",
(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.ValAddress"
];
repeated bool results = 3;
}

View File

@ -1,24 +0,0 @@
syntax = "proto3";
package zgc.das.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
option go_package = "github.com/0glabs/0g-chain/x/das/v1/types";
option (gogoproto.goproto_getters_all) = false;
// Query defines the gRPC querier service for the das module
service Query {
rpc NextRequestID(QueryNextRequestIDRequest) returns (QueryNextRequestIDResponse) {
option (google.api.http).get = "/0gchain/das/v1/next-request-id";
}
}
message QueryNextRequestIDRequest {}
message QueryNextRequestIDResponse {
uint64 next_request_id = 1 [(gogoproto.customname) = "NextRequestID"];
}

View File

@ -1,35 +0,0 @@
syntax = "proto3";
package zgc.das.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "zgc/das/v1/genesis.proto";
option go_package = "github.com/0glabs/0g-chain/x/das/v1/types";
option (gogoproto.goproto_getters_all) = false;
// Msg defines the das Msg service
service Msg {
rpc RequestDAS(MsgRequestDAS) returns (MsgRequestDASResponse);
rpc ReportDASResult(MsgReportDASResult) returns (MsgReportDASResultResponse);
}
message MsgRequestDAS {
string requester = 1 [(gogoproto.moretags) = "Requester"];
string stream_id = 2 [(gogoproto.customname) = "StreamID"];
string batch_header_hash = 3;
uint32 num_blobs = 4;
}
message MsgRequestDASResponse {
uint64 request_id = 1 [(gogoproto.customname) = "RequestID"];
}
message MsgReportDASResult {
uint64 request_id = 1 [(gogoproto.customname) = "RequestID"];
string sampler = 2;
repeated bool results = 3;
}
message MsgReportDASResultResponse {}

View File

@ -4,7 +4,6 @@ package zgc.dasigners.v1;
import "cosmos_proto/cosmos.proto"; import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto"; import "gogoproto/gogo.proto";
import "google/protobuf/any.proto"; import "google/protobuf/any.proto";
import "zgc/das/v1/genesis.proto";
import "zgc/dasigners/v1/dasigners.proto"; import "zgc/dasigners/v1/dasigners.proto";
option go_package = "github.com/0glabs/0g-chain/x/dasigners/v1/types"; option go_package = "github.com/0glabs/0g-chain/x/dasigners/v1/types";

View File

@ -13,7 +13,7 @@ message ConversionPair {
option (gogoproto.goproto_getters) = false; option (gogoproto.goproto_getters) = false;
// ERC20 address of the token on the 0gChain EVM // ERC20 address of the token on the 0gChain EVM
bytes zgChain_erc20_address = 1 [ bytes zgchain_erc20_address = 1 [
(gogoproto.customname) = "ZgChainERC20Address", (gogoproto.customname) = "ZgChainERC20Address",
(gogoproto.casttype) = "HexBytes" (gogoproto.casttype) = "HexBytes"
]; ];

View File

@ -44,7 +44,7 @@ message MsgConvertERC20ToCoin {
// 0gChain bech32 address that will receive the converted sdk.Coin. // 0gChain bech32 address that will receive the converted sdk.Coin.
string receiver = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; string receiver = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
// EVM 0x hex address of the ERC20 contract. // EVM 0x hex address of the ERC20 contract.
string zgChain_erc20_address = 3 [(gogoproto.customname) = "ZgChainERC20Address"]; string zgchain_erc20_address = 3 [(gogoproto.customname) = "ZgChainERC20Address"];
// ERC20 token amount to convert. // ERC20 token amount to convert.
string amount = 4 [ string amount = 4 [
(cosmos_proto.scalar) = "cosmos.Int", (cosmos_proto.scalar) = "cosmos.Int",

View File

@ -12,6 +12,7 @@ import (
ethtypes "github.com/ethereum/go-ethereum/core/types" ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/tests/e2e/testutil" "github.com/0glabs/0g-chain/tests/e2e/testutil"
"github.com/0glabs/0g-chain/tests/util" "github.com/0glabs/0g-chain/tests/util"
evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
@ -63,7 +64,7 @@ func (suite *IntegrationTestSuite) setupAccountWithCosmosCoinERC20Balance(
tx := util.ZgChainMsgRequest{ tx := util.ZgChainMsgRequest{
Msgs: []sdk.Msg{&msg}, Msgs: []sdk.Msg{&msg},
GasLimit: 4e5, GasLimit: 4e5,
FeeAmount: sdk.NewCoins(a0gi(big.NewInt(400))), FeeAmount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(400)),
Data: "converting sdk coin to erc20", Data: "converting sdk coin to erc20",
} }
res := user.SignAndBroadcastZgChainTx(tx) res := user.SignAndBroadcastZgChainTx(tx)
@ -102,7 +103,7 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoinsToFromERC20() {
tx := util.ZgChainMsgRequest{ tx := util.ZgChainMsgRequest{
Msgs: []sdk.Msg{&convertToErc20Msg}, Msgs: []sdk.Msg{&convertToErc20Msg},
GasLimit: 2e6, GasLimit: 2e6,
FeeAmount: sdk.NewCoins(a0gi(big.NewInt(2000))), FeeAmount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(2000)),
Data: "converting sdk coin to erc20", Data: "converting sdk coin to erc20",
} }
res := user.SignAndBroadcastZgChainTx(tx) res := user.SignAndBroadcastZgChainTx(tx)
@ -144,7 +145,7 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoinsToFromERC20() {
tx = util.ZgChainMsgRequest{ tx = util.ZgChainMsgRequest{
Msgs: []sdk.Msg{&convertFromErc20Msg}, Msgs: []sdk.Msg{&convertFromErc20Msg},
GasLimit: 2e5, GasLimit: 2e5,
FeeAmount: sdk.NewCoins(a0gi(big.NewInt(200))), FeeAmount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(200)),
Data: "converting erc20 to cosmos coin", Data: "converting erc20 to cosmos coin",
} }
res = user.SignAndBroadcastZgChainTx(tx) res = user.SignAndBroadcastZgChainTx(tx)
@ -183,7 +184,7 @@ func (suite *IntegrationTestSuite) TestEIP712ConvertCosmosCoinsToFromERC20() {
user, user,
suite.ZgChain, suite.ZgChain,
2e6, 2e6,
sdk.NewCoins(a0gi(big.NewInt(1e4))), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e4)),
[]sdk.Msg{&convertToErc20Msg}, []sdk.Msg{&convertToErc20Msg},
"this is a memo", "this is a memo",
).GetTx() ).GetTx()
@ -237,7 +238,7 @@ func (suite *IntegrationTestSuite) TestEIP712ConvertCosmosCoinsToFromERC20() {
user, user,
suite.ZgChain, suite.ZgChain,
2e5, 2e5,
sdk.NewCoins(a0gi(big.NewInt(200))), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(200)),
[]sdk.Msg{&convertFromErc20Msg}, []sdk.Msg{&convertFromErc20Msg},
"", "",
).GetTx() ).GetTx()
@ -331,7 +332,7 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoins_ERC20Magic() {
"cosmo-coin-converter-complex-alice", initialAliceAmount, "cosmo-coin-converter-complex-alice", initialAliceAmount,
) )
gasMoney := sdk.NewCoins(a0gi(big.NewInt(1e5))) gasMoney := sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e5))
bob := suite.ZgChain.NewFundedAccount("cosmo-coin-converter-complex-bob", gasMoney) bob := suite.ZgChain.NewFundedAccount("cosmo-coin-converter-complex-bob", gasMoney)
amount := big.NewInt(1e3) // test assumes this is half of alice's balance. amount := big.NewInt(1e3) // test assumes this is half of alice's balance.
@ -412,7 +413,7 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoins_ERC20Magic() {
convertTx := util.ZgChainMsgRequest{ convertTx := util.ZgChainMsgRequest{
Msgs: []sdk.Msg{&convertMsg}, Msgs: []sdk.Msg{&convertMsg},
GasLimit: 2e5, GasLimit: 2e5,
FeeAmount: sdk.NewCoins(a0gi(big.NewInt(200))), FeeAmount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(200)),
Data: "bob converts his new erc20 to an sdk.Coin", Data: "bob converts his new erc20 to an sdk.Coin",
} }
convertRes := bob.SignAndBroadcastZgChainTx(convertTx) convertRes := bob.SignAndBroadcastZgChainTx(convertTx)

View File

@ -11,7 +11,7 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/tests/e2e/contracts/greeter" "github.com/0glabs/0g-chain/tests/e2e/contracts/greeter"
"github.com/0glabs/0g-chain/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
@ -20,7 +20,7 @@ func (suite *IntegrationTestSuite) TestEthCallToGreeterContract() {
// this test manipulates state of the Greeter contract which means other tests shouldn't use it. // this test manipulates state of the Greeter contract which means other tests shouldn't use it.
// setup funded account to interact with contract // setup funded account to interact with contract
user := suite.ZgChain.NewFundedAccount("greeter-contract-user", sdk.NewCoins(a0gi(big.NewInt(1e6)))) user := suite.ZgChain.NewFundedAccount("greeter-contract-user", sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e6)))
greeterAddr := suite.ZgChain.ContractAddrs["greeter"] greeterAddr := suite.ZgChain.ContractAddrs["greeter"]
contract, err := greeter.NewGreeter(greeterAddr, suite.ZgChain.EvmClient) contract, err := greeter.NewGreeter(greeterAddr, suite.ZgChain.EvmClient)
@ -63,12 +63,12 @@ func (suite *IntegrationTestSuite) TestEthCallToErc20() {
func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() { func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() {
// create new funded account // create new funded account
sender := suite.ZgChain.NewFundedAccount("eip712-msgSend", sdk.NewCoins(a0gi(big.NewInt(2e4)))) sender := suite.ZgChain.NewFundedAccount("eip712-msgSend", sdk.NewCoins(chaincfg.MakeCoinForGasDenom(2e4)))
receiver := app.RandomAddress() receiver := app.RandomAddress()
// setup message for sending some a0gi to random receiver // setup message for sending some gas denom to random receiver
msgs := []sdk.Msg{ msgs := []sdk.Msg{
banktypes.NewMsgSend(sender.SdkAddress, receiver, sdk.NewCoins(a0gi(big.NewInt(1e3)))), banktypes.NewMsgSend(sender.SdkAddress, receiver, sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e3))),
} }
// create tx // create tx
@ -76,7 +76,7 @@ func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() {
sender, sender,
suite.ZgChain, suite.ZgChain,
1e6, 1e6,
sdk.NewCoins(a0gi(big.NewInt(1e4))), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e4)),
msgs, msgs,
"this is a memo", "this is a memo",
).GetTx() ).GetTx()
@ -95,10 +95,10 @@ func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() {
_, err = util.WaitForSdkTxCommit(suite.ZgChain.Tx, res.TxResponse.TxHash, 6*time.Second) _, err = util.WaitForSdkTxCommit(suite.ZgChain.Tx, res.TxResponse.TxHash, 6*time.Second)
suite.NoError(err) suite.NoError(err)
// check that the message was processed & the a0gi is transferred. // check that the message was processed & the gas denom is transferred.
balRes, err := suite.ZgChain.Bank.Balance(context.Background(), &banktypes.QueryBalanceRequest{ balRes, err := suite.ZgChain.Bank.Balance(context.Background(), &banktypes.QueryBalanceRequest{
Address: receiver.String(), Address: receiver.String(),
Denom: "ua0gi", Denom: chaincfg.GasDenom,
}) })
suite.NoError(err) suite.NoError(err)
suite.Equal(sdk.NewInt(1e3), balRes.Balance.Amount) suite.Equal(sdk.NewInt(1e3), balRes.Balance.Amount)
@ -113,7 +113,7 @@ func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() {
// sdkDenom := suite.DeployedErc20.CosmosDenom // sdkDenom := suite.DeployedErc20.CosmosDenom
// // create new funded account // // create new funded account
// depositor := suite.ZgChain.NewFundedAccount("eip712-lend-depositor", sdk.NewCoins(a0gi(big.NewInt(1e5))) // depositor := suite.ZgChain.NewFundedAccount("eip712-lend-depositor", sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e5)))
// // give them erc20 balance to deposit // // give them erc20 balance to deposit
// fundRes := suite.FundZgChainErc20Balance(depositor.EvmAddress, amount.BigInt()) // fundRes := suite.FundZgChainErc20Balance(depositor.EvmAddress, amount.BigInt())
// suite.NoError(fundRes.Err) // suite.NoError(fundRes.Err)
@ -143,7 +143,7 @@ func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() {
// depositor, // depositor,
// suite.ZgChain, // suite.ZgChain,
// 1e6, // 1e6,
// sdk.NewCoins(a0gi(big.NewInt(1e4)), // sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e4)),
// msgs, // msgs,
// "doing the USDT Earn workflow! erc20 -> sdk.Coin -> USDX hard deposit", // "doing the USDT Earn workflow! erc20 -> sdk.Coin -> USDX hard deposit",
// ).GetTx() // ).GetTx()
@ -189,7 +189,7 @@ func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() {
// withdrawAndConvertBack := util.ZgChainMsgRequest{ // withdrawAndConvertBack := util.ZgChainMsgRequest{
// Msgs: []sdk.Msg{&withdraw, &convertBack}, // Msgs: []sdk.Msg{&withdraw, &convertBack},
// GasLimit: 1e6, // GasLimit: 1e6,
// FeeAmount: sdk.NewCoins(a0gi(big.NewInt(1000)), // FeeAmount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1000)),
// Data: "withdrawing from mint & converting back to erc20", // Data: "withdrawing from mint & converting back to erc20",
// } // }
// lastRes := depositor.SignAndBroadcastZgChainTx(withdrawAndConvertBack) // lastRes := depositor.SignAndBroadcastZgChainTx(withdrawAndConvertBack)

View File

@ -13,6 +13,7 @@ import (
ethtypes "github.com/ethereum/go-ethereum/core/types" ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
@ -23,10 +24,10 @@ func (suite *IntegrationTestSuite) TestEthGasPriceReturnsMinFee() {
minGasPrices, err := getMinFeeFromAppToml(util.ZgChainHomePath()) minGasPrices, err := getMinFeeFromAppToml(util.ZgChainHomePath())
suite.NoError(err) suite.NoError(err)
// evm uses neuron, get neuron min fee // evm uses evm denom, get evm denom min fee
evmMinGas := minGasPrices.AmountOf("neuron").TruncateInt().BigInt() evmMinGas := minGasPrices.AmountOf(chaincfg.EvmDenom).TruncateInt().BigInt()
// returns eth_gasPrice, units in a0gi // returns eth_gasPrice, units in gas denom
gasPrice, err := suite.ZgChain.EvmClient.SuggestGasPrice(context.Background()) gasPrice, err := suite.ZgChain.EvmClient.SuggestGasPrice(context.Background())
suite.NoError(err) suite.NoError(err)
@ -37,13 +38,13 @@ func (suite *IntegrationTestSuite) TestEvmRespectsMinFee() {
suite.SkipIfKvtoolDisabled() suite.SkipIfKvtoolDisabled()
// setup sender & receiver // setup sender & receiver
sender := suite.ZgChain.NewFundedAccount("evm-min-fee-test-sender", sdk.NewCoins(a0gi(big.NewInt(1e3)))) sender := suite.ZgChain.NewFundedAccount("evm-min-fee-test-sender", sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e3)))
randoReceiver := util.SdkToEvmAddress(app.RandomAddress()) randoReceiver := util.SdkToEvmAddress(app.RandomAddress())
// get min gas price for evm (from app.toml) // get min gas price for evm (from app.toml)
minFees, err := getMinFeeFromAppToml(util.ZgChainHomePath()) minFees, err := getMinFeeFromAppToml(util.ZgChainHomePath())
suite.NoError(err) suite.NoError(err)
minGasPrice := minFees.AmountOf("neuron").TruncateInt() minGasPrice := minFees.AmountOf(chaincfg.EvmDenom).TruncateInt()
// attempt tx with less than min gas price (min fee - 1) // attempt tx with less than min gas price (min fee - 1)
tooLowGasPrice := minGasPrice.Sub(sdk.OneInt()).BigInt() tooLowGasPrice := minGasPrice.Sub(sdk.OneInt()).BigInt()

View File

@ -19,18 +19,15 @@ import (
emtypes "github.com/evmos/ethermint/types" emtypes "github.com/evmos/ethermint/types"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/tests/e2e/testutil" "github.com/0glabs/0g-chain/tests/e2e/testutil"
"github.com/0glabs/0g-chain/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
var ( var (
minEvmGasPrice = big.NewInt(1e10) // neuron minEvmGasPrice = big.NewInt(1e10) // evm denom
) )
func a0gi(amt *big.Int) sdk.Coin {
return sdk.NewCoin("ua0gi", sdkmath.NewIntFromBigInt(amt))
}
type IntegrationTestSuite struct { type IntegrationTestSuite struct {
testutil.E2eTestSuite testutil.E2eTestSuite
} }
@ -57,7 +54,7 @@ func (suite *IntegrationTestSuite) TestChainID() {
// example test that funds a new account & queries its balance // example test that funds a new account & queries its balance
func (suite *IntegrationTestSuite) TestFundedAccount() { func (suite *IntegrationTestSuite) TestFundedAccount() {
funds := a0gi(big.NewInt(1e3)) funds := chaincfg.MakeCoinForGasDenom(1e3)
acc := suite.ZgChain.NewFundedAccount("example-acc", sdk.NewCoins(funds)) acc := suite.ZgChain.NewFundedAccount("example-acc", sdk.NewCoins(funds))
// check that the sdk & evm signers are for the same account // check that the sdk & evm signers are for the same account
@ -66,21 +63,21 @@ func (suite *IntegrationTestSuite) TestFundedAccount() {
// check balance via SDK query // check balance via SDK query
res, err := suite.ZgChain.Bank.Balance(context.Background(), banktypes.NewQueryBalanceRequest( res, err := suite.ZgChain.Bank.Balance(context.Background(), banktypes.NewQueryBalanceRequest(
acc.SdkAddress, "ua0gi", acc.SdkAddress, chaincfg.GasDenom,
)) ))
suite.NoError(err) suite.NoError(err)
suite.Equal(funds, *res.Balance) suite.Equal(funds, *res.Balance)
// check balance via EVM query // check balance via EVM query
neuronBal, err := suite.ZgChain.EvmClient.BalanceAt(context.Background(), acc.EvmAddress, nil) evmDenomBal, err := suite.ZgChain.EvmClient.BalanceAt(context.Background(), acc.EvmAddress, nil)
suite.NoError(err) suite.NoError(err)
suite.Equal(funds.Amount.MulRaw(1e12).BigInt(), neuronBal) suite.Equal(funds.Amount.MulRaw(1e12).BigInt(), evmDenomBal)
} }
// example test that signs & broadcasts an EVM tx // example test that signs & broadcasts an EVM tx
func (suite *IntegrationTestSuite) TestTransferOverEVM() { func (suite *IntegrationTestSuite) TestTransferOverEVM() {
// fund an account that can perform the transfer // fund an account that can perform the transfer
initialFunds := a0gi(big.NewInt(1e6)) // 1 A0GI initialFunds := chaincfg.MakeCoinForGasDenom(1e6) // 1 (gas denom)
acc := suite.ZgChain.NewFundedAccount("evm-test-transfer", sdk.NewCoins(initialFunds)) acc := suite.ZgChain.NewFundedAccount("evm-test-transfer", sdk.NewCoins(initialFunds))
// get a rando account to send 0gchain to // get a rando account to send 0gchain to
@ -92,10 +89,10 @@ func (suite *IntegrationTestSuite) TestTransferOverEVM() {
suite.NoError(err) suite.NoError(err)
suite.Equal(uint64(0), nonce) // sanity check. the account should have no prior txs suite.Equal(uint64(0), nonce) // sanity check. the account should have no prior txs
// transfer a0gi over EVM // transfer gas denom over EVM
a0giToTransfer := big.NewInt(1e17) // .1 A0GI; neuron has 18 decimals. GasDenomToTransfer := big.NewInt(1e17) // .1 (gas denom); evm denom has 18 decimals.
req := util.EvmTxRequest{ req := util.EvmTxRequest{
Tx: ethtypes.NewTransaction(nonce, to, a0giToTransfer, 1e5, minEvmGasPrice, nil), Tx: ethtypes.NewTransaction(nonce, to, GasDenomToTransfer, 1e5, minEvmGasPrice, nil),
Data: "any ol' data to track this through the system", Data: "any ol' data to track this through the system",
} }
res := acc.SignAndBroadcastEvmTx(req) res := acc.SignAndBroadcastEvmTx(req)
@ -103,31 +100,31 @@ func (suite *IntegrationTestSuite) TestTransferOverEVM() {
suite.Equal(ethtypes.ReceiptStatusSuccessful, res.Receipt.Status) suite.Equal(ethtypes.ReceiptStatusSuccessful, res.Receipt.Status)
// evm txs refund unused gas. so to know the expected balance we need to know how much gas was used. // evm txs refund unused gas. so to know the expected balance we need to know how much gas was used.
a0giUsedForGas := sdkmath.NewIntFromBigInt(minEvmGasPrice). GasDenomUsedForGas := sdkmath.NewIntFromBigInt(minEvmGasPrice).
Mul(sdkmath.NewIntFromUint64(res.Receipt.GasUsed)). Mul(sdkmath.NewIntFromUint64(res.Receipt.GasUsed)).
QuoRaw(1e12) // convert neuron to a0gi QuoRaw(1e12) // convert evm denom to gas denom
// expect (9 - gas used) A0GI remaining in account. // expect (9 - gas used) (gas denom) remaining in account.
balance := suite.ZgChain.QuerySdkForBalances(acc.SdkAddress) balance := suite.ZgChain.QuerySdkForBalances(acc.SdkAddress)
suite.Equal(sdkmath.NewInt(9e5).Sub(a0giUsedForGas), balance.AmountOf("ua0gi")) suite.Equal(sdkmath.NewInt(9e5).Sub(GasDenomUsedForGas), balance.AmountOf(chaincfg.GasDenom))
} }
// TestIbcTransfer transfers A0GI from the primary 0g-chain (suite.ZgChain) to the ibc chain (suite.Ibc). // TestIbcTransfer transfers (gas denom) from the primary 0g-chain (suite.ZgChain) to the ibc chain (suite.Ibc).
// Note that because the IBC chain also runs 0g-chain's binary, this tests both the sending & receiving. // Note that because the IBC chain also runs 0g-chain's binary, this tests both the sending & receiving.
func (suite *IntegrationTestSuite) TestIbcTransfer() { func (suite *IntegrationTestSuite) TestIbcTransfer() {
suite.SkipIfIbcDisabled() suite.SkipIfIbcDisabled()
// ARRANGE // ARRANGE
// setup 0g-chain account // setup 0g-chain account
funds := a0gi(big.NewInt(1e5)) // .1 A0GI funds := chaincfg.MakeCoinForGasDenom(1e5) // .1 (gas denom)
zgChainAcc := suite.ZgChain.NewFundedAccount("ibc-transfer-0g-side", sdk.NewCoins(funds)) zgChainAcc := suite.ZgChain.NewFundedAccount("ibc-transfer-0g-side", sdk.NewCoins(funds))
// setup ibc account // setup ibc account
ibcAcc := suite.Ibc.NewFundedAccount("ibc-transfer-ibc-side", sdk.NewCoins()) ibcAcc := suite.Ibc.NewFundedAccount("ibc-transfer-ibc-side", sdk.NewCoins())
gasLimit := int64(2e5) gasLimit := int64(2e5)
fee := a0gi(big.NewInt(200)) fee := chaincfg.MakeCoinForGasDenom(200)
fundsToSend := a0gi(big.NewInt(5e4)) // .005 A0GI fundsToSend := chaincfg.MakeCoinForGasDenom(5e4) // .005 (gas denom)
transferMsg := ibctypes.NewMsgTransfer( transferMsg := ibctypes.NewMsgTransfer(
testutil.IbcPort, testutil.IbcPort,
testutil.IbcChannel, testutil.IbcChannel,
@ -157,7 +154,7 @@ func (suite *IntegrationTestSuite) TestIbcTransfer() {
// the balance should be deducted from 0g-chain account // the balance should be deducted from 0g-chain account
suite.Eventually(func() bool { suite.Eventually(func() bool {
balance := suite.ZgChain.QuerySdkForBalances(zgChainAcc.SdkAddress) balance := suite.ZgChain.QuerySdkForBalances(zgChainAcc.SdkAddress)
return balance.AmountOf("ua0gi").Equal(expectedSrcBalance.Amount) return balance.AmountOf(chaincfg.GasDenom).Equal(expectedSrcBalance.Amount)
}, 10*time.Second, 1*time.Second) }, 10*time.Second, 1*time.Second)
// expect the balance to be transferred to the ibc chain! // expect the balance to be transferred to the ibc chain!

View File

@ -3,7 +3,6 @@ package e2e_test
import ( import (
"context" "context"
"fmt" "fmt"
"math/big"
"time" "time"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -12,6 +11,7 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/tests/e2e/testutil" "github.com/0glabs/0g-chain/tests/e2e/testutil"
"github.com/0glabs/0g-chain/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
@ -101,13 +101,13 @@ func (suite *IntegrationTestSuite) TestModuleAccountGovTransfers() {
name: "transfer from community to kavadist for incentive rewards", name: "transfer from community to kavadist for incentive rewards",
sender: communityAcc, sender: communityAcc,
receiver: zgChainDistAcc, receiver: zgChainDistAcc,
amount: a0gi(big.NewInt(100)), amount: chaincfg.MakeCoinForGasDenom(100),
}, },
{ {
name: "transfer from kavadist to community", name: "transfer from kavadist to community",
sender: zgChainDistAcc, sender: zgChainDistAcc,
receiver: communityAcc, receiver: communityAcc,
amount: a0gi(big.NewInt(50)), amount: chaincfg.MakeCoinForGasDenom(50),
}, },
} }
@ -153,7 +153,7 @@ func (suite *IntegrationTestSuite) submitAndPassProposal(msgs []sdk.Msg) int64 {
suite.NoError(err) suite.NoError(err)
gasLimit := 1e6 gasLimit := 1e6
fee := sdk.NewCoin("neuron", sdk.NewInt(1e15)) fee := chaincfg.MakeCoinForEvmDenom(1e15)
req := util.ZgChainMsgRequest{ req := util.ZgChainMsgRequest{
Msgs: []sdk.Msg{proposalMsg}, Msgs: []sdk.Msg{proposalMsg},

View File

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/ethclient"
rpchttpclient "github.com/tendermint/tendermint/rpc/client/http" rpchttpclient "github.com/tendermint/tendermint/rpc/client/http"
"google.golang.org/grpc" "google.golang.org/grpc"
@ -81,7 +82,7 @@ var (
EvmRpcUrl: "http://localhost:8545", EvmRpcUrl: "http://localhost:8545",
ChainId: "0gchainlocalnet_8888-1", ChainId: "0gchainlocalnet_8888-1",
StakingDenom: "ua0gi", StakingDenom: chaincfg.GasDenom,
} }
kvtoolIbcChain = ChainDetails{ kvtoolIbcChain = ChainDetails{
RpcUrl: "http://localhost:26658", RpcUrl: "http://localhost:26658",

View File

@ -262,7 +262,7 @@ func (a *SigningAccount) BankSend(to sdk.AccAddress, amount sdk.Coins) util.ZgCh
util.ZgChainMsgRequest{ util.ZgChainMsgRequest{
Msgs: []sdk.Msg{banktypes.NewMsgSend(a.SdkAddress, to, amount)}, Msgs: []sdk.Msg{banktypes.NewMsgSend(a.SdkAddress, to, amount)},
GasLimit: 2e5, // 200,000 gas GasLimit: 2e5, // 200,000 gas
FeeAmount: sdk.NewCoins(sdk.NewCoin(a.gasDenom, sdkmath.NewInt(200))), // assume min gas price of .001a0gi FeeAmount: sdk.NewCoins(sdk.NewCoin(a.gasDenom, sdkmath.NewInt(200))), // assume min gas price of .001 gas denom
Data: fmt.Sprintf("sending %s to %s", amount, to), Data: fmt.Sprintf("sending %s to %s", amount, to),
}, },
) )

View File

@ -82,7 +82,7 @@ message Metadata {
string description = 1; string description = 1;
// denom_units represents the list of DenomUnit's for a given coin // denom_units represents the list of DenomUnit's for a given coin
repeated DenomUnit denom_units = 2; repeated DenomUnit denom_units = 2;
// base represents the base denom (should be the DenomUnit with exponent = 0). // base represents the evm denom (should be the DenomUnit with exponent = 0).
string base = 3; string base = 3;
// display indicates the suggested denom that should be // display indicates the suggested denom that should be
// displayed in clients. // displayed in clients.

View File

@ -234,18 +234,18 @@ message Tip {
string tipper = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; string tipper = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
} }
// AuxSignerData is the intermediary format that an auxiliary signer (e.g. a // AuxSignerData is the intermediary format that an gas signer (e.g. a
// tipper) builds and sends to the fee payer (who will build and broadcast the // tipper) builds and sends to the fee payer (who will build and broadcast the
// actual tx). AuxSignerData is not a valid tx in itself, and will be rejected // actual tx). AuxSignerData is not a valid tx in itself, and will be rejected
// by the node if sent directly as-is. // by the node if sent directly as-is.
// //
// Since: cosmos-sdk 0.46 // Since: cosmos-sdk 0.46
message AuxSignerData { message AuxSignerData {
// address is the bech32-encoded address of the auxiliary signer. If using // address is the bech32-encoded address of the gas signer. If using
// AuxSignerData across different chains, the bech32 prefix of the target // AuxSignerData across different chains, the bech32 prefix of the target
// chain (where the final transaction is broadcasted) should be used. // chain (where the final transaction is broadcasted) should be used.
string address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; string address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
// sign_doc is the SIGN_MODE_DIRECT_AUX sign doc that the auxiliary signer // sign_doc is the SIGN_MODE_DIRECT_AUX sign doc that the gas signer
// signs. Note: we use the same sign doc even if we're signing with // signs. Note: we use the same sign doc even if we're signing with
// LEGACY_AMINO_JSON. // LEGACY_AMINO_JSON.
SignDocDirectAux sign_doc = 2; SignDocDirectAux sign_doc = 2;

View File

@ -6,13 +6,13 @@ option go_package = "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types";
import "gogoproto/gogo.proto"; import "gogoproto/gogo.proto";
// DenomTrace contains the base denomination for ICS20 fungible tokens and the // DenomTrace contains the evm denomination for ICS20 fungible tokens and the
// source tracing information path. // source tracing information path.
message DenomTrace { message DenomTrace {
// path defines the chain of port/channel identifiers used for tracing the // path defines the chain of port/channel identifiers used for tracing the
// source of the fungible token. // source of the fungible token.
string path = 1; string path = 1;
// base denomination of the relayed fungible token. // evm denomination of the relayed fungible token.
string base_denom = 2; string base_denom = 2;
} }

View File

@ -106,7 +106,7 @@ func QueryCalcSwapIDCmd(queryRoute string) *cobra.Command {
return &cobra.Command{ return &cobra.Command{
Use: "calc-swapid [random-number-hash] [sender] [sender-other-chain]", Use: "calc-swapid [random-number-hash] [sender] [sender-other-chain]",
Short: "calculate swap ID for the given random number hash, sender, and sender other chain", Short: "calculate swap ID for the given random number hash, sender, and sender other chain",
Example: "bep3 calc-swapid 0677bd8a303dd981810f34d8e5cc6507f13b391899b84d3c1be6c6045a17d747 kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny bnb1ud3q90r98l3mhd87kswv3h8cgrymzeljct8qn7", Example: "bep3 calc-swapid 0677bd8a303dd981810f34d8e5cc6507f13b391899b84d3c1be6c6045a17d747 0g1l0xsq2z7gqd7yly0g40y5836g0appumark77ny bnb1ud3q90r98l3mhd87kswv3h8cgrymzeljct8qn7",
Args: cobra.MinimumNArgs(3), Args: cobra.MinimumNArgs(3),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd) clientCtx, err := client.GetClientQueryContext(cmd)
@ -220,7 +220,7 @@ func QueryGetAtomicSwapsCmd(queryRoute string) *cobra.Command {
Short: "query atomic swaps with optional filters", Short: "query atomic swaps with optional filters",
Long: strings.TrimSpace(`Query for all paginated atomic swaps that match optional filters: Long: strings.TrimSpace(`Query for all paginated atomic swaps that match optional filters:
Example: Example:
$ kvcli q bep3 swaps --involve=kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny $ kvcli q bep3 swaps --involve=0g1l0xsq2z7gqd7yly0g40y5836g0appumark77ny
$ kvcli q bep3 swaps --expiration=280 $ kvcli q bep3 swaps --expiration=280
$ kvcli q bep3 swaps --status=(Open|Completed|Expired) $ kvcli q bep3 swaps --status=(Open|Completed|Expired)
$ kvcli q bep3 swaps --direction=(Incoming|Outgoing) $ kvcli q bep3 swaps --direction=(Incoming|Outgoing)

View File

@ -12,6 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/bep3" "github.com/0glabs/0g-chain/x/bep3"
"github.com/0glabs/0g-chain/x/bep3/keeper" "github.com/0glabs/0g-chain/x/bep3/keeper"
"github.com/0glabs/0g-chain/x/bep3/types" "github.com/0glabs/0g-chain/x/bep3/types"
@ -35,7 +36,7 @@ func (suite *MsgServerTestSuite) SetupTest() {
// Set up genesis state and initialize // Set up genesis state and initialize
_, addrs := app.GeneratePrivKeyAddressPairs(3) _, addrs := app.GeneratePrivKeyAddressPairs(3)
coins := sdk.NewCoins(c("bnb", 10000000000), c("a0gi", 10000)) coins := sdk.NewCoins(c("bnb", 10000000000), c(chaincfg.GasDenom, 10000))
authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs)
tApp.InitializeFromGenesisStates(authGS, NewBep3GenStateMulti(cdc, addrs[0])) tApp.InitializeFromGenesisStates(authGS, NewBep3GenStateMulti(cdc, addrs[0]))

View File

@ -16,6 +16,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/bep3/keeper" "github.com/0glabs/0g-chain/x/bep3/keeper"
"github.com/0glabs/0g-chain/x/bep3/types" "github.com/0glabs/0g-chain/x/bep3/types"
) )
@ -41,7 +42,7 @@ func (suite *QuerierTestSuite) SetupTest() {
// Set up auth GenesisState // Set up auth GenesisState
_, addrs := app.GeneratePrivKeyAddressPairs(11) _, addrs := app.GeneratePrivKeyAddressPairs(11)
coins := sdk.NewCoins(c("bnb", 10000000000), c("a0gi", 10000)) coins := sdk.NewCoins(c("bnb", 10000000000), c(chaincfg.GasDenom, 10000))
authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs)
tApp.InitializeFromGenesisStates( tApp.InitializeFromGenesisStates(

View File

@ -1,57 +0,0 @@
package v0_16
import (
"fmt"
"github.com/0glabs/0g-chain/x/bep3/types"
)
// resetSwapForZeroHeight updates swap expiry/close heights to work when the chain height is reset to zero.
func resetSwapForZeroHeight(swap types.AtomicSwap) types.AtomicSwap {
switch status := swap.Status; status {
case types.SWAP_STATUS_COMPLETED:
// Reset closed block to one so completed swaps are not held in long term storage too long.
swap.ClosedBlock = 1
case types.SWAP_STATUS_OPEN:
switch dir := swap.Direction; dir {
case types.SWAP_DIRECTION_INCOMING:
// Open incoming swaps can be expired safely. They haven't been claimed yet, so the outgoing swap on bnb will just timeout.
// The chain downtime cannot be accurately predicted, so it's easier to expire than to recalculate a correct expire height.
swap.ExpireHeight = 1
swap.Status = types.SWAP_STATUS_EXPIRED
case types.SWAP_DIRECTION_OUTGOING:
// Open outgoing swaps should be extended to allow enough time to claim after the chain launches.
// They cannot be expired as there could be an open/claimed bnb swap.
swap.ExpireHeight = 1 + 24686 // default timeout used when sending swaps from 0g
case types.SWAP_DIRECTION_UNSPECIFIED:
default:
panic(fmt.Sprintf("unknown bep3 swap direction '%s'", dir))
}
case types.SWAP_STATUS_EXPIRED:
// Once a swap is marked expired the expire height is ignored. However reset to 1 to be sure.
swap.ExpireHeight = 1
case types.SWAP_STATUS_UNSPECIFIED:
default:
panic(fmt.Sprintf("unknown bep3 swap status '%s'", status))
}
return swap
}
func resetSwapsForZeroHeight(oldSwaps types.AtomicSwaps) types.AtomicSwaps {
newSwaps := make(types.AtomicSwaps, len(oldSwaps))
for i, oldSwap := range oldSwaps {
swap := resetSwapForZeroHeight(oldSwap)
newSwaps[i] = swap
}
return newSwaps
}
func Migrate(oldState types.GenesisState) *types.GenesisState {
return &types.GenesisState{
PreviousBlockTime: oldState.PreviousBlockTime,
Params: oldState.Params,
AtomicSwaps: resetSwapsForZeroHeight(oldState.AtomicSwaps),
Supplies: oldState.Supplies,
}
}

View File

@ -1,176 +0,0 @@
package v0_16
import (
"io/ioutil"
"path/filepath"
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
"github.com/tendermint/tendermint/libs/bytes"
app "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/bep3/types"
)
type migrateTestSuite struct {
suite.Suite
addresses []sdk.AccAddress
v16genstate types.GenesisState
cdc codec.Codec
}
func (s *migrateTestSuite) SetupTest() {
chaincfg.SetSDKConfig()
s.v16genstate = types.GenesisState{
PreviousBlockTime: time.Date(2021, 4, 8, 15, 0, 0, 0, time.UTC),
Params: types.Params{},
Supplies: types.AssetSupplies{},
AtomicSwaps: types.AtomicSwaps{},
}
config := app.MakeEncodingConfig()
s.cdc = config.Marshaler
_, accAddresses := app.GeneratePrivKeyAddressPairs(10)
s.addresses = accAddresses
}
func (s *migrateTestSuite) TestMigrate_JSON() {
// Migrate v16 bep3 to v17
file := filepath.Join("testdata", "v16-bep3.json")
data, err := ioutil.ReadFile(file)
s.Require().NoError(err)
err = s.cdc.UnmarshalJSON(data, &s.v16genstate)
s.Require().NoError(err)
genstate := Migrate(s.v16genstate)
// Compare expect v16 bep3 json with migrated json
actual := s.cdc.MustMarshalJSON(genstate)
file = filepath.Join("testdata", "v17-bep3.json")
expected, err := ioutil.ReadFile(file)
s.Require().NoError(err)
s.Require().JSONEq(string(expected), string(actual))
}
func (s *migrateTestSuite) TestMigrate_Swaps() {
type swap struct {
ExpireHeight uint64
CloseBlock int64
Status types.SwapStatus
Direction types.SwapDirection
}
testcases := []struct {
name string
oldSwap swap
newSwap swap
}{
{
name: "incoming open swap",
oldSwap: swap{
// expire and close not set in open swaps
Status: types.SWAP_STATUS_OPEN,
Direction: types.SWAP_DIRECTION_INCOMING,
},
newSwap: swap{
ExpireHeight: 1,
Status: types.SWAP_STATUS_EXPIRED,
Direction: types.SWAP_DIRECTION_INCOMING,
},
},
{
name: "outgoing open swap",
oldSwap: swap{
// expire and close not set in open swaps
Status: types.SWAP_STATUS_OPEN,
Direction: types.SWAP_DIRECTION_OUTGOING,
},
newSwap: swap{
ExpireHeight: 24687,
Status: types.SWAP_STATUS_OPEN,
Direction: types.SWAP_DIRECTION_OUTGOING,
},
},
{
name: "completed swap",
oldSwap: swap{
ExpireHeight: 1000,
CloseBlock: 900,
Status: types.SWAP_STATUS_COMPLETED,
Direction: types.SWAP_DIRECTION_INCOMING,
},
newSwap: swap{
ExpireHeight: 1000,
CloseBlock: 1,
Status: types.SWAP_STATUS_COMPLETED,
Direction: types.SWAP_DIRECTION_INCOMING,
},
},
{
name: "expired swap",
oldSwap: swap{
ExpireHeight: 1000,
CloseBlock: 900,
Status: types.SWAP_STATUS_EXPIRED,
Direction: types.SWAP_DIRECTION_INCOMING,
},
newSwap: swap{
ExpireHeight: 1,
CloseBlock: 900,
Status: types.SWAP_STATUS_EXPIRED,
Direction: types.SWAP_DIRECTION_INCOMING,
},
},
}
for _, tc := range testcases {
s.Run(tc.name, func() {
oldSwaps := types.AtomicSwaps{
{
Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(12))),
RandomNumberHash: bytes.HexBytes{},
ExpireHeight: tc.oldSwap.ExpireHeight,
Timestamp: 1110,
Sender: s.addresses[0],
Recipient: s.addresses[1],
RecipientOtherChain: s.addresses[0].String(),
SenderOtherChain: s.addresses[1].String(),
ClosedBlock: tc.oldSwap.CloseBlock,
Status: tc.oldSwap.Status,
CrossChain: true,
Direction: tc.oldSwap.Direction,
},
}
expectedSwaps := types.AtomicSwaps{
{
Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(12))),
RandomNumberHash: bytes.HexBytes{},
ExpireHeight: tc.newSwap.ExpireHeight,
Timestamp: 1110,
Sender: s.addresses[0],
Recipient: s.addresses[1],
RecipientOtherChain: s.addresses[0].String(),
SenderOtherChain: s.addresses[1].String(),
ClosedBlock: tc.newSwap.CloseBlock,
Status: tc.newSwap.Status,
CrossChain: true,
Direction: tc.newSwap.Direction,
},
}
s.v16genstate.AtomicSwaps = oldSwaps
genState := Migrate(s.v16genstate)
s.Require().Len(genState.AtomicSwaps, 1)
s.Equal(expectedSwaps, genState.AtomicSwaps)
})
}
}
func TestMigrateTestSuite(t *testing.T) {
suite.Run(t, new(migrateTestSuite))
}

View File

@ -1,212 +0,0 @@
{
"atomic_swaps": [
{
"amount": [
{
"amount": "1999955998",
"denom": "btcb"
}
],
"closed_block": "838115",
"cross_chain": true,
"direction": "SWAP_DIRECTION_INCOMING",
"expire_height": "838627",
"random_number_hash": "6F1CF8F2E13A0C0F0A359F54E47E4E265D766B8E006D2F00BDF994ABDEF1E9E4",
"recipient": "kava1fl2hs6y9vz986g5v52pdan9ga923n9mn5cxxkw",
"recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr",
"sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc",
"sender_other_chain": "bnb19k9wuv2j7c7ck8tmc7kav0r0cnt3esmkrpf25x",
"status": "SWAP_STATUS_COMPLETED",
"timestamp": "1636034914"
},
{
"amount": [
{
"amount": "19000000000",
"denom": "bnb"
}
],
"closed_block": "1712118",
"cross_chain": true,
"direction": "SWAP_DIRECTION_OUTGOING",
"expire_height": "1736797",
"random_number_hash": "280EB832A37F2265CC82F3957CE603AAD57BAD7038B876A1F28953AFA29FA1C3",
"recipient": "kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6",
"recipient_other_chain": "bnb18nsgj50zvc4uq93w4j0ltz5gaxhwv7aq4qnq0p",
"sender": "kava1zw6gg4ztvly7zf25pa33mclav3spvj3ympxxna",
"sender_other_chain": "bnb1jh7uv2rm6339yue8k4mj9406k3509kr4wt5nxn",
"status": "SWAP_STATUS_COMPLETED",
"timestamp": "1641976566"
},
{
"amount": [
{
"amount": "999595462080",
"denom": "busd"
}
],
"closed_block": "787122",
"cross_chain": true,
"direction": "SWAP_DIRECTION_INCOMING",
"expire_height": "811799",
"random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83",
"recipient": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl",
"recipient_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8",
"sender": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu",
"sender_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at",
"status": "SWAP_STATUS_EXPIRED",
"timestamp": "1635694492"
},
{
"amount": [
{
"amount": "999595462080",
"denom": "busd"
}
],
"closed_block": "787122",
"cross_chain": true,
"direction": "SWAP_DIRECTION_OUTGOING",
"expire_height": "811799",
"random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83",
"recipient": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu",
"recipient_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at",
"sender": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl",
"sender_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8",
"status": "SWAP_STATUS_EXPIRED",
"timestamp": "1635694492"
},
{
"amount": [
{
"amount": "1000000",
"denom": "btcb"
}
],
"closed_block": "0",
"cross_chain": true,
"direction": "SWAP_DIRECTION_OUTGOING",
"expire_height": "1730589",
"random_number_hash": "A74EA1AB58D312FDF1E872D18583CACCF294E639DDA4F303939E9ADCEC081D93",
"recipient": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc",
"recipient_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6",
"sender": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5",
"sender_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr",
"status": "SWAP_STATUS_OPEN",
"timestamp": "1641934114"
},
{
"amount": [
{
"amount": "1000000",
"denom": "btcb"
}
],
"closed_block": "0",
"cross_chain": true,
"direction": "SWAP_DIRECTION_INCOMING",
"expire_height": "1740000",
"random_number_hash": "39E9ADCEC081D93A74EA1A83CACCF294E639DDA4F3039B58D312FDF1E872D185",
"recipient": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5",
"recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr",
"sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc",
"sender_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6",
"status": "SWAP_STATUS_OPEN",
"timestamp": "1641934114"
}
],
"params": {
"asset_params": [
{
"active": true,
"coin_id": "0",
"denom": "btcb",
"deputy_address": "kava1kla4wl0ccv7u85cemvs3y987hqk0afcv7vue84",
"fixed_fee": "2",
"max_block_lock": "86400",
"max_swap_amount": "2000000000",
"min_block_lock": "24686",
"min_swap_amount": "3",
"supply_limit": {
"limit": "100000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
},
{
"active": true,
"coin_id": "144",
"denom": "xrpb",
"deputy_address": "kava14q5sawxdxtpap5x5sgzj7v4sp3ucncjlpuk3hs",
"fixed_fee": "100000",
"max_block_lock": "86400",
"max_swap_amount": "250000000000000",
"min_block_lock": "24686",
"min_swap_amount": "100001",
"supply_limit": {
"limit": "2000000000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
},
{
"active": true,
"coin_id": "714",
"denom": "bnb",
"deputy_address": "kava1agcvt07tcw0tglu0hmwdecsnuxp2yd45f3avgm",
"fixed_fee": "1000",
"max_block_lock": "86400",
"max_swap_amount": "500000000000",
"min_block_lock": "24686",
"min_swap_amount": "1001",
"supply_limit": {
"limit": "100000000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
},
{
"active": true,
"coin_id": "727",
"denom": "busd",
"deputy_address": "kava1j9je7f6s0v6k7dmgv6u5k5ru202f5ffsc7af04",
"fixed_fee": "20000",
"max_block_lock": "86400",
"max_swap_amount": "100000000000000",
"min_block_lock": "24686",
"min_swap_amount": "20001",
"supply_limit": {
"limit": "2000000000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
}
]
},
"previous_block_time": "1970-01-01T00:00:00Z",
"supplies": [
{
"current_supply": {
"amount": "30467559434006",
"denom": "bnb"
},
"incoming_supply": {
"amount": "0",
"denom": "bnb"
},
"outgoing_supply": {
"amount": "0",
"denom": "bnb"
},
"time_elapsed": "0s",
"time_limited_current_supply": {
"amount": "0",
"denom": "bnb"
}
}
]
}

View File

@ -1,212 +0,0 @@
{
"atomic_swaps": [
{
"amount": [
{
"amount": "1999955998",
"denom": "btcb"
}
],
"closed_block": "1",
"cross_chain": true,
"direction": "SWAP_DIRECTION_INCOMING",
"expire_height": "838627",
"random_number_hash": "6F1CF8F2E13A0C0F0A359F54E47E4E265D766B8E006D2F00BDF994ABDEF1E9E4",
"recipient": "kava1fl2hs6y9vz986g5v52pdan9ga923n9mn5cxxkw",
"recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr",
"sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc",
"sender_other_chain": "bnb19k9wuv2j7c7ck8tmc7kav0r0cnt3esmkrpf25x",
"status": "SWAP_STATUS_COMPLETED",
"timestamp": "1636034914"
},
{
"amount": [
{
"amount": "19000000000",
"denom": "bnb"
}
],
"closed_block": "1",
"cross_chain": true,
"direction": "SWAP_DIRECTION_OUTGOING",
"expire_height": "1736797",
"random_number_hash": "280EB832A37F2265CC82F3957CE603AAD57BAD7038B876A1F28953AFA29FA1C3",
"recipient": "kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6",
"recipient_other_chain": "bnb18nsgj50zvc4uq93w4j0ltz5gaxhwv7aq4qnq0p",
"sender": "kava1zw6gg4ztvly7zf25pa33mclav3spvj3ympxxna",
"sender_other_chain": "bnb1jh7uv2rm6339yue8k4mj9406k3509kr4wt5nxn",
"status": "SWAP_STATUS_COMPLETED",
"timestamp": "1641976566"
},
{
"amount": [
{
"amount": "999595462080",
"denom": "busd"
}
],
"closed_block": "787122",
"cross_chain": true,
"direction": "SWAP_DIRECTION_INCOMING",
"expire_height": "1",
"random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83",
"recipient": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl",
"recipient_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8",
"sender": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu",
"sender_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at",
"status": "SWAP_STATUS_EXPIRED",
"timestamp": "1635694492"
},
{
"amount": [
{
"amount": "999595462080",
"denom": "busd"
}
],
"closed_block": "787122",
"cross_chain": true,
"direction": "SWAP_DIRECTION_OUTGOING",
"expire_height": "1",
"random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83",
"recipient": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu",
"recipient_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at",
"sender": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl",
"sender_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8",
"status": "SWAP_STATUS_EXPIRED",
"timestamp": "1635694492"
},
{
"amount": [
{
"amount": "1000000",
"denom": "btcb"
}
],
"closed_block": "0",
"cross_chain": true,
"direction": "SWAP_DIRECTION_OUTGOING",
"expire_height": "24687",
"random_number_hash": "A74EA1AB58D312FDF1E872D18583CACCF294E639DDA4F303939E9ADCEC081D93",
"recipient": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc",
"recipient_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6",
"sender": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5",
"sender_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr",
"status": "SWAP_STATUS_OPEN",
"timestamp": "1641934114"
},
{
"amount": [
{
"amount": "1000000",
"denom": "btcb"
}
],
"closed_block": "0",
"cross_chain": true,
"direction": "SWAP_DIRECTION_INCOMING",
"expire_height": "1",
"random_number_hash": "39E9ADCEC081D93A74EA1A83CACCF294E639DDA4F3039B58D312FDF1E872D185",
"recipient": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5",
"recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr",
"sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc",
"sender_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6",
"status": "SWAP_STATUS_EXPIRED",
"timestamp": "1641934114"
}
],
"params": {
"asset_params": [
{
"active": true,
"coin_id": "0",
"denom": "btcb",
"deputy_address": "kava1kla4wl0ccv7u85cemvs3y987hqk0afcv7vue84",
"fixed_fee": "2",
"max_block_lock": "86400",
"max_swap_amount": "2000000000",
"min_block_lock": "24686",
"min_swap_amount": "3",
"supply_limit": {
"limit": "100000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
},
{
"active": true,
"coin_id": "144",
"denom": "xrpb",
"deputy_address": "kava14q5sawxdxtpap5x5sgzj7v4sp3ucncjlpuk3hs",
"fixed_fee": "100000",
"max_block_lock": "86400",
"max_swap_amount": "250000000000000",
"min_block_lock": "24686",
"min_swap_amount": "100001",
"supply_limit": {
"limit": "2000000000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
},
{
"active": true,
"coin_id": "714",
"denom": "bnb",
"deputy_address": "kava1agcvt07tcw0tglu0hmwdecsnuxp2yd45f3avgm",
"fixed_fee": "1000",
"max_block_lock": "86400",
"max_swap_amount": "500000000000",
"min_block_lock": "24686",
"min_swap_amount": "1001",
"supply_limit": {
"limit": "100000000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
},
{
"active": true,
"coin_id": "727",
"denom": "busd",
"deputy_address": "kava1j9je7f6s0v6k7dmgv6u5k5ru202f5ffsc7af04",
"fixed_fee": "20000",
"max_block_lock": "86400",
"max_swap_amount": "100000000000000",
"min_block_lock": "24686",
"min_swap_amount": "20001",
"supply_limit": {
"limit": "2000000000000000",
"time_based_limit": "0",
"time_limited": false,
"time_period": "0s"
}
}
]
},
"previous_block_time": "1970-01-01T00:00:00Z",
"supplies": [
{
"current_supply": {
"amount": "30467559434006",
"denom": "bnb"
},
"incoming_supply": {
"amount": "0",
"denom": "bnb"
},
"outgoing_supply": {
"amount": "0",
"denom": "bnb"
},
"time_elapsed": "0s",
"time_limited_current_supply": {
"amount": "0",
"denom": "bnb"
}
}
]
}

View File

@ -20,7 +20,7 @@ type GenesisTestSuite struct {
} }
func (suite *GenesisTestSuite) SetupTest() { func (suite *GenesisTestSuite) SetupTest() {
coin := sdk.NewCoin("a0gi", sdk.OneInt()) coin := chaincfg.MakeCoinForGasDenom(1)
suite.swaps = atomicSwaps(10) suite.swaps = atomicSwaps(10)
supply := types.NewAssetSupply(coin, coin, coin, coin, time.Duration(0)) supply := types.NewAssetSupply(coin, coin, coin, coin, time.Duration(0))

View File

@ -5,12 +5,13 @@ import (
"time" "time"
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
"github.com/0glabs/0g-chain/chaincfg"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func TestAssetSupplyValidate(t *testing.T) { func TestAssetSupplyValidate(t *testing.T) {
coin := sdk.NewCoin("a0gi", sdk.OneInt()) coin := chaincfg.MakeCoinForGasDenom(1)
invalidCoin := sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(-1)} invalidCoin := sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(-1)}
testCases := []struct { testCases := []struct {
msg string msg string

View File

@ -6,12 +6,12 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/committee/keeper" "github.com/0glabs/0g-chain/x/committee/keeper"
"github.com/0glabs/0g-chain/x/committee/types" "github.com/0glabs/0g-chain/x/committee/types"
) )
@ -61,7 +61,7 @@ func (suite *MsgServerTestSuite) SetupTest() {
[]types.Proposal{}, []types.Proposal{},
[]types.Vote{}, []types.Vote{},
) )
suite.communityPoolAmt = sdk.NewCoins(sdk.NewCoin("neuron", sdkmath.NewInt(1000000000000000))) suite.communityPoolAmt = sdk.NewCoins(chaincfg.MakeCoinForEvmDenom(1000000000000000))
suite.app.InitializeFromGenesisStates( suite.app.InitializeFromGenesisStates(
app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(testGenesis)}, app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(testGenesis)},
// TODO: not used? // TODO: not used?

View File

@ -4,6 +4,7 @@ import (
fmt "fmt" fmt "fmt"
"time" "time"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -18,7 +19,7 @@ const (
BaseCommitteeType = "0g/BaseCommittee" BaseCommitteeType = "0g/BaseCommittee"
MemberCommitteeType = "0g/MemberCommittee" // Committee is composed of member addresses that vote to enact proposals within their permissions MemberCommitteeType = "0g/MemberCommittee" // Committee is composed of member addresses that vote to enact proposals within their permissions
TokenCommitteeType = "0g/TokenCommittee" // Committee is composed of token holders with voting power determined by total token balance TokenCommitteeType = "0g/TokenCommittee" // Committee is composed of token holders with voting power determined by total token balance
BondDenom = "neuron" BondDenom = chaincfg.BondDenom
) )
// Marshal needed for protobuf compatibility. // Marshal needed for protobuf compatibility.

View File

@ -171,10 +171,10 @@ func NewVoteCmd() *cobra.Command {
tokens = val.GetTokens() tokens = val.GetTokens()
} }
} }
// the denom of token is neuron, need to convert to A0GI // the denom of token is evm denom, need to convert to A0GI
a0gi := tokens.Quo(sdk.NewInt(1_000_000_000_000_000_000)) a0giTokenCnt := tokens.Quo(sdk.NewInt(1_000_000_000_000_000_000))
// 1_000 0AGI token / vote // 1_000 0AGI token / vote
numBallots := a0gi.Quo(sdk.NewInt(1_000)).Uint64() numBallots := a0giTokenCnt.Quo(sdk.NewInt(1_000)).Uint64()
ballots := make([]*types.Ballot, numBallots) ballots := make([]*types.Ballot, numBallots)
for i := range ballots { for i := range ballots {
ballotID := uint64(i) ballotID := uint64(i)

View File

@ -21,8 +21,8 @@ var (
const ( const (
// Amino names // Amino names
registerName = "evmos/council/MsgRegister" registerName = "0g/council/MsgRegister"
voteName = "evmos/council/MsgVote" voteName = "0g/council/MsgVote"
) )
// NOTE: This is required for the GetSignBytes function // NOTE: This is required for the GetSignBytes function

View File

@ -1,57 +0,0 @@
package cli
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/0glabs/0g-chain/x/das/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
)
// GetQueryCmd returns the cli query commands for the inflation module.
func GetQueryCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: "Querying commands for the das module",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
GetNextRequestID(),
)
return cmd
}
func GetNextRequestID() *cobra.Command {
cmd := &cobra.Command{
Use: "next-request-id",
Short: "Query the next request ID",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
params := &types.QueryNextRequestIDRequest{}
res, err := queryClient.NextRequestID(context.Background(), params)
if err != nil {
return err
}
return clientCtx.PrintString(fmt.Sprintf("%v\n", res.NextRequestID))
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}

View File

@ -1,103 +0,0 @@
package cli
import (
"encoding/hex"
"fmt"
"strconv"
"github.com/0glabs/0g-chain/x/das/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
)
// 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(
NewRequestDASCmd(),
NewReportDASResultCmd(),
)
return cmd
}
func NewRequestDASCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "request-das steram-id batch-header-hash num-blobs",
Short: "Request data-availability-sampling",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
numBlobs, err := strconv.Atoi(args[2])
if err != nil {
return err
}
msg := types.NewMsgRequestDAS(clientCtx.GetFromAddress(), args[0], args[1], uint32(numBlobs))
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func NewReportDASResultCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "report-das-result request-id results",
Short: "Report data-availability-sampling result",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
requestID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
n := len(args) - 1
results := make([]bool, n)
for i := 0; i < n; i++ {
var err error
results[i], err = strconv.ParseBool(args[i+1])
if err != nil {
return err
}
}
// get account name by address
accAddr := clientCtx.GetFromAddress()
samplerAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(accAddr.Bytes()))
if err != nil {
return err
}
msg := &types.MsgReportDASResult{
RequestID: requestID,
Sampler: samplerAddr.String(),
Results: results,
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}

View File

@ -1,39 +0,0 @@
package das
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/0glabs/0g-chain/x/das/v1/keeper"
"github.com/0glabs/0g-chain/x/das/v1/types"
)
// InitGenesis initializes the store state from a genesis state.
func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, gs types.GenesisState) {
if err := gs.Validate(); err != nil {
panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err))
}
keeper.SetNextRequestID(ctx, gs.NextRequestID)
for _, req := range gs.Requests {
keeper.SetDASRequest(ctx, req)
}
for _, resp := range gs.Responses {
keeper.SetDASResponse(ctx, resp)
}
}
// ExportGenesis returns a GenesisState for a given context and keeper.
func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState {
nextRequestID, err := keeper.GetNextRequestID(ctx)
if err != nil {
panic(err)
}
return types.NewGenesisState(
nextRequestID,
keeper.GetDASRequests(ctx),
keeper.GetDASResponses(ctx),
)
}

View File

@ -1,22 +0,0 @@
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/das/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var _ types.QueryServer = Keeper{}
func (k Keeper) NextRequestID(
c context.Context,
_ *types.QueryNextRequestIDRequest,
) (*types.QueryNextRequestIDResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
nextRequestID, err := k.GetNextRequestID(ctx)
if err != nil {
return nil, err
}
return &types.QueryNextRequestIDResponse{NextRequestID: nextRequestID}, nil
}

View File

@ -1,198 +0,0 @@
package keeper
import (
"encoding/hex"
"strconv"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/0glabs/0g-chain/x/das/v1/types"
)
type Keeper struct {
storeKey storetypes.StoreKey
cdc codec.BinaryCodec
stakingKeeperRef types.StakingKeeperRef
}
// NewKeeper creates a new das Keeper instance
func NewKeeper(
storeKey storetypes.StoreKey,
cdc codec.BinaryCodec,
stakingKeeper types.StakingKeeperRef,
) Keeper {
return Keeper{
storeKey: storeKey,
cdc: cdc,
stakingKeeperRef: stakingKeeper,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
func (k Keeper) SetNextRequestID(ctx sdk.Context, id uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.NextRequestIDKey, types.GetKeyFromID(id))
}
func (k Keeper) GetNextRequestID(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.NextRequestIDKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "next request ID not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
func (k Keeper) IncrementNextRequestID(ctx sdk.Context) error {
id, err := k.GetNextRequestID(ctx)
if err != nil {
return err
}
k.SetNextRequestID(ctx, id+1)
return nil
}
func (k Keeper) GetDASRequest(ctx sdk.Context, requestID uint64) (types.DASRequest, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.RequestKeyPrefix)
bz := store.Get(types.GetKeyFromID(requestID))
if bz == nil {
return types.DASRequest{}, false
}
var req types.DASRequest
k.cdc.MustUnmarshal(bz, &req)
return req, true
}
func (k Keeper) SetDASRequest(ctx sdk.Context, req types.DASRequest) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.RequestKeyPrefix)
bz := k.cdc.MustMarshal(&req)
store.Set(types.GetKeyFromID(req.ID), bz)
}
func (k Keeper) IterateDASRequest(ctx sdk.Context, cb func(req types.DASRequest) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.RequestKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var req types.DASRequest
k.cdc.MustUnmarshal(iterator.Value(), &req)
if cb(req) {
break
}
}
}
func (k Keeper) GetDASRequests(ctx sdk.Context) []types.DASRequest {
results := []types.DASRequest{}
k.IterateDASRequest(ctx, func(req types.DASRequest) bool {
results = append(results, req)
return false
})
return results
}
func (k Keeper) StoreNewDASRequest(
ctx sdk.Context,
streamIDHexStr string,
batchHeaderHashHexStr string,
numBlobs uint32) (uint64, error) {
requestID, err := k.GetNextRequestID(ctx)
if err != nil {
return 0, err
}
streamID, err := hex.DecodeString(streamIDHexStr)
if err != nil {
return 0, err
}
batchHeaderHash, err := hex.DecodeString(batchHeaderHashHexStr)
if err != nil {
return 0, err
}
req := types.DASRequest{
ID: requestID,
StreamID: streamID,
BatchHeaderHash: batchHeaderHash,
NumBlobs: numBlobs,
}
k.SetDASRequest(ctx, req)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeDASRequest,
sdk.NewAttribute(types.AttributeKeyRequestID, strconv.FormatUint(requestID, 10)),
sdk.NewAttribute(types.AttributeKeyStreamID, streamIDHexStr),
sdk.NewAttribute(types.AttributeKeyBatchHeaderHash, batchHeaderHashHexStr),
sdk.NewAttribute(types.AttributeKeyNumBlobs, strconv.FormatUint(uint64(numBlobs), 10)),
),
)
return requestID, nil
}
func (k Keeper) GetDASResponse(
ctx sdk.Context, requestID uint64, sampler sdk.ValAddress,
) (types.DASResponse, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix)
bz := store.Get(types.GetResponseKey(requestID, sampler))
if bz == nil {
return types.DASResponse{}, false
}
var vote types.DASResponse
k.cdc.MustUnmarshal(bz, &vote)
return vote, true
}
func (k Keeper) SetDASResponse(ctx sdk.Context, resp types.DASResponse) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix)
bz := k.cdc.MustMarshal(&resp)
store.Set(types.GetResponseKey(resp.ID, resp.Sampler), bz)
}
func (k Keeper) IterateDASResponse(ctx sdk.Context, cb func(resp types.DASResponse) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var resp types.DASResponse
k.cdc.MustUnmarshal(iterator.Value(), &resp)
if cb(resp) {
break
}
}
}
func (k Keeper) GetDASResponses(ctx sdk.Context) []types.DASResponse {
results := []types.DASResponse{}
k.IterateDASResponse(ctx, func(resp types.DASResponse) bool {
results = append(results, resp)
return false
})
return results
}
func (k Keeper) StoreNewDASResponse(
ctx sdk.Context, requestID uint64, sampler sdk.ValAddress, results []bool) error {
if _, found := k.GetDASRequest(ctx, requestID); !found {
return errorsmod.Wrapf(types.ErrUnknownRequest, "%d", requestID)
}
k.SetDASResponse(ctx, types.DASResponse{
ID: requestID,
Sampler: sampler,
Results: results,
})
return nil
}

View File

@ -1,49 +0,0 @@
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/das/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
var _ types.MsgServer = &Keeper{}
// RequestDAS handles MsgRequestDAS messages
func (k Keeper) RequestDAS(
goCtx context.Context, msg *types.MsgRequestDAS,
) (*types.MsgRequestDASResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
requestID, err := k.StoreNewDASRequest(ctx, msg.StreamID, msg.BatchHeaderHash, msg.NumBlobs)
if err != nil {
return nil, err
}
k.IncrementNextRequestID(ctx)
return &types.MsgRequestDASResponse{
RequestID: requestID,
}, nil
}
// ReportDASResult handles MsgReportDASResult messages
func (k Keeper) ReportDASResult(
goCtx context.Context, msg *types.MsgReportDASResult,
) (*types.MsgReportDASResultResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
sampler, err := sdk.ValAddressFromBech32(msg.Sampler)
if err != nil {
return nil, err
}
if _, found := k.stakingKeeperRef.GetValidator(ctx, sampler); !found {
return nil, stakingtypes.ErrNoValidatorFound
}
if err := k.StoreNewDASResponse(ctx, msg.RequestID, sampler, msg.Results); err != nil {
return nil, err
}
return &types.MsgReportDASResultResponse{}, nil
}

View File

@ -1,180 +0,0 @@
package das
import (
"context"
"encoding/json"
"fmt"
"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/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/0glabs/0g-chain/x/das/v1/client/cli"
"github.com/0glabs/0g-chain/x/das/v1/keeper"
"github.com/0glabs/0g-chain/x/das/v1/types"
)
// consensusVersion defines the current x/council module consensus version.
const consensusVersion = 1
// type check to ensure the interface is properly implemented
var (
_ module.AppModule = AppModule{}
_ module.AppModuleBasic = AppModuleBasic{}
// _ module.AppModuleSimulation = AppModule{}
_ module.BeginBlockAppModule = AppModule{}
_ module.EndBlockAppModule = AppModule{}
)
// app module Basics object
type AppModuleBasic struct{}
// Name returns the inflation module's name.
func (AppModuleBasic) Name() string {
return types.ModuleName
}
// RegisterLegacyAminoCodec registers the inflation module's types on the given LegacyAmino codec.
func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {}
// ConsensusVersion returns the consensus state-breaking version for the module.
func (AppModuleBasic) ConsensusVersion() uint64 {
return consensusVersion
}
// RegisterInterfaces registers interfaces and implementations of the incentives
// module.
func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) {
types.RegisterInterfaces(interfaceRegistry)
}
// DefaultGenesis returns default genesis state as raw bytes for the incentives
// module.
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the inflation module.
func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error {
var genesisState types.GenesisState
if err := cdc.UnmarshalJSON(bz, &genesisState); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
}
return genesisState.Validate()
}
// RegisterRESTRoutes performs a no-op as the inflation module doesn't expose REST
// endpoints
func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {}
// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the inflation module.
func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) {
if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil {
panic(err)
}
}
// GetTxCmd returns the root tx command for the inflation module.
func (AppModuleBasic) GetTxCmd() *cobra.Command {
return cli.GetTxCmd()
}
// GetQueryCmd returns no root query command for the inflation module.
func (AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd()
}
// ___________________________________________________________________________
// AppModule implements an application module for the inflation module.
type AppModule struct {
AppModuleBasic
keeper keeper.Keeper
}
// NewAppModule creates a new AppModule Object
func NewAppModule(
k keeper.Keeper,
) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{},
keeper: k,
}
}
// Name returns the inflation module's name.
func (AppModule) Name() string {
return types.ModuleName
}
// Route returns evmutil module's message route.
func (am AppModule) Route() sdk.Route { return sdk.Route{} }
// QuerierRoute returns evmutil module's query routing key.
func (AppModule) QuerierRoute() string { return "" }
// LegacyQuerierHandler returns evmutil module's Querier.
func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier {
return nil
}
// RegisterInvariants registers the inflation module invariants.
func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}
// RegisterServices registers a gRPC query service to respond to the
// module-specific gRPC queries.
func (am AppModule) RegisterServices(cfg module.Configurator) {
types.RegisterMsgServer(cfg.MsgServer(), am.keeper)
types.RegisterQueryServer(cfg.QueryServer(), am.keeper)
}
func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {
// am.keeper.BeginBlock(ctx, req)
}
func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate {
// am.keeper.EndBlock(ctx, req)
return []abci.ValidatorUpdate{}
}
// InitGenesis performs genesis initialization for the inflation module. It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(data, &genesisState)
InitGenesis(ctx, am.keeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the inflation
// module.
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage {
gs := ExportGenesis(ctx, am.keeper)
return cdc.MustMarshalJSON(gs)
}
// ___________________________________________________________________________
// AppModuleSimulation functions
// 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{}
}

View File

@ -1,47 +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 evm module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding.
ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
// AminoCdc is a amino codec created to support amino JSON compatible msgs.
AminoCdc = codec.NewAminoCodec(amino)
)
const (
// Amino names
requestDASName = "evmos/das/MsgRequestDAS"
reportDASResultName = "evmos/das/MsgReportDASResult"
)
// 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),
&MsgRequestDAS{},
&MsgReportDASResult{},
)
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}
// RegisterLegacyAminoCodec required for EIP-712
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&MsgRequestDAS{}, requestDASName, nil)
cdc.RegisterConcrete(&MsgReportDASResult{}, reportDASResultName, nil)
}

View File

@ -1,8 +0,0 @@
package types
import errorsmod "cosmossdk.io/errors"
var (
ErrUnknownRequest = errorsmod.Register(ModuleName, 0, "request not found")
ErrInvalidGenesis = errorsmod.Register(ModuleName, 1, "invalid genesis")
)

View File

@ -1,11 +0,0 @@
package types
// Module event types
const (
EventTypeDASRequest = "das_request"
AttributeKeyRequestID = "request_id"
AttributeKeyStreamID = "stream_id"
AttributeKeyBatchHeaderHash = "batch_header_hash"
AttributeKeyNumBlobs = "num_blobs"
)

View File

@ -1,28 +0,0 @@
package types
const (
DefaultNextRequestID = 0
)
// NewGenesisState returns a new genesis state object for the module.
func NewGenesisState(nextRequestID uint64, requests []DASRequest, responses []DASResponse) *GenesisState {
return &GenesisState{
NextRequestID: nextRequestID,
Requests: requests,
Responses: responses,
}
}
// DefaultGenesisState returns the default genesis state for the module.
func DefaultGenesisState() *GenesisState {
return NewGenesisState(
DefaultNextRequestID,
[]DASRequest{},
[]DASResponse{},
)
}
// Validate performs basic validation of genesis data.
func (gs GenesisState) Validate() error {
return nil
}

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +0,0 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
type StakingKeeperRef interface {
GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool)
}

View File

@ -1,44 +0,0 @@
package types
import (
"encoding/binary"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// ModuleName The name that will be used throughout the module
ModuleName = "das"
// StoreKey Top level store key where all module items will be stored
StoreKey = ModuleName
)
// Key prefixes
var (
RequestKeyPrefix = []byte{0x00} // prefix for keys that store requests
ResponseKeyPrefix = []byte{0x01} // prefix for keys that store responses
NextRequestIDKey = []byte{0x02}
)
// GetKeyFromID returns the bytes to use as a key for a uint64 id
func GetKeyFromID(id uint64) []byte {
return Uint64ToBytes(id)
}
func GetResponseKey(requestID uint64, sampler sdk.ValAddress) []byte {
return append(GetKeyFromID(requestID), sampler.Bytes()...)
}
// Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys.
func Uint64ToBytes(id uint64) []byte {
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, uint64(id))
return bz
}
// Uint64FromBytes converts some fixed length bytes back into a uint64.
func Uint64FromBytes(bz []byte) uint64 {
return binary.BigEndian.Uint64(bz)
}

View File

@ -1,57 +0,0 @@
package types
import (
"encoding/hex"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
var _, _ sdk.Msg = &MsgRequestDAS{}, &MsgReportDASResult{}
func NewMsgRequestDAS(fromAddr sdk.AccAddress, streamID, hash string, numBlobs uint32) *MsgRequestDAS {
return &MsgRequestDAS{
Requester: fromAddr.String(),
StreamID: streamID,
BatchHeaderHash: hash,
NumBlobs: numBlobs,
}
}
func (msg MsgRequestDAS) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(msg.Requester)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func (msg MsgRequestDAS) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Requester)
if err != nil {
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid requester account address (%s)", err)
}
return nil
}
func (msg *MsgReportDASResult) GetSigners() []sdk.AccAddress {
samplerValAddr, err := sdk.ValAddressFromBech32(msg.Sampler)
if err != nil {
panic(err)
}
accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(samplerValAddr.Bytes()))
if err != nil {
panic(err)
}
return []sdk.AccAddress{accAddr}
}
func (msg *MsgReportDASResult) ValidateBasic() error {
_, err := sdk.ValAddressFromBech32(msg.Sampler)
if err != nil {
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sampler validator address (%s)", err)
}
return nil
}

View File

@ -1,511 +0,0 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: zgc/das/v1/query.proto
package types
import (
context "context"
fmt "fmt"
_ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/cosmos-sdk/codec/types"
_ "github.com/gogo/protobuf/gogoproto"
grpc1 "github.com/gogo/protobuf/grpc"
proto "github.com/gogo/protobuf/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"
_ "google.golang.org/protobuf/types/known/timestamppb"
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
type QueryNextRequestIDRequest struct {
}
func (m *QueryNextRequestIDRequest) Reset() { *m = QueryNextRequestIDRequest{} }
func (m *QueryNextRequestIDRequest) String() string { return proto.CompactTextString(m) }
func (*QueryNextRequestIDRequest) ProtoMessage() {}
func (*QueryNextRequestIDRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_d404c1962bca645f, []int{0}
}
func (m *QueryNextRequestIDRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryNextRequestIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryNextRequestIDRequest.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 *QueryNextRequestIDRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryNextRequestIDRequest.Merge(m, src)
}
func (m *QueryNextRequestIDRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryNextRequestIDRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryNextRequestIDRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryNextRequestIDRequest proto.InternalMessageInfo
type QueryNextRequestIDResponse struct {
NextRequestID uint64 `protobuf:"varint,1,opt,name=next_request_id,json=nextRequestId,proto3" json:"next_request_id,omitempty"`
}
func (m *QueryNextRequestIDResponse) Reset() { *m = QueryNextRequestIDResponse{} }
func (m *QueryNextRequestIDResponse) String() string { return proto.CompactTextString(m) }
func (*QueryNextRequestIDResponse) ProtoMessage() {}
func (*QueryNextRequestIDResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_d404c1962bca645f, []int{1}
}
func (m *QueryNextRequestIDResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryNextRequestIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryNextRequestIDResponse.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 *QueryNextRequestIDResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryNextRequestIDResponse.Merge(m, src)
}
func (m *QueryNextRequestIDResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryNextRequestIDResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryNextRequestIDResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryNextRequestIDResponse proto.InternalMessageInfo
func init() {
proto.RegisterType((*QueryNextRequestIDRequest)(nil), "zgc.das.v1.QueryNextRequestIDRequest")
proto.RegisterType((*QueryNextRequestIDResponse)(nil), "zgc.das.v1.QueryNextRequestIDResponse")
}
func init() { proto.RegisterFile("zgc/das/v1/query.proto", fileDescriptor_d404c1962bca645f) }
var fileDescriptor_d404c1962bca645f = []byte{
// 334 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xbf, 0x4b, 0x03, 0x31,
0x14, 0xc7, 0x2f, 0xa2, 0x0e, 0x81, 0x22, 0x1e, 0x22, 0xf6, 0x94, 0x54, 0x0b, 0xfe, 0x1a, 0x9a,
0xb4, 0x3a, 0xb9, 0x16, 0x41, 0x5c, 0x04, 0x5d, 0x04, 0x97, 0x92, 0xbb, 0x8b, 0x69, 0xa0, 0x97,
0x5c, 0x9b, 0x5c, 0x69, 0x3b, 0xba, 0xb8, 0x2a, 0xfe, 0x53, 0x1d, 0x0b, 0x2e, 0x4e, 0xa2, 0x57,
0xff, 0x10, 0xe9, 0xe5, 0x0e, 0xad, 0x28, 0x6e, 0xef, 0xbd, 0xef, 0xf7, 0x7d, 0xf3, 0xe1, 0x05,
0xae, 0x8f, 0x78, 0x40, 0x42, 0xaa, 0x49, 0xbf, 0x41, 0xba, 0x09, 0xeb, 0x0d, 0x71, 0xdc, 0x53,
0x46, 0xb9, 0x70, 0xc4, 0x03, 0x1c, 0x52, 0x8d, 0xfb, 0x0d, 0xaf, 0x1c, 0x28, 0x1d, 0x29, 0xdd,
0xca, 0x14, 0x62, 0x1b, 0x6b, 0xf3, 0xd6, 0xb8, 0xe2, 0xca, 0xce, 0x67, 0x55, 0x3e, 0xdd, 0xe2,
0x4a, 0xf1, 0x0e, 0x23, 0x34, 0x16, 0x84, 0x4a, 0xa9, 0x0c, 0x35, 0x42, 0xc9, 0x62, 0xa7, 0x9c,
0xab, 0x59, 0xe7, 0x27, 0xb7, 0x84, 0xca, 0xfc, 0x55, 0xaf, 0xf2, 0x53, 0x32, 0x22, 0x62, 0xda,
0xd0, 0x28, 0xb6, 0x86, 0xea, 0x26, 0x2c, 0x5f, 0xce, 0x28, 0x2f, 0xd8, 0xc0, 0x5c, 0xb1, 0x6e,
0xc2, 0xb4, 0x39, 0x3f, 0xcd, 0x8b, 0xea, 0x35, 0xf4, 0x7e, 0x13, 0x75, 0xac, 0xa4, 0x66, 0xee,
0x09, 0x5c, 0x91, 0x6c, 0x60, 0x5a, 0x3d, 0xab, 0xb4, 0x44, 0xb8, 0x01, 0xb6, 0xc1, 0xc1, 0x62,
0x73, 0x35, 0x7d, 0xad, 0x94, 0xe6, 0x77, 0x4a, 0xf2, 0x5b, 0x1b, 0x1e, 0x3d, 0x02, 0xb8, 0x94,
0x25, 0xbb, 0xf7, 0x00, 0xce, 0x5b, 0xdd, 0x5d, 0xfc, 0x75, 0x29, 0xfc, 0x27, 0x9b, 0xb7, 0xf7,
0x9f, 0xcd, 0x52, 0x56, 0xf7, 0xef, 0x9e, 0x3f, 0x9e, 0x16, 0x76, 0xdc, 0x0a, 0xa9, 0xf3, 0xa0,
0x4d, 0x85, 0x2c, 0x3e, 0x67, 0x46, 0x54, 0xcb, 0xd9, 0x6b, 0x22, 0x6c, 0x9e, 0x8d, 0xdf, 0x91,
0x33, 0x4e, 0x11, 0x98, 0xa4, 0x08, 0xbc, 0xa5, 0x08, 0x3c, 0x4c, 0x91, 0x33, 0x99, 0x22, 0xe7,
0x65, 0x8a, 0x9c, 0x9b, 0x43, 0x2e, 0x4c, 0x3b, 0xf1, 0x71, 0xa0, 0x22, 0x52, 0xe7, 0x1d, 0xea,
0x6b, 0x52, 0xe7, 0x35, 0x1b, 0x38, 0x28, 0x22, 0xcd, 0x30, 0x66, 0xda, 0x5f, 0xce, 0x2e, 0x7b,
0xfc, 0x19, 0x00, 0x00, 0xff, 0xff, 0xd5, 0x9e, 0xd6, 0x49, 0x0a, 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
// 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 {
NextRequestID(ctx context.Context, in *QueryNextRequestIDRequest, opts ...grpc.CallOption) (*QueryNextRequestIDResponse, error)
}
type queryClient struct {
cc grpc1.ClientConn
}
func NewQueryClient(cc grpc1.ClientConn) QueryClient {
return &queryClient{cc}
}
func (c *queryClient) NextRequestID(ctx context.Context, in *QueryNextRequestIDRequest, opts ...grpc.CallOption) (*QueryNextRequestIDResponse, error) {
out := new(QueryNextRequestIDResponse)
err := c.cc.Invoke(ctx, "/zgc.das.v1.Query/NextRequestID", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// QueryServer is the server API for Query service.
type QueryServer interface {
NextRequestID(context.Context, *QueryNextRequestIDRequest) (*QueryNextRequestIDResponse, error)
}
// UnimplementedQueryServer can be embedded to have forward compatible implementations.
type UnimplementedQueryServer struct {
}
func (*UnimplementedQueryServer) NextRequestID(ctx context.Context, req *QueryNextRequestIDRequest) (*QueryNextRequestIDResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method NextRequestID not implemented")
}
func RegisterQueryServer(s grpc1.Server, srv QueryServer) {
s.RegisterService(&_Query_serviceDesc, srv)
}
func _Query_NextRequestID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryNextRequestIDRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).NextRequestID(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/zgc.das.v1.Query/NextRequestID",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).NextRequestID(ctx, req.(*QueryNextRequestIDRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Query_serviceDesc = grpc.ServiceDesc{
ServiceName: "zgc.das.v1.Query",
HandlerType: (*QueryServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "NextRequestID",
Handler: _Query_NextRequestID_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "zgc/das/v1/query.proto",
}
func (m *QueryNextRequestIDRequest) 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 *QueryNextRequestIDRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryNextRequestIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryNextRequestIDResponse) 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 *QueryNextRequestIDResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryNextRequestIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.NextRequestID != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.NextRequestID))
i--
dAtA[i] = 0x8
}
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 *QueryNextRequestIDRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryNextRequestIDResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.NextRequestID != 0 {
n += 1 + sovQuery(uint64(m.NextRequestID))
}
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 *QueryNextRequestIDRequest) 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: QueryNextRequestIDRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryNextRequestIDRequest: 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 *QueryNextRequestIDResponse) 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: QueryNextRequestIDResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryNextRequestIDResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field NextRequestID", wireType)
}
m.NextRequestID = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.NextRequestID |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
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")
)

View File

@ -1,153 +0,0 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: zgc/das/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_NextRequestID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryNextRequestIDRequest
var metadata runtime.ServerMetadata
msg, err := client.NextRequestID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_NextRequestID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryNextRequestIDRequest
var metadata runtime.ServerMetadata
msg, err := server.NextRequestID(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_NextRequestID_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_NextRequestID_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_NextRequestID_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_NextRequestID_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_NextRequestID_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_NextRequestID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_Query_NextRequestID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0gchain", "das", "v1", "next-request-id"}, "", runtime.AssumeColonVerbOpt(false)))
)
var (
forward_Query_NextRequestID_0 = runtime.ForwardResponseMessage
)

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@ package cli
import ( import (
"fmt" "fmt"
"github.com/0glabs/0g-chain/x/das/v1/types" "github.com/0glabs/0g-chain/x/dasigners/v1/types"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -6,7 +6,6 @@ package types
import ( import (
context "context" context "context"
fmt "fmt" fmt "fmt"
_ "github.com/0glabs/0g-chain/x/das/v1/types"
_ "github.com/cosmos/cosmos-proto" _ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/cosmos-sdk/codec/types" _ "github.com/cosmos/cosmos-sdk/codec/types"
_ "github.com/gogo/protobuf/gogoproto" _ "github.com/gogo/protobuf/gogoproto"
@ -265,33 +264,32 @@ func init() {
func init() { proto.RegisterFile("zgc/dasigners/v1/tx.proto", fileDescriptor_8bfa0cc0bd2f98e0) } func init() { proto.RegisterFile("zgc/dasigners/v1/tx.proto", fileDescriptor_8bfa0cc0bd2f98e0) }
var fileDescriptor_8bfa0cc0bd2f98e0 = []byte{ var fileDescriptor_8bfa0cc0bd2f98e0 = []byte{
// 410 bytes of a gzipped FileDescriptorProto // 399 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x93, 0xcf, 0xae, 0xd2, 0x40, 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x93, 0xcf, 0xae, 0xd2, 0x40,
0x18, 0xc5, 0x5b, 0x4c, 0x30, 0x8c, 0x44, 0xa5, 0x21, 0xda, 0x56, 0x32, 0xc1, 0x9a, 0x18, 0x8c, 0x14, 0x87, 0x5b, 0x4c, 0x30, 0x8c, 0x44, 0xa5, 0x21, 0xda, 0x56, 0x32, 0xc1, 0x9a, 0x18, 0x8c,
0xb1, 0x03, 0xf8, 0x06, 0x1a, 0x97, 0x65, 0x51, 0xe2, 0xc6, 0x98, 0x98, 0x76, 0x18, 0x87, 0x06, 0xb1, 0x03, 0xf8, 0x06, 0x1a, 0x97, 0x65, 0x51, 0xe2, 0xc6, 0x98, 0x98, 0x76, 0x18, 0x87, 0x06,
0xe8, 0x34, 0x9d, 0x29, 0x01, 0x9e, 0xc2, 0x87, 0xf1, 0x21, 0x58, 0xb2, 0x74, 0xe9, 0x85, 0x17, 0xe8, 0x34, 0x9d, 0x29, 0x01, 0x9e, 0xc2, 0x87, 0xf1, 0x21, 0x58, 0xb2, 0x74, 0xe9, 0x85, 0x17,
0xb9, 0x61, 0xfa, 0x07, 0x6e, 0x4b, 0xb8, 0xec, 0xe6, 0x9b, 0xef, 0xd7, 0x73, 0x4e, 0x4f, 0x5a, 0xb9, 0x61, 0xfa, 0x07, 0x6e, 0x4b, 0xb8, 0xec, 0xe6, 0xcc, 0xf9, 0x7a, 0xbe, 0xd3, 0x5f, 0x5a,
0x60, 0x6c, 0x28, 0x46, 0x13, 0x8f, 0x07, 0x34, 0x24, 0x31, 0x47, 0xcb, 0x01, 0x12, 0x2b, 0x3b, 0x60, 0x6c, 0x28, 0x46, 0x13, 0x8f, 0x07, 0x34, 0x24, 0x31, 0x47, 0xcb, 0x01, 0x12, 0x2b, 0x3b,
0x8a, 0x99, 0x60, 0xda, 0xcb, 0x0d, 0xc5, 0x76, 0xb1, 0xb2, 0x97, 0x03, 0xd3, 0xc0, 0x8c, 0x2f, 0x8a, 0x99, 0x60, 0xda, 0xcb, 0x0d, 0xc5, 0x76, 0xd1, 0xb2, 0x97, 0x03, 0xd3, 0xc0, 0x8c, 0x2f,
0x18, 0xff, 0x25, 0xf7, 0x28, 0x1d, 0x52, 0xd8, 0x6c, 0x53, 0x46, 0x59, 0x7a, 0x7f, 0x3c, 0x65, 0x18, 0xff, 0x25, 0xfb, 0x28, 0x2d, 0x52, 0xd8, 0x6c, 0x53, 0x46, 0x59, 0x7a, 0x7f, 0x3c, 0x65,
0xb7, 0x06, 0x65, 0x8c, 0xce, 0x09, 0x92, 0x93, 0x9f, 0xfc, 0x46, 0x5e, 0xb8, 0xce, 0x56, 0x7a, 0xb7, 0x06, 0x65, 0x8c, 0xce, 0x09, 0x92, 0x95, 0x9f, 0xfc, 0x46, 0x5e, 0xb8, 0xce, 0x5a, 0xdd,
0x66, 0x7c, 0xb4, 0xa4, 0x24, 0x24, 0x3c, 0xc8, 0xa5, 0xba, 0x95, 0x48, 0xa7, 0x10, 0x92, 0xb0, 0x8a, 0xf8, 0xa4, 0x92, 0x84, 0x85, 0x41, 0xcb, 0xe1, 0xd4, 0x25, 0x34, 0xe0, 0x82, 0xc4, 0x63,
0x30, 0x68, 0x39, 0x9c, 0xba, 0x84, 0x06, 0x5c, 0x90, 0x78, 0x2c, 0x77, 0x5a, 0x1f, 0xd4, 0x53, 0xd9, 0xd3, 0xfa, 0xa0, 0x9e, 0x52, 0xba, 0xda, 0x55, 0x7b, 0xcf, 0x86, 0xba, 0x5d, 0xde, 0xd2,
0x4a, 0x57, 0xbb, 0x6a, 0xef, 0xd9, 0x50, 0xb7, 0xcb, 0xf9, 0xed, 0x94, 0x74, 0x33, 0x4e, 0xeb, 0x4e, 0x49, 0x37, 0xe3, 0xb4, 0x0e, 0x68, 0x1c, 0x4f, 0x9e, 0x48, 0x62, 0xa2, 0xd7, 0xba, 0x6a,
0x80, 0xc6, 0xf1, 0xe4, 0x89, 0x24, 0x26, 0x7a, 0xad, 0xab, 0xf6, 0x9a, 0xee, 0xe9, 0xc2, 0x7a, 0xaf, 0xe9, 0x9e, 0x2e, 0xac, 0x37, 0xc0, 0xa8, 0x48, 0x5c, 0xc2, 0x23, 0x16, 0x72, 0x62, 0x7d,
0x03, 0x8c, 0x8a, 0x89, 0x4b, 0x78, 0xc4, 0x42, 0x4e, 0xac, 0xaf, 0xe0, 0x85, 0xc3, 0xe9, 0xf7, 0x05, 0x2f, 0x1c, 0x4e, 0xbf, 0x47, 0x13, 0x4f, 0x90, 0x31, 0xc3, 0x33, 0x22, 0x34, 0x1d, 0x3c,
0x68, 0xe2, 0x09, 0x32, 0x66, 0x78, 0x46, 0x84, 0xa6, 0x83, 0xa7, 0x1e, 0xc6, 0x2c, 0x09, 0x85, 0xf5, 0x30, 0x66, 0x49, 0x28, 0xe4, 0x02, 0x0d, 0x37, 0x2f, 0xb5, 0x57, 0xa0, 0xce, 0x25, 0x23,
0x0c, 0xd0, 0x70, 0xf3, 0x51, 0x7b, 0x05, 0xea, 0x5c, 0x32, 0xd2, 0xa4, 0xe1, 0x66, 0x93, 0x65, 0x25, 0x0d, 0x37, 0xab, 0x2c, 0x03, 0xbc, 0x2e, 0x0d, 0x29, 0xe6, 0x8f, 0x40, 0xfb, 0x4c, 0x3e,
0x80, 0xd7, 0x25, 0x91, 0x42, 0x7f, 0x04, 0xda, 0x67, 0xe6, 0x23, 0xb2, 0x12, 0xdf, 0x22, 0x86, 0x22, 0x2b, 0xf1, 0x2d, 0x62, 0x78, 0x7a, 0x45, 0x72, 0xfd, 0x65, 0x20, 0xe8, 0x5c, 0x9a, 0x97,
0xa7, 0x57, 0x4c, 0xae, 0xbf, 0x0c, 0x04, 0x9d, 0x4b, 0x7a, 0xb9, 0xdf, 0xf0, 0x6f, 0x0d, 0x3c, 0xfb, 0x86, 0x7f, 0x6b, 0xe0, 0x89, 0xc3, 0xa9, 0xe6, 0x83, 0xe7, 0xa5, 0x58, 0xdf, 0x55, 0x63,
0x71, 0x38, 0xd5, 0x7c, 0xf0, 0xbc, 0x54, 0xeb, 0xbb, 0x6a, 0x8d, 0x95, 0x5a, 0xcc, 0x8f, 0x37, 0xac, 0xc4, 0x62, 0x7e, 0xbc, 0x01, 0xca, 0x5d, 0xda, 0x4f, 0xd0, 0x7c, 0x10, 0xdc, 0xdb, 0x8b,
0x40, 0xb9, 0x97, 0xf6, 0x13, 0x34, 0x1f, 0x14, 0xf7, 0xf6, 0xe2, 0xc3, 0xe7, 0x88, 0xf9, 0xe1, 0x0f, 0x9f, 0x23, 0xe6, 0x87, 0x47, 0x91, 0x62, 0xfa, 0x0c, 0xb4, 0xaa, 0xb1, 0xbd, 0xbf, 0xba,
0x51, 0xa4, 0x50, 0x9f, 0x81, 0x56, 0xb5, 0xb6, 0xf7, 0x57, 0xf3, 0x15, 0x9c, 0x69, 0xdf, 0xc6, 0x5f, 0xc1, 0x99, 0xf6, 0x6d, 0x5c, 0x2e, 0xfb, 0xe2, 0x6c, 0xef, 0xa0, 0xb2, 0xdd, 0x43, 0x75,
0xe5, 0x66, 0x5f, 0x9c, 0xed, 0x1d, 0x54, 0xb6, 0x7b, 0xa8, 0xee, 0xf6, 0x50, 0xfd, 0xbf, 0x87, 0xb7, 0x87, 0xea, 0xff, 0x3d, 0x54, 0xff, 0x1c, 0xa0, 0xb2, 0x3b, 0x40, 0xe5, 0xdf, 0x01, 0x2a,
0xea, 0x9f, 0x03, 0x54, 0x76, 0x07, 0xa8, 0xfc, 0x3b, 0x40, 0xe5, 0x07, 0xa2, 0x81, 0x98, 0x26, 0x3f, 0x10, 0x0d, 0xc4, 0x34, 0xf1, 0x6d, 0xcc, 0x16, 0xa8, 0x4f, 0xe7, 0x9e, 0xcf, 0x51, 0x9f,
0xbe, 0x8d, 0xd9, 0x02, 0xf5, 0xe9, 0xdc, 0xf3, 0x39, 0xea, 0xd3, 0x4f, 0x78, 0xea, 0x05, 0x21, 0x7e, 0xc2, 0x53, 0x2f, 0x08, 0xd1, 0xaa, 0xf4, 0x6b, 0xad, 0x23, 0xc2, 0xfd, 0xba, 0xfc, 0xbc,
0x5a, 0x95, 0x7e, 0xba, 0x75, 0x44, 0xb8, 0x5f, 0x97, 0x9f, 0xf7, 0xe7, 0xfb, 0x00, 0x00, 0x00, 0x3f, 0xdf, 0x07, 0x00, 0x00, 0xff, 0xff, 0xc6, 0x5a, 0xce, 0x9a, 0x7b, 0x03, 0x00, 0x00,
0xff, 0xff, 0xa3, 0x4c, 0x19, 0x64, 0x95, 0x03, 0x00, 0x00,
} }
// Reference imports to suppress errors if they are not otherwise used. // Reference imports to suppress errors if they are not otherwise used.

View File

@ -9,64 +9,57 @@ import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/evmutil/types" "github.com/0glabs/0g-chain/x/evmutil/types"
) )
const ( // ConversionMultiplier is the conversion multiplier between evm denom and gas denom
// EvmDenom is the gas denom used by the evm var ConversionMultiplier = sdkmath.NewInt(chaincfg.GasDenomConversionMultiplier)
EvmDenom = "neuron"
// CosmosDenom is the gas denom used by the 0g-chain app
CosmosDenom = "ua0gi"
)
// ConversionMultiplier is the conversion multiplier between neuron and ua0gi
var ConversionMultiplier = sdkmath.NewInt(1_000_000_000_000)
var _ evmtypes.BankKeeper = EvmBankKeeper{} var _ evmtypes.BankKeeper = EvmBankKeeper{}
// EvmBankKeeper is a BankKeeper wrapper for the x/evm module to allow the use // EvmBankKeeper is a BankKeeper wrapper for the x/evm module to allow the use
// of the 18 decimal neuron coin on the evm. // of the 18 decimal evm denom coin on the evm.
// x/evm consumes gas and send coins by minting and burning neuron coins in its module // x/evm consumes gas and send coins by minting and burning evm denom coins in its module
// account and then sending the funds to the target account. // account and then sending the funds to the target account.
// This keeper uses both the a0gi coin and a separate neuron balance to manage the // This keeper uses both the gas denom coin and a separate evm denom balance to manage the
// extra percision needed by the evm. // extra percision needed by the evm.
type EvmBankKeeper struct { type EvmBankKeeper struct {
neuronKeeper Keeper evmDenomKeeper Keeper
bk types.BankKeeper bk types.BankKeeper
ak types.AccountKeeper ak types.AccountKeeper
} }
func NewEvmBankKeeper(neuronKeeper Keeper, bk types.BankKeeper, ak types.AccountKeeper) EvmBankKeeper { func NewEvmBankKeeper(baseKeeper Keeper, bk types.BankKeeper, ak types.AccountKeeper) EvmBankKeeper {
return EvmBankKeeper{ return EvmBankKeeper{
neuronKeeper: neuronKeeper, evmDenomKeeper: baseKeeper,
bk: bk, bk: bk,
ak: ak, ak: ak,
} }
} }
// GetBalance returns the total **spendable** balance of neuron for a given account by address. // GetBalance returns the total **spendable** balance of evm denom for a given account by address.
func (k EvmBankKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { func (k EvmBankKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin {
if denom != EvmDenom { if denom != chaincfg.EvmDenom {
panic(fmt.Errorf("only evm denom %s is supported by EvmBankKeeper", EvmDenom)) panic(fmt.Errorf("only evm denom %s is supported by EvmBankKeeper", chaincfg.EvmDenom))
} }
spendableCoins := k.bk.SpendableCoins(ctx, addr) spendableCoins := k.bk.SpendableCoins(ctx, addr)
cosmosDenomFromBank := spendableCoins.AmountOf(CosmosDenom) gasDenomFromBank := spendableCoins.AmountOf(chaincfg.GasDenom)
evmDenomFromBank := spendableCoins.AmountOf(EvmDenom) evmDenomFromBank := spendableCoins.AmountOf(chaincfg.EvmDenom)
evmDenomFromEvmBank := k.neuronKeeper.GetBalance(ctx, addr) evmDenomFromEvmBank := k.evmDenomKeeper.GetBalance(ctx, addr)
var total sdkmath.Int var total sdkmath.Int
if cosmosDenomFromBank.IsPositive() { if gasDenomFromBank.IsPositive() {
total = cosmosDenomFromBank.Mul(ConversionMultiplier).Add(evmDenomFromBank).Add(evmDenomFromEvmBank) total = gasDenomFromBank.Mul(ConversionMultiplier).Add(evmDenomFromBank).Add(evmDenomFromEvmBank)
} else { } else {
total = evmDenomFromBank.Add(evmDenomFromEvmBank) total = evmDenomFromBank.Add(evmDenomFromEvmBank)
} }
return sdk.NewCoin(EvmDenom, total) return sdk.NewCoin(chaincfg.EvmDenom, total)
} }
// SendCoins transfers neuron coins from a AccAddress to an AccAddress. // SendCoins transfers evm denom coins from a AccAddress to an AccAddress.
func (k EvmBankKeeper) SendCoins(ctx sdk.Context, senderAddr sdk.AccAddress, recipientAddr sdk.AccAddress, amt sdk.Coins) error { func (k EvmBankKeeper) SendCoins(ctx sdk.Context, senderAddr sdk.AccAddress, recipientAddr sdk.AccAddress, amt sdk.Coins) error {
// SendCoins method is not used by the evm module, but is required by the // SendCoins method is not used by the evm module, but is required by the
// evmtypes.BankKeeper interface. This must be updated if the evm module // evmtypes.BankKeeper interface. This must be updated if the evm module
@ -74,148 +67,148 @@ func (k EvmBankKeeper) SendCoins(ctx sdk.Context, senderAddr sdk.AccAddress, rec
panic("not implemented") panic("not implemented")
} }
// SendCoinsFromModuleToAccount transfers neuron coins from a ModuleAccount to an AccAddress. // SendCoinsFromModuleToAccount transfers evm denom coins from a ModuleAccount to an AccAddress.
// It will panic if the module account does not exist. An error is returned if the recipient // It will panic if the module account does not exist. An error is returned if the recipient
// address is black-listed or if sending the tokens fails. // address is black-listed or if sending the tokens fails.
func (k EvmBankKeeper) SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error { func (k EvmBankKeeper) SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error {
ua0gi, neuron, err := SplitNeuronCoins(amt) gasDenomCoin, baseDemonCnt, err := SplitEvmDenomCoins(amt)
if err != nil { if err != nil {
return err return err
} }
if ua0gi.Amount.IsPositive() { if gasDenomCoin.Amount.IsPositive() {
if err := k.bk.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, sdk.NewCoins(ua0gi)); err != nil { if err := k.bk.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, sdk.NewCoins(gasDenomCoin)); err != nil {
return err return err
} }
} }
senderAddr := k.GetModuleAddress(senderModule) senderAddr := k.GetModuleAddress(senderModule)
if err := k.ConvertOneUa0giToNeuronIfNeeded(ctx, senderAddr, neuron); err != nil { if err := k.ConvertOneGasDenomToEvmDenomIfNeeded(ctx, senderAddr, baseDemonCnt); err != nil {
return err return err
} }
if err := k.neuronKeeper.SendBalance(ctx, senderAddr, recipientAddr, neuron); err != nil { if err := k.evmDenomKeeper.SendBalance(ctx, senderAddr, recipientAddr, baseDemonCnt); err != nil {
return err return err
} }
return k.ConvertNeuronToUa0gi(ctx, recipientAddr) return k.ConvertEvmDenomToGasDenom(ctx, recipientAddr)
} }
// SendCoinsFromAccountToModule transfers neuron coins from an AccAddress to a ModuleAccount. // SendCoinsFromAccountToModule transfers evm denom coins from an AccAddress to a ModuleAccount.
// It will panic if the module account does not exist. // It will panic if the module account does not exist.
func (k EvmBankKeeper) SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error { func (k EvmBankKeeper) SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error {
ua0gi, neuronNeeded, err := SplitNeuronCoins(amt) gasDenomCoin, evmDenomCnt, err := SplitEvmDenomCoins(amt)
if err != nil { if err != nil {
return err return err
} }
if ua0gi.IsPositive() { if gasDenomCoin.IsPositive() {
if err := k.bk.SendCoinsFromAccountToModule(ctx, senderAddr, recipientModule, sdk.NewCoins(ua0gi)); err != nil { if err := k.bk.SendCoinsFromAccountToModule(ctx, senderAddr, recipientModule, sdk.NewCoins(gasDenomCoin)); err != nil {
return err return err
} }
} }
if err := k.ConvertOneUa0giToNeuronIfNeeded(ctx, senderAddr, neuronNeeded); err != nil { if err := k.ConvertOneGasDenomToEvmDenomIfNeeded(ctx, senderAddr, evmDenomCnt); err != nil {
return err return err
} }
recipientAddr := k.GetModuleAddress(recipientModule) recipientAddr := k.GetModuleAddress(recipientModule)
if err := k.neuronKeeper.SendBalance(ctx, senderAddr, recipientAddr, neuronNeeded); err != nil { if err := k.evmDenomKeeper.SendBalance(ctx, senderAddr, recipientAddr, evmDenomCnt); err != nil {
return err return err
} }
return k.ConvertNeuronToUa0gi(ctx, recipientAddr) return k.ConvertEvmDenomToGasDenom(ctx, recipientAddr)
} }
// MintCoins mints neuron coins by minting the equivalent a0gi coins and any remaining neuron coins. // MintCoins mints evm denom coins by minting the equivalent gas denom coins and any remaining evm denom coins.
// It will panic if the module account does not exist or is unauthorized. // It will panic if the module account does not exist or is unauthorized.
func (k EvmBankKeeper) MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error { func (k EvmBankKeeper) MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error {
ua0gi, neuron, err := SplitNeuronCoins(amt) gasDenomCoin, baseDemonCnt, err := SplitEvmDenomCoins(amt)
if err != nil { if err != nil {
return err return err
} }
if ua0gi.IsPositive() { if gasDenomCoin.IsPositive() {
if err := k.bk.MintCoins(ctx, moduleName, sdk.NewCoins(ua0gi)); err != nil { if err := k.bk.MintCoins(ctx, moduleName, sdk.NewCoins(gasDenomCoin)); err != nil {
return err return err
} }
} }
recipientAddr := k.GetModuleAddress(moduleName) recipientAddr := k.GetModuleAddress(moduleName)
if err := k.neuronKeeper.AddBalance(ctx, recipientAddr, neuron); err != nil { if err := k.evmDenomKeeper.AddBalance(ctx, recipientAddr, baseDemonCnt); err != nil {
return err return err
} }
return k.ConvertNeuronToUa0gi(ctx, recipientAddr) return k.ConvertEvmDenomToGasDenom(ctx, recipientAddr)
} }
// BurnCoins burns neuron coins by burning the equivalent a0gi coins and any remaining neuron coins. // BurnCoins burns evm denom coins by burning the equivalent gas denom coins and any remaining evm denom coins.
// It will panic if the module account does not exist or is unauthorized. // It will panic if the module account does not exist or is unauthorized.
func (k EvmBankKeeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error { func (k EvmBankKeeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error {
ua0gi, neuron, err := SplitNeuronCoins(amt) gasDenomCoin, baseDemonCnt, err := SplitEvmDenomCoins(amt)
if err != nil { if err != nil {
return err return err
} }
if ua0gi.IsPositive() { if gasDenomCoin.IsPositive() {
if err := k.bk.BurnCoins(ctx, moduleName, sdk.NewCoins(ua0gi)); err != nil { if err := k.bk.BurnCoins(ctx, moduleName, sdk.NewCoins(gasDenomCoin)); err != nil {
return err return err
} }
} }
moduleAddr := k.GetModuleAddress(moduleName) moduleAddr := k.GetModuleAddress(moduleName)
if err := k.ConvertOneUa0giToNeuronIfNeeded(ctx, moduleAddr, neuron); err != nil { if err := k.ConvertOneGasDenomToEvmDenomIfNeeded(ctx, moduleAddr, baseDemonCnt); err != nil {
return err return err
} }
return k.neuronKeeper.RemoveBalance(ctx, moduleAddr, neuron) return k.evmDenomKeeper.RemoveBalance(ctx, moduleAddr, baseDemonCnt)
} }
// ConvertOneUa0giToNeuronIfNeeded converts 1 a0gi to neuron for an address if // ConvertOnegasDenomToEvmDenomIfNeeded converts 1 gas denom to evm denom for an address if
// its neuron balance is smaller than the neuronNeeded amount. // its evm denom balance is smaller than the evmDenomCnt amount.
func (k EvmBankKeeper) ConvertOneUa0giToNeuronIfNeeded(ctx sdk.Context, addr sdk.AccAddress, neuronNeeded sdkmath.Int) error { func (k EvmBankKeeper) ConvertOneGasDenomToEvmDenomIfNeeded(ctx sdk.Context, addr sdk.AccAddress, evmDenomCnt sdkmath.Int) error {
neuronBal := k.neuronKeeper.GetBalance(ctx, addr) evmDenomBal := k.evmDenomKeeper.GetBalance(ctx, addr)
if neuronBal.GTE(neuronNeeded) { if evmDenomBal.GTE(evmDenomCnt) {
return nil return nil
} }
ua0giToStore := sdk.NewCoins(sdk.NewCoin(CosmosDenom, sdk.OneInt())) gasDenomToStore := sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdk.OneInt()))
if err := k.bk.SendCoinsFromAccountToModule(ctx, addr, types.ModuleName, ua0giToStore); err != nil { if err := k.bk.SendCoinsFromAccountToModule(ctx, addr, types.ModuleName, gasDenomToStore); err != nil {
return err return err
} }
// add 1a0gi equivalent of neuron to addr // add 1 gas denom equivalent of evm denom to addr
neuronToReceive := ConversionMultiplier evmDenomToReceive := ConversionMultiplier
if err := k.neuronKeeper.AddBalance(ctx, addr, neuronToReceive); err != nil { if err := k.evmDenomKeeper.AddBalance(ctx, addr, evmDenomToReceive); err != nil {
return err return err
} }
return nil return nil
} }
// ConvertNeuronToA0gi converts all available neuron to a0gi for a given AccAddress. // ConvertEvmDenomTogasDenom converts all available evm denom to gas denom for a given AccAddress.
func (k EvmBankKeeper) ConvertNeuronToUa0gi(ctx sdk.Context, addr sdk.AccAddress) error { func (k EvmBankKeeper) ConvertEvmDenomToGasDenom(ctx sdk.Context, addr sdk.AccAddress) error {
totalNeuron := k.neuronKeeper.GetBalance(ctx, addr) totalEvmDenom := k.evmDenomKeeper.GetBalance(ctx, addr)
ua0gi, _, err := SplitNeuronCoins(sdk.NewCoins(sdk.NewCoin(EvmDenom, totalNeuron))) gasDenomCoin, _, err := SplitEvmDenomCoins(sdk.NewCoins(sdk.NewCoin(chaincfg.EvmDenom, totalEvmDenom)))
if err != nil { if err != nil {
return err return err
} }
// do nothing if account does not have enough neuron for a single a0gi // do nothing if account does not have enough evm denom for a single gas denom
ua0giToReceive := ua0gi.Amount gasDenomToReceive := gasDenomCoin.Amount
if !ua0giToReceive.IsPositive() { if !gasDenomToReceive.IsPositive() {
return nil return nil
} }
// remove neuron used for converting to ua0gi // remove evm denom used for converting to gas denom
neuronToBurn := ua0giToReceive.Mul(ConversionMultiplier) evmDenomToBurn := gasDenomToReceive.Mul(ConversionMultiplier)
finalBal := totalNeuron.Sub(neuronToBurn) finalBal := totalEvmDenom.Sub(evmDenomToBurn)
if err := k.neuronKeeper.SetBalance(ctx, addr, finalBal); err != nil { if err := k.evmDenomKeeper.SetBalance(ctx, addr, finalBal); err != nil {
return err return err
} }
fromAddr := k.GetModuleAddress(types.ModuleName) fromAddr := k.GetModuleAddress(types.ModuleName)
if err := k.bk.SendCoins(ctx, fromAddr, addr, sdk.NewCoins(ua0gi)); err != nil { if err := k.bk.SendCoins(ctx, fromAddr, addr, sdk.NewCoins(gasDenomCoin)); err != nil {
return err return err
} }
@ -230,35 +223,35 @@ func (k EvmBankKeeper) GetModuleAddress(moduleName string) sdk.AccAddress {
return addr return addr
} }
// SplitNeuronCoins splits neuron coins to the equivalent a0gi coins and any remaining neuron balance. // SplitEvmDenomCoins splits evm denom coins to the equivalent gas denom coins and any remaining evm denom balance.
// An error will be returned if the coins are not valid or if the coins are not the neuron denom. // An error will be returned if the coins are not valid or if the coins are not the evm denom.
func SplitNeuronCoins(coins sdk.Coins) (sdk.Coin, sdkmath.Int, error) { func SplitEvmDenomCoins(coins sdk.Coins) (sdk.Coin, sdkmath.Int, error) {
neuron := sdk.ZeroInt() baseDemonCnt := sdk.ZeroInt()
ua0gi := sdk.NewCoin(CosmosDenom, sdk.ZeroInt()) gasDenomAmt := sdk.NewCoin(chaincfg.GasDenom, sdk.ZeroInt())
if len(coins) == 0 { if len(coins) == 0 {
return ua0gi, neuron, nil return gasDenomAmt, baseDemonCnt, nil
} }
if err := ValidateEvmCoins(coins); err != nil { if err := ValidateEvmCoins(coins); err != nil {
return ua0gi, neuron, err return gasDenomAmt, baseDemonCnt, err
} }
// note: we should always have len(coins) == 1 here since coins cannot have dup denoms after we validate. // note: we should always have len(coins) == 1 here since coins cannot have dup denoms after we validate.
coin := coins[0] coin := coins[0]
remainingBalance := coin.Amount.Mod(ConversionMultiplier) remainingBalance := coin.Amount.Mod(ConversionMultiplier)
if remainingBalance.IsPositive() { if remainingBalance.IsPositive() {
neuron = remainingBalance baseDemonCnt = remainingBalance
} }
ua0giAmount := coin.Amount.Quo(ConversionMultiplier) gasDenomAmount := coin.Amount.Quo(ConversionMultiplier)
if ua0giAmount.IsPositive() { if gasDenomAmount.IsPositive() {
ua0gi = sdk.NewCoin(CosmosDenom, ua0giAmount) gasDenomAmt = sdk.NewCoin(chaincfg.GasDenom, gasDenomAmount)
} }
return ua0gi, neuron, nil return gasDenomAmt, baseDemonCnt, nil
} }
// ValidateEvmCoins validates the coins from evm is valid and is the EvmDenom (neuron). // ValidateEvmCoins validates the coins from evm is valid and is the evm denom.
func ValidateEvmCoins(coins sdk.Coins) error { func ValidateEvmCoins(coins sdk.Coins) error {
if len(coins) == 0 { if len(coins) == 0 {
return nil return nil
@ -269,9 +262,9 @@ func ValidateEvmCoins(coins sdk.Coins) error {
return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coins.String()) return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coins.String())
} }
// validate that coin denom is neuron // validate that coin denom is evm denom
if len(coins) != 1 || coins[0].Denom != EvmDenom { if len(coins) != 1 || coins[0].Denom != chaincfg.EvmDenom {
errMsg := fmt.Sprintf("invalid evm coin denom, only %s is supported", EvmDenom) errMsg := fmt.Sprintf("invalid evm coin denom, only %s is supported", chaincfg.EvmDenom)
return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, errMsg) return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, errMsg)
} }

View File

@ -6,6 +6,7 @@ import (
"time" "time"
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/evmutil/keeper" "github.com/0glabs/0g-chain/x/evmutil/keeper"
"github.com/0glabs/0g-chain/x/evmutil/testutil" "github.com/0glabs/0g-chain/x/evmutil/testutil"
"github.com/0glabs/0g-chain/x/evmutil/types" "github.com/0glabs/0g-chain/x/evmutil/types"
@ -26,8 +27,8 @@ func (suite *evmBankKeeperTestSuite) SetupTest() {
} }
func (suite *evmBankKeeperTestSuite) TestGetBalance_ReturnsSpendable() { func (suite *evmBankKeeperTestSuite) TestGetBalance_ReturnsSpendable() {
startingCoins := sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10)) startingCoins := sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10))
startingNeuron := sdkmath.NewInt(100) startingEvmDenom := sdkmath.NewInt(100)
now := tmtime.Now() now := tmtime.Now()
endTime := now.Add(24 * time.Hour) endTime := now.Add(24 * time.Hour)
@ -37,24 +38,26 @@ func (suite *evmBankKeeperTestSuite) TestGetBalance_ReturnsSpendable() {
err := suite.App.FundAccount(suite.Ctx, suite.Addrs[0], startingCoins) err := suite.App.FundAccount(suite.Ctx, suite.Addrs[0], startingCoins)
suite.Require().NoError(err) suite.Require().NoError(err)
err = suite.Keeper.SetBalance(suite.Ctx, suite.Addrs[0], startingNeuron) err = suite.Keeper.SetBalance(suite.Ctx, suite.Addrs[0], startingEvmDenom)
suite.Require().NoError(err) suite.Require().NoError(err)
coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "neuron") coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.EvmDenom)
suite.Require().Equal(startingNeuron, coin.Amount) suite.Require().Equal(startingEvmDenom, coin.Amount)
ctx := suite.Ctx.WithBlockTime(now.Add(12 * time.Hour)) ctx := suite.Ctx.WithBlockTime(now.Add(12 * time.Hour))
coin = suite.EvmBankKeeper.GetBalance(ctx, suite.Addrs[0], "neuron") coin = suite.EvmBankKeeper.GetBalance(ctx, suite.Addrs[0], chaincfg.EvmDenom)
suite.Require().Equal(sdkmath.NewIntFromUint64(5_000_000_000_100), coin.Amount) suite.Require().Equal(sdkmath.NewIntFromUint64(5_000_000_000_100), coin.Amount)
} }
func (suite *evmBankKeeperTestSuite) TestGetBalance_NotEvmDenom() { func (suite *evmBankKeeperTestSuite) TestGetBalance_NotEvmDenom() {
suite.Require().Panics(func() { suite.Require().Panics(func() {
suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ua0gi") suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.GasDenom)
}) })
suite.Require().Panics(func() { suite.Require().Panics(func() {
suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "busd") suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "busd")
}) })
} }
func (suite *evmBankKeeperTestSuite) TestGetBalance() { func (suite *evmBankKeeperTestSuite) TestGetBalance() {
tests := []struct { tests := []struct {
name string name string
@ -62,41 +65,41 @@ func (suite *evmBankKeeperTestSuite) TestGetBalance() {
expAmount sdkmath.Int expAmount sdkmath.Int
}{ }{
{ {
"ua0gi with neuron", "gas denom with evm denom",
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 100), sdk.NewInt64Coin(chaincfg.EvmDenom, 100),
sdk.NewInt64Coin("ua0gi", 10), sdk.NewInt64Coin(chaincfg.GasDenom, 10),
), ),
sdk.NewIntFromBigInt(makeBigIntByString("10000000000100")), sdkmath.NewInt(10_000_000_000_100),
}, },
{ {
"just neuron", "just evm denom",
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 100), sdk.NewInt64Coin(chaincfg.EvmDenom, 100),
sdk.NewInt64Coin("busd", 100), sdk.NewInt64Coin("busd", 100),
), ),
sdkmath.NewInt(100), sdkmath.NewInt(100),
}, },
{ {
"just ua0gi", "just gas denom",
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("ua0gi", 10), sdk.NewInt64Coin(chaincfg.GasDenom, 10),
sdk.NewInt64Coin("busd", 100), sdk.NewInt64Coin("busd", 100),
), ),
sdk.NewIntFromBigInt(makeBigIntByString("10000000000000")), sdkmath.NewInt(10_000_000_000_000),
}, },
{ {
"no ua0gi or neuron", "no gas denom or evm denom",
sdk.NewCoins(), sdk.NewCoins(),
sdk.ZeroInt(), sdk.ZeroInt(),
}, },
{ {
"with avaka that is more than 1 ua0gi", "with avaka that is more than 1 gas denom",
sdk.NewCoins( sdk.NewCoins(
sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("20000000000220"))), sdk.NewInt64Coin(chaincfg.EvmDenom, 20_000_000_000_220),
sdk.NewInt64Coin("ua0gi", 11), sdk.NewInt64Coin(chaincfg.GasDenom, 11),
), ),
sdk.NewIntFromBigInt(makeBigIntByString("31000000000220")), sdkmath.NewInt(31_000_000_000_220),
}, },
} }
@ -105,15 +108,16 @@ func (suite *evmBankKeeperTestSuite) TestGetBalance() {
suite.SetupTest() suite.SetupTest()
suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingAmount) suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingAmount)
coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "neuron") coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.EvmDenom)
suite.Require().Equal(tt.expAmount, coin.Amount) suite.Require().Equal(tt.expAmount, coin.Amount)
}) })
} }
} }
func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() { func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() {
startingModuleCoins := sdk.NewCoins( startingModuleCoins := sdk.NewCoins(
sdk.NewInt64Coin("neuron", 200), sdk.NewInt64Coin(chaincfg.EvmDenom, 200),
sdk.NewInt64Coin("ua0gi", 100), sdk.NewInt64Coin(chaincfg.GasDenom, 100),
) )
tests := []struct { tests := []struct {
name string name string
@ -123,102 +127,102 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() {
hasErr bool hasErr bool
}{ }{
{ {
"send more than 1 ua0gi", "send more than 1 gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("12000000000010")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 12_000_000_000_010)),
sdk.Coins{}, sdk.Coins{},
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 10), sdk.NewInt64Coin(chaincfg.EvmDenom, 10),
sdk.NewInt64Coin("ua0gi", 12), sdk.NewInt64Coin(chaincfg.GasDenom, 12),
), ),
false, false,
}, },
{ {
"send less than 1 ua0gi", "send less than 1 gas denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 122)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 122)),
sdk.Coins{}, sdk.Coins{},
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 122), sdk.NewInt64Coin(chaincfg.EvmDenom, 122),
sdk.NewInt64Coin("ua0gi", 0), sdk.NewInt64Coin(chaincfg.GasDenom, 0),
), ),
false, false,
}, },
{ {
"send an exact amount of ua0gi", "send an exact amount of gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("98000000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 98_000_000_000_000)),
sdk.Coins{}, sdk.Coins{},
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 0), sdk.NewInt64Coin(chaincfg.EvmDenom, 0o0),
sdk.NewInt64Coin("ua0gi", 98), sdk.NewInt64Coin(chaincfg.GasDenom, 98),
), ),
false, false,
}, },
{ {
"send no neuron", "send no evm denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 0)),
sdk.Coins{}, sdk.Coins{},
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 0), sdk.NewInt64Coin(chaincfg.EvmDenom, 0),
sdk.NewInt64Coin("ua0gi", 0), sdk.NewInt64Coin(chaincfg.GasDenom, 0),
), ),
false, false,
}, },
{ {
"errors if sending other coins", "errors if sending other coins",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 500), sdk.NewInt64Coin("busd", 1000)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 500), sdk.NewInt64Coin("busd", 1000)),
sdk.Coins{}, sdk.Coins{},
sdk.Coins{}, sdk.Coins{},
true, true,
}, },
{ {
"errors if not enough total neuron to cover", "errors if not enough total evm denom to cover",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("100000000001000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_001_000)),
sdk.Coins{}, sdk.Coins{},
sdk.Coins{}, sdk.Coins{},
true, true,
}, },
{ {
"errors if not enough ua0gi to cover", "errors if not enough gas denom to cover",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("200000000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 200_000_000_000_000)),
sdk.Coins{}, sdk.Coins{},
sdk.Coins{}, sdk.Coins{},
true, true,
}, },
{ {
"converts receiver's neuron to ua0gi if there's enough neuron after the transfer", "converts receiver's evm denom to gas denom if there's enough evm denom after the transfer",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("99000000000200")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 99_000_000_000_200)),
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 999_999_999_900), sdk.NewInt64Coin(chaincfg.EvmDenom, 999_999_999_900),
sdk.NewInt64Coin("ua0gi", 1), sdk.NewInt64Coin(chaincfg.GasDenom, 1),
), ),
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 100), sdk.NewInt64Coin(chaincfg.EvmDenom, 100),
sdk.NewInt64Coin("ua0gi", 101), sdk.NewInt64Coin(chaincfg.GasDenom, 101),
), ),
false, false,
}, },
{ {
"converts all of receiver's neuron to ua0gi even if somehow receiver has more than 1a0gi of neuron", "converts all of receiver's evm denom to gas denom even if somehow receiver has more than 1 gas denom of evm denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("12000000000100")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 12_000_000_000_100)),
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 5_999_999_999_990), sdk.NewInt64Coin(chaincfg.EvmDenom, 5_999_999_999_990),
sdk.NewInt64Coin("ua0gi", 1), sdk.NewInt64Coin(chaincfg.GasDenom, 1),
), ),
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 90), sdk.NewInt64Coin(chaincfg.EvmDenom, 90),
sdk.NewInt64Coin("ua0gi", 19), sdk.NewInt64Coin(chaincfg.GasDenom, 19),
), ),
false, false,
}, },
{ {
"swap 1 ua0gi for neuron if module account doesn't have enough neuron", "swap 1 gas denom for evm denom if module account doesn't have enough evm denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("99000000001000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 99_000_000_001_000)),
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 200), sdk.NewInt64Coin(chaincfg.EvmDenom, 200),
sdk.NewInt64Coin("ua0gi", 1), sdk.NewInt64Coin(chaincfg.GasDenom, 1),
), ),
sdk.NewCoins( sdk.NewCoins(
sdk.NewInt64Coin("neuron", 1200), sdk.NewInt64Coin(chaincfg.EvmDenom, 1200),
sdk.NewInt64Coin("ua0gi", 100), sdk.NewInt64Coin(chaincfg.GasDenom, 100),
), ),
false, false,
}, },
@ -231,8 +235,8 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() {
suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingAccBal) suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingAccBal)
suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, startingModuleCoins) suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, startingModuleCoins)
// fund our module with some ua0gi to account for converting extra neuron back to ua0gi // fund our module with some gas denom to account for converting extra evm denom back to gas denom
suite.FundModuleAccountWithZgChain(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10))) suite.FundModuleAccountWithZgChain(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10)))
err := suite.EvmBankKeeper.SendCoinsFromModuleToAccount(suite.Ctx, evmtypes.ModuleName, suite.Addrs[0], tt.sendCoins) err := suite.EvmBankKeeper.SendCoinsFromModuleToAccount(suite.Ctx, evmtypes.ModuleName, suite.Addrs[0], tt.sendCoins)
if tt.hasErr { if tt.hasErr {
@ -242,23 +246,24 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() {
suite.Require().NoError(err) suite.Require().NoError(err)
} }
// check ua0gi // check gas denom
a0giSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ua0gi") GasDenomSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.GasDenom)
suite.Require().Equal(tt.expAccBal.AmountOf("ua0gi").Int64(), a0giSender.Amount.Int64()) suite.Require().Equal(tt.expAccBal.AmountOf(chaincfg.GasDenom).Int64(), GasDenomSender.Amount.Int64())
// check neuron // check evm denom
actualNeuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) actualEvmDenom := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0])
suite.Require().Equal(tt.expAccBal.AmountOf("neuron").Int64(), actualNeuron.Int64()) suite.Require().Equal(tt.expAccBal.AmountOf(chaincfg.EvmDenom).Int64(), actualEvmDenom.Int64())
}) })
} }
} }
func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() { func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() {
startingAccCoins := sdk.NewCoins( startingAccCoins := sdk.NewCoins(
sdk.NewInt64Coin("neuron", 200), sdk.NewInt64Coin(chaincfg.EvmDenom, 200),
sdk.NewInt64Coin("ua0gi", 100), sdk.NewInt64Coin(chaincfg.GasDenom, 100),
) )
startingModuleCoins := sdk.NewCoins( startingModuleCoins := sdk.NewCoins(
sdk.NewInt64Coin("neuron", 100_000_000_000), sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_000),
) )
tests := []struct { tests := []struct {
name string name string
@ -268,36 +273,36 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() {
hasErr bool hasErr bool
}{ }{
{ {
"send more than 1 ua0gi", "send more than 1 gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("12000000000010")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 12_000_000_000_010)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 190), sdk.NewInt64Coin("ua0gi", 88)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 190), sdk.NewInt64Coin(chaincfg.GasDenom, 88)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100_000_000_010), sdk.NewInt64Coin("ua0gi", 12)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_010), sdk.NewInt64Coin(chaincfg.GasDenom, 12)),
false, false,
}, },
{ {
"send less than 1 ua0gi", "send less than 1 gas denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 122)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 122)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 78), sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 78), sdk.NewInt64Coin(chaincfg.GasDenom, 100)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100_000_000_122), sdk.NewInt64Coin("ua0gi", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_122), sdk.NewInt64Coin(chaincfg.GasDenom, 0)),
false, false,
}, },
{ {
"send an exact amount of ua0gi", "send an exact amount of gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("98000000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 98_000_000_000_000)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 200), sdk.NewInt64Coin("ua0gi", 2)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 200), sdk.NewInt64Coin(chaincfg.GasDenom, 2)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100_000_000_000), sdk.NewInt64Coin("ua0gi", 98)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_000), sdk.NewInt64Coin(chaincfg.GasDenom, 98)),
false, false,
}, },
{ {
"send no neuron", "send no evm denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 0)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 200), sdk.NewInt64Coin("ua0gi", 100)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 200), sdk.NewInt64Coin(chaincfg.GasDenom, 100)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100_000_000_000), sdk.NewInt64Coin("ua0gi", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_000), sdk.NewInt64Coin(chaincfg.GasDenom, 0)),
false, false,
}, },
{ {
"errors if sending other coins", "errors if sending other coins",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 500), sdk.NewInt64Coin("busd", 1000)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 500), sdk.NewInt64Coin("busd", 1000)),
sdk.Coins{}, sdk.Coins{},
sdk.Coins{}, sdk.Coins{},
true, true,
@ -305,39 +310,39 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() {
{ {
"errors if have dup coins", "errors if have dup coins",
sdk.Coins{ sdk.Coins{
sdk.NewInt64Coin("neuron", 12_000_000_000_000), sdk.NewInt64Coin(chaincfg.EvmDenom, 12_000_000_000_000),
sdk.NewInt64Coin("neuron", 2_000_000_000_000), sdk.NewInt64Coin(chaincfg.EvmDenom, 2_000_000_000_000),
}, },
sdk.Coins{}, sdk.Coins{},
sdk.Coins{}, sdk.Coins{},
true, true,
}, },
{ {
"errors if not enough total neuron to cover", "errors if not enough total evm denom to cover",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("100000000001000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_001_000)),
sdk.Coins{}, sdk.Coins{},
sdk.Coins{}, sdk.Coins{},
true, true,
}, },
{ {
"errors if not enough ua0gi to cover", "errors if not enough gas denom to cover",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("200000000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 200_000_000_000_000)),
sdk.Coins{}, sdk.Coins{},
sdk.Coins{}, sdk.Coins{},
true, true,
}, },
{ {
"converts 1 ua0gi to neuron if not enough neuron to cover", "converts 1 gas denom to evm denom if not enough evm denom to cover",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("99001000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 99_001_000_000_000)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 999_000_000_200), sdk.NewInt64Coin("ua0gi", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 999_000_000_200), sdk.NewInt64Coin(chaincfg.GasDenom, 0)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 101_000_000_000), sdk.NewInt64Coin("ua0gi", 99)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 101_000_000_000), sdk.NewInt64Coin(chaincfg.GasDenom, 99)),
false, false,
}, },
{ {
"converts receiver's neuron to ua0gi if there's enough neuron after the transfer", "converts receiver's evm denom to gas denom if there's enough evm denom after the transfer",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 5_900_000_000_200)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 5_900_000_000_200)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100_000_000_000), sdk.NewInt64Coin("ua0gi", 94)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_000_000_000), sdk.NewInt64Coin(chaincfg.GasDenom, 94)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 200), sdk.NewInt64Coin("ua0gi", 6)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 200), sdk.NewInt64Coin(chaincfg.GasDenom, 6)),
false, false,
}, },
} }
@ -357,66 +362,67 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() {
} }
// check sender balance // check sender balance
a0giSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ua0gi") GasDenomSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.GasDenom)
suite.Require().Equal(tt.expSenderCoins.AmountOf("ua0gi").Int64(), a0giSender.Amount.Int64()) suite.Require().Equal(tt.expSenderCoins.AmountOf(chaincfg.GasDenom).Int64(), GasDenomSender.Amount.Int64())
actualNeuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) actualEvmDenom := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0])
suite.Require().Equal(tt.expSenderCoins.AmountOf("neuron").Int64(), actualNeuron.Int64()) suite.Require().Equal(tt.expSenderCoins.AmountOf(chaincfg.EvmDenom).Int64(), actualEvmDenom.Int64())
// check module balance // check module balance
moduleAddr := suite.AccountKeeper.GetModuleAddress(evmtypes.ModuleName) moduleAddr := suite.AccountKeeper.GetModuleAddress(evmtypes.ModuleName)
a0giSender = suite.BankKeeper.GetBalance(suite.Ctx, moduleAddr, "ua0gi") GasDenomSender = suite.BankKeeper.GetBalance(suite.Ctx, moduleAddr, chaincfg.GasDenom)
suite.Require().Equal(tt.expModuleCoins.AmountOf("ua0gi").Int64(), a0giSender.Amount.Int64()) suite.Require().Equal(tt.expModuleCoins.AmountOf(chaincfg.GasDenom).Int64(), GasDenomSender.Amount.Int64())
actualNeuron = suite.Keeper.GetBalance(suite.Ctx, moduleAddr) actualEvmDenom = suite.Keeper.GetBalance(suite.Ctx, moduleAddr)
suite.Require().Equal(tt.expModuleCoins.AmountOf("neuron").Int64(), actualNeuron.Int64()) suite.Require().Equal(tt.expModuleCoins.AmountOf(chaincfg.EvmDenom).Int64(), actualEvmDenom.Int64())
}) })
} }
} }
func (suite *evmBankKeeperTestSuite) TestBurnCoins() { func (suite *evmBankKeeperTestSuite) TestBurnCoins() {
startingA0gi := sdkmath.NewInt(100) startingGasDenom := sdkmath.NewInt(100)
tests := []struct { tests := []struct {
name string name string
burnCoins sdk.Coins burnCoins sdk.Coins
expA0gi sdkmath.Int expGasDenom sdkmath.Int
expNeuron sdkmath.Int expEvmDenom sdkmath.Int
hasErr bool hasErr bool
neuronStart sdkmath.Int evmDenomStart sdkmath.Int
}{ }{
{ {
"burn more than 1 ua0gi", "burn more than 1 gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("12021000000002")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 12_021_000_000_002)),
sdkmath.NewInt(88), sdkmath.NewInt(88),
sdkmath.NewInt(100_000_000_000), sdkmath.NewInt(100_000_000_000),
false, false,
sdk.NewIntFromBigInt(makeBigIntByString("121000000002")), sdkmath.NewInt(121_000_000_002),
}, },
{ {
"burn less than 1 ua0gi", "burn less than 1 gas denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 122)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 122)),
sdkmath.NewInt(100), sdkmath.NewInt(100),
sdkmath.NewInt(878), sdkmath.NewInt(878),
false, false,
sdkmath.NewInt(1000), sdkmath.NewInt(1000),
}, },
{ {
"burn an exact amount of ua0gi", "burn an exact amount of gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("98000000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 98_000_000_000_000)),
sdkmath.NewInt(2), sdkmath.NewInt(2),
sdkmath.NewInt(10), sdkmath.NewInt(10),
false, false,
sdkmath.NewInt(10), sdkmath.NewInt(10),
}, },
{ {
"burn no neuron", "burn no evm denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 0)),
startingA0gi, startingGasDenom,
sdk.ZeroInt(), sdk.ZeroInt(),
false, false,
sdk.ZeroInt(), sdk.ZeroInt(),
}, },
{ {
"errors if burning other coins", "errors if burning other coins",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 500), sdk.NewInt64Coin("busd", 1000)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 500), sdk.NewInt64Coin("busd", 1000)),
startingA0gi, startingGasDenom,
sdkmath.NewInt(100), sdkmath.NewInt(100),
true, true,
sdkmath.NewInt(100), sdkmath.NewInt(100),
@ -424,41 +430,41 @@ func (suite *evmBankKeeperTestSuite) TestBurnCoins() {
{ {
"errors if have dup coins", "errors if have dup coins",
sdk.Coins{ sdk.Coins{
sdk.NewInt64Coin("neuron", 12_000_000_000_000), sdk.NewInt64Coin(chaincfg.EvmDenom, 12_000_000_000_000),
sdk.NewInt64Coin("neuron", 2_000_000_000_000), sdk.NewInt64Coin(chaincfg.EvmDenom, 2_000_000_000_000),
}, },
startingA0gi, startingGasDenom,
sdk.ZeroInt(), sdk.ZeroInt(),
true, true,
sdk.ZeroInt(), sdk.ZeroInt(),
}, },
{ {
"errors if burn amount is negative", "errors if burn amount is negative",
sdk.Coins{sdk.Coin{Denom: "neuron", Amount: sdkmath.NewInt(-100)}}, sdk.Coins{sdk.Coin{Denom: chaincfg.EvmDenom, Amount: sdkmath.NewInt(-100)}},
startingA0gi, startingGasDenom,
sdkmath.NewInt(50), sdkmath.NewInt(50),
true, true,
sdkmath.NewInt(50), sdkmath.NewInt(50),
}, },
{ {
"errors if not enough neuron to cover burn", "errors if not enough evm denom to cover burn",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("100999000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100_999_000_000_000)),
sdkmath.NewInt(0), sdkmath.NewInt(0),
sdkmath.NewInt(99_000_000_000), sdkmath.NewInt(99_000_000_000),
true, true,
sdkmath.NewInt(99_000_000_000), sdkmath.NewInt(99_000_000_000),
}, },
{ {
"errors if not enough ua0gi to cover burn", "errors if not enough gas denom to cover burn",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("200000000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 200_000_000_000_000)),
sdkmath.NewInt(100), sdkmath.NewInt(100),
sdk.ZeroInt(), sdk.ZeroInt(),
true, true,
sdk.ZeroInt(), sdk.ZeroInt(),
}, },
{ {
"converts 1 ua0gi to neuron if not enough neuron to cover", "converts 1 gas denom to evm denom if not enough evm denom to cover",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("12021000000002")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 12_021_000_000_002)),
sdkmath.NewInt(87), sdkmath.NewInt(87),
sdkmath.NewInt(980_000_000_000), sdkmath.NewInt(980_000_000_000),
false, false,
@ -470,8 +476,8 @@ func (suite *evmBankKeeperTestSuite) TestBurnCoins() {
suite.Run(tt.name, func() { suite.Run(tt.name, func() {
suite.SetupTest() suite.SetupTest()
startingCoins := sdk.NewCoins( startingCoins := sdk.NewCoins(
sdk.NewCoin("ua0gi", startingA0gi), sdk.NewCoin(chaincfg.GasDenom, startingGasDenom),
sdk.NewCoin("neuron", tt.neuronStart), sdk.NewCoin(chaincfg.EvmDenom, tt.evmDenomStart),
) )
suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, startingCoins) suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, startingCoins)
@ -483,52 +489,53 @@ func (suite *evmBankKeeperTestSuite) TestBurnCoins() {
suite.Require().NoError(err) suite.Require().NoError(err)
} }
// check ua0gi // check gas denom
a0giActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, "ua0gi") GasDenomActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, chaincfg.GasDenom)
suite.Require().Equal(tt.expA0gi, a0giActual.Amount) suite.Require().Equal(tt.expGasDenom, GasDenomActual.Amount)
// check neuron // check evm denom
neuronActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr) evmDenomActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr)
suite.Require().Equal(tt.expNeuron, neuronActual) suite.Require().Equal(tt.expEvmDenom, evmDenomActual)
}) })
} }
} }
func (suite *evmBankKeeperTestSuite) TestMintCoins() { func (suite *evmBankKeeperTestSuite) TestMintCoins() {
tests := []struct { tests := []struct {
name string name string
mintCoins sdk.Coins mintCoins sdk.Coins
ua0gi sdkmath.Int GasDenomCnt sdkmath.Int
neuron sdkmath.Int evmDenomCnt sdkmath.Int
hasErr bool hasErr bool
neuronStart sdkmath.Int evmDenomStart sdkmath.Int
}{ }{
{ {
"mint more than 1 ua0gi", "mint more than 1 gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("12021000000002")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 12_021_000_000_002)),
sdkmath.NewInt(12), sdkmath.NewInt(12),
sdkmath.NewInt(21_000_000_002), sdkmath.NewInt(21_000_000_002),
false, false,
sdk.ZeroInt(), sdk.ZeroInt(),
}, },
{ {
"mint less than 1 ua0gi", "mint less than 1 gas denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 901_000_000_001)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 901_000_000_001)),
sdk.ZeroInt(), sdk.ZeroInt(),
sdkmath.NewInt(901_000_000_001), sdkmath.NewInt(901_000_000_001),
false, false,
sdk.ZeroInt(), sdk.ZeroInt(),
}, },
{ {
"mint an exact amount of ua0gi", "mint an exact amount of gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("123000000000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 123_000_000_000_000_000)),
sdkmath.NewInt(123_000), sdkmath.NewInt(123_000),
sdk.ZeroInt(), sdk.ZeroInt(),
false, false,
sdk.ZeroInt(), sdk.ZeroInt(),
}, },
{ {
"mint no neuron", "mint no evm denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 0)),
sdk.ZeroInt(), sdk.ZeroInt(),
sdk.ZeroInt(), sdk.ZeroInt(),
false, false,
@ -536,7 +543,7 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() {
}, },
{ {
"errors if minting other coins", "errors if minting other coins",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 500), sdk.NewInt64Coin("busd", 1000)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 500), sdk.NewInt64Coin("busd", 1000)),
sdk.ZeroInt(), sdk.ZeroInt(),
sdkmath.NewInt(100), sdkmath.NewInt(100),
true, true,
@ -545,8 +552,8 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() {
{ {
"errors if have dup coins", "errors if have dup coins",
sdk.Coins{ sdk.Coins{
sdk.NewInt64Coin("neuron", 12_000_000_000_000), sdk.NewInt64Coin(chaincfg.EvmDenom, 12_000_000_000_000),
sdk.NewInt64Coin("neuron", 2_000_000_000_000), sdk.NewInt64Coin(chaincfg.EvmDenom, 2_000_000_000_000),
}, },
sdk.ZeroInt(), sdk.ZeroInt(),
sdk.ZeroInt(), sdk.ZeroInt(),
@ -555,35 +562,35 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() {
}, },
{ {
"errors if mint amount is negative", "errors if mint amount is negative",
sdk.Coins{sdk.Coin{Denom: "neuron", Amount: sdkmath.NewInt(-100)}}, sdk.Coins{sdk.Coin{Denom: chaincfg.EvmDenom, Amount: sdkmath.NewInt(-100)}},
sdk.ZeroInt(), sdk.ZeroInt(),
sdkmath.NewInt(50), sdkmath.NewInt(50),
true, true,
sdkmath.NewInt(50), sdkmath.NewInt(50),
}, },
{ {
"adds to existing neuron balance", "adds to existing evm denom balance",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("12021000000002")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 12_021_000_000_002)),
sdkmath.NewInt(12), sdkmath.NewInt(12),
sdkmath.NewInt(21_000_000_102), sdkmath.NewInt(21_000_000_102),
false, false,
sdkmath.NewInt(100), sdkmath.NewInt(100),
}, },
{ {
"convert neuron balance to ua0gi if it exceeds 1 ua0gi", "convert evm denom balance to gas denom if it exceeds 1 gas denom",
sdk.NewCoins(sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("10999000000000")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 10_999_000_000_000)),
sdkmath.NewInt(12), sdkmath.NewInt(12),
sdkmath.NewInt(1_200_000_001), sdkmath.NewInt(1_200_000_001),
false, false,
sdkmath.NewIntFromBigInt(makeBigIntByString("1002200000001")), sdkmath.NewInt(1_002_200_000_001),
}, },
} }
for _, tt := range tests { for _, tt := range tests {
suite.Run(tt.name, func() { suite.Run(tt.name, func() {
suite.SetupTest() suite.SetupTest()
suite.FundModuleAccountWithZgChain(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10))) suite.FundModuleAccountWithZgChain(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10)))
suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, sdk.NewCoins(sdk.NewCoin("neuron", tt.neuronStart))) suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(chaincfg.EvmDenom, tt.evmDenomStart)))
err := suite.EvmBankKeeper.MintCoins(suite.Ctx, evmtypes.ModuleName, tt.mintCoins) err := suite.EvmBankKeeper.MintCoins(suite.Ctx, evmtypes.ModuleName, tt.mintCoins)
if tt.hasErr { if tt.hasErr {
@ -593,13 +600,13 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() {
suite.Require().NoError(err) suite.Require().NoError(err)
} }
// check ua0gi // check gas denom
a0giActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, "ua0gi") GasDenomActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, chaincfg.GasDenom)
suite.Require().Equal(tt.ua0gi, a0giActual.Amount) suite.Require().Equal(tt.GasDenomCnt, GasDenomActual.Amount)
// check neuron // check evm denom
neuronActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr) evmDenomActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr)
suite.Require().Equal(tt.neuron, neuronActual) suite.Require().Equal(tt.evmDenomCnt, evmDenomActual)
}) })
} }
} }
@ -612,22 +619,22 @@ func (suite *evmBankKeeperTestSuite) TestValidateEvmCoins() {
}{ }{
{ {
"valid coins", "valid coins",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 500)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 500)),
false, false,
}, },
{ {
"dup coins", "dup coins",
sdk.Coins{sdk.NewInt64Coin("neuron", 500), sdk.NewInt64Coin("neuron", 500)}, sdk.Coins{sdk.NewInt64Coin(chaincfg.EvmDenom, 500), sdk.NewInt64Coin(chaincfg.EvmDenom, 500)},
true, true,
}, },
{ {
"not evm coins", "not evm coins",
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 500)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 500)),
true, true,
}, },
{ {
"negative coins", "negative coins",
sdk.Coins{sdk.Coin{Denom: "neuron", Amount: sdkmath.NewInt(-500)}}, sdk.Coins{sdk.Coin{Denom: chaincfg.EvmDenom, Amount: sdkmath.NewInt(-500)}},
true, true,
}, },
} }
@ -643,8 +650,8 @@ func (suite *evmBankKeeperTestSuite) TestValidateEvmCoins() {
} }
} }
func (suite *evmBankKeeperTestSuite) TestConvertOneA0giToNeuronIfNeeded() { func (suite *evmBankKeeperTestSuite) TestConvertOneGasDenomToEvmDenomIfNeeded() {
neuronNeeded := sdkmath.NewInt(200) evmDenomNeeded := sdkmath.NewInt(200)
tests := []struct { tests := []struct {
name string name string
startingCoins sdk.Coins startingCoins sdk.Coins
@ -652,21 +659,21 @@ func (suite *evmBankKeeperTestSuite) TestConvertOneA0giToNeuronIfNeeded() {
success bool success bool
}{ }{
{ {
"not enough ua0gi for conversion", "not enough gas denom for conversion",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100)),
false, false,
}, },
{ {
"converts 1 ua0gi to neuron", "converts 1 gas denom to evm denom",
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10), sdk.NewInt64Coin("neuron", 100)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10), sdk.NewInt64Coin(chaincfg.EvmDenom, 100)),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 9), sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("1000000000100")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 9), sdk.NewInt64Coin(chaincfg.EvmDenom, 1_000_000_000_100)),
true, true,
}, },
{ {
"conversion not needed", "conversion not needed",
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10), sdk.NewInt64Coin("neuron", 200)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10), sdk.NewInt64Coin(chaincfg.EvmDenom, 200)),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10), sdk.NewInt64Coin("neuron", 200)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10), sdk.NewInt64Coin(chaincfg.EvmDenom, 200)),
true, true,
}, },
} }
@ -675,11 +682,11 @@ func (suite *evmBankKeeperTestSuite) TestConvertOneA0giToNeuronIfNeeded() {
suite.SetupTest() suite.SetupTest()
suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingCoins) suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingCoins)
err := suite.EvmBankKeeper.ConvertOneUa0giToNeuronIfNeeded(suite.Ctx, suite.Addrs[0], neuronNeeded) err := suite.EvmBankKeeper.ConvertOneGasDenomToEvmDenomIfNeeded(suite.Ctx, suite.Addrs[0], evmDenomNeeded)
moduleZgChain := suite.BankKeeper.GetBalance(suite.Ctx, suite.AccountKeeper.GetModuleAddress(types.ModuleName), "ua0gi") moduleZgChain := suite.BankKeeper.GetBalance(suite.Ctx, suite.AccountKeeper.GetModuleAddress(types.ModuleName), chaincfg.GasDenom)
if tt.success { if tt.success {
suite.Require().NoError(err) suite.Require().NoError(err)
if tt.startingCoins.AmountOf("neuron").LT(neuronNeeded) { if tt.startingCoins.AmountOf(chaincfg.EvmDenom).LT(evmDenomNeeded) {
suite.Require().Equal(sdk.OneInt(), moduleZgChain.Amount) suite.Require().Equal(sdk.OneInt(), moduleZgChain.Amount)
} }
} else { } else {
@ -687,52 +694,54 @@ func (suite *evmBankKeeperTestSuite) TestConvertOneA0giToNeuronIfNeeded() {
suite.Require().Equal(sdk.ZeroInt(), moduleZgChain.Amount) suite.Require().Equal(sdk.ZeroInt(), moduleZgChain.Amount)
} }
neuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) evmDenomCnt := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0])
suite.Require().Equal(tt.expectedCoins.AmountOf("neuron"), neuron) suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.EvmDenom), evmDenomCnt)
ua0gi := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ua0gi") GasDenomCoin := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.GasDenom)
suite.Require().Equal(tt.expectedCoins.AmountOf("ua0gi"), ua0gi.Amount) suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.GasDenom), GasDenomCoin.Amount)
}) })
} }
} }
func (suite *evmBankKeeperTestSuite) TestConvertNeuronToA0gi() {
func (suite *evmBankKeeperTestSuite) TestConvertEvmDenomToGasDenom() {
tests := []struct { tests := []struct {
name string name string
startingCoins sdk.Coins startingCoins sdk.Coins
expectedCoins sdk.Coins expectedCoins sdk.Coins
}{ }{
{ {
"not enough ua0gi", "not enough gas denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 100), sdk.NewInt64Coin("ua0gi", 0)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 100), sdk.NewInt64Coin(chaincfg.GasDenom, 0)),
}, },
{ {
"converts neuron for 1 ua0gi", "converts evm denom for 1 gas denom",
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10), sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("1000000000003")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10), sdk.NewInt64Coin(chaincfg.EvmDenom, 1_000_000_000_003)),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 11), sdk.NewInt64Coin("neuron", 3)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 11), sdk.NewInt64Coin(chaincfg.EvmDenom, 3)),
}, },
{ {
"converts more than 1 ua0gi of neuron", "converts more than 1 gas denom of evm denom",
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10), sdk.NewCoin("neuron", sdk.NewIntFromBigInt(makeBigIntByString("8000000000123")))), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10), sdk.NewInt64Coin(chaincfg.EvmDenom, 8_000_000_000_123)),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 18), sdk.NewInt64Coin("neuron", 123)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 18), sdk.NewInt64Coin(chaincfg.EvmDenom, 123)),
}, },
} }
for _, tt := range tests { for _, tt := range tests {
suite.Run(tt.name, func() { suite.Run(tt.name, func() {
suite.SetupTest() suite.SetupTest()
err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 10))) err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 10)))
suite.Require().NoError(err) suite.Require().NoError(err)
suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingCoins) suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingCoins)
err = suite.EvmBankKeeper.ConvertNeuronToUa0gi(suite.Ctx, suite.Addrs[0]) err = suite.EvmBankKeeper.ConvertEvmDenomToGasDenom(suite.Ctx, suite.Addrs[0])
suite.Require().NoError(err) suite.Require().NoError(err)
neuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) evmDenomCnt := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0])
suite.Require().Equal(tt.expectedCoins.AmountOf("neuron"), neuron) suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.EvmDenom), evmDenomCnt)
ua0gi := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ua0gi") GasDenomCoin := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.GasDenom)
suite.Require().Equal(tt.expectedCoins.AmountOf("ua0gi"), ua0gi.Amount) suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.GasDenom), GasDenomCoin.Amount)
}) })
} }
} }
func (suite *evmBankKeeperTestSuite) TestSplitNeuronCoins() {
func (suite *evmBankKeeperTestSuite) TestSplitEvmDenomCoins() {
tests := []struct { tests := []struct {
name string name string
coins sdk.Coins coins sdk.Coins
@ -741,7 +750,7 @@ func (suite *evmBankKeeperTestSuite) TestSplitNeuronCoins() {
}{ }{
{ {
"invalid coins", "invalid coins",
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 500)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 500)),
nil, nil,
true, true,
}, },
@ -752,33 +761,33 @@ func (suite *evmBankKeeperTestSuite) TestSplitNeuronCoins() {
false, false,
}, },
{ {
"ua0gi & neuron coins", "gas denom & evm denom coins",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 8_000_000_000_123)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 8_000_000_000_123)),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 8), sdk.NewInt64Coin("neuron", 123)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 8), sdk.NewInt64Coin(chaincfg.EvmDenom, 123)),
false, false,
}, },
{ {
"only neuron", "only evm denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 10_123)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 10_123)),
sdk.NewCoins(sdk.NewInt64Coin("neuron", 10_123)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 10_123)),
false, false,
}, },
{ {
"only ua0gi", "only gas denom",
sdk.NewCoins(sdk.NewInt64Coin("neuron", 5_000_000_000_000)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.EvmDenom, 5_000_000_000_000)),
sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 5)), sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 5)),
false, false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
suite.Run(tt.name, func() { suite.Run(tt.name, func() {
ua0gi, neuron, err := keeper.SplitNeuronCoins(tt.coins) GasDenomCoin, evmDenomCnt, err := keeper.SplitEvmDenomCoins(tt.coins)
if tt.shouldErr { if tt.shouldErr {
suite.Require().Error(err) suite.Require().Error(err)
} else { } else {
suite.Require().NoError(err) suite.Require().NoError(err)
suite.Require().Equal(tt.expectedCoins.AmountOf("ua0gi"), ua0gi.Amount) suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.GasDenom), GasDenomCoin.Amount)
suite.Require().Equal(tt.expectedCoins.AmountOf("neuron"), neuron) suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.EvmDenom), evmDenomCnt)
} }
}) })
} }

View File

@ -6,6 +6,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/evmutil/types" "github.com/0glabs/0g-chain/x/evmutil/types"
) )
@ -50,7 +51,7 @@ func FullyBackedInvariant(bankK types.BankKeeper, k Keeper) sdk.Invariant {
}) })
bankAddr := authtypes.NewModuleAddress(types.ModuleName) bankAddr := authtypes.NewModuleAddress(types.ModuleName)
bankBalance := bankK.GetBalance(ctx, bankAddr, CosmosDenom).Amount.Mul(ConversionMultiplier) bankBalance := bankK.GetBalance(ctx, bankAddr, chaincfg.GasDenom).Amount.Mul(ConversionMultiplier)
broken = totalMinorBalances.GT(bankBalance) broken = totalMinorBalances.GT(bankBalance)

View File

@ -12,6 +12,7 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/evmutil/keeper" "github.com/0glabs/0g-chain/x/evmutil/keeper"
"github.com/0glabs/0g-chain/x/evmutil/testutil" "github.com/0glabs/0g-chain/x/evmutil/testutil"
"github.com/0glabs/0g-chain/x/evmutil/types" "github.com/0glabs/0g-chain/x/evmutil/types"
@ -49,7 +50,7 @@ func (suite *invariantTestSuite) SetupValidState() {
suite.FundModuleAccountWithZgChain( suite.FundModuleAccountWithZgChain(
types.ModuleName, types.ModuleName,
sdk.NewCoins( sdk.NewCoins(
sdk.NewCoin("ua0gi", sdkmath.NewInt(2)), // ( sum of all minor balances ) / conversion multiplier sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(2)), // ( sum of all minor balances ) / conversion multiplier
), ),
) )
@ -159,8 +160,8 @@ func (suite *invariantTestSuite) TestSmallBalances() {
// increase minor balance at least above conversion multiplier // increase minor balance at least above conversion multiplier
suite.Keeper.AddBalance(suite.Ctx, suite.Addrs[0], keeper.ConversionMultiplier) suite.Keeper.AddBalance(suite.Ctx, suite.Addrs[0], keeper.ConversionMultiplier)
// add same number of a0gi to avoid breaking other invariants // add same number of gas denom to avoid breaking other invariants
amt := sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 1)) amt := sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 1))
suite.Require().NoError( suite.Require().NoError(
suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, amt), suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, amt),
) )

View File

@ -115,7 +115,7 @@ func (k Keeper) SetAccount(ctx sdk.Context, account types.Account) error {
return nil return nil
} }
// GetBalance returns the total balance of neuron for a given account by address. // GetBalance returns the total balance of evm denom for a given account by address.
func (k Keeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdkmath.Int { func (k Keeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdkmath.Int {
account := k.GetAccount(ctx, addr) account := k.GetAccount(ctx, addr)
if account == nil { if account == nil {
@ -124,7 +124,7 @@ func (k Keeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdkmath.Int {
return account.Balance return account.Balance
} }
// SetBalance sets the total balance of neuron for a given account by address. // SetBalance sets the total balance of evm denom for a given account by address.
func (k Keeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, bal sdkmath.Int) error { func (k Keeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, bal sdkmath.Int) error {
account := k.GetAccount(ctx, addr) account := k.GetAccount(ctx, addr)
if account == nil { if account == nil {
@ -140,10 +140,10 @@ func (k Keeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, bal sdkmath.Int
return k.SetAccount(ctx, *account) return k.SetAccount(ctx, *account)
} }
// SendBalance transfers the neuron balance from sender addr to recipient addr. // SendBalance transfers the evm denom balance from sender addr to recipient addr.
func (k Keeper) SendBalance(ctx sdk.Context, senderAddr sdk.AccAddress, recipientAddr sdk.AccAddress, amt sdkmath.Int) error { func (k Keeper) SendBalance(ctx sdk.Context, senderAddr sdk.AccAddress, recipientAddr sdk.AccAddress, amt sdkmath.Int) error {
if amt.IsNegative() { if amt.IsNegative() {
return fmt.Errorf("cannot send a negative amount of neuron: %d", amt) return fmt.Errorf("cannot send a negative amount of evm denom: %d", amt)
} }
if amt.IsZero() { if amt.IsZero() {
@ -162,13 +162,13 @@ func (k Keeper) SendBalance(ctx sdk.Context, senderAddr sdk.AccAddress, recipien
return k.SetBalance(ctx, recipientAddr, receiverBal) return k.SetBalance(ctx, recipientAddr, receiverBal)
} }
// AddBalance increments the neuron balance of an address. // AddBalance increments the evm denom balance of an address.
func (k Keeper) AddBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdkmath.Int) error { func (k Keeper) AddBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdkmath.Int) error {
bal := k.GetBalance(ctx, addr) bal := k.GetBalance(ctx, addr)
return k.SetBalance(ctx, addr, amt.Add(bal)) return k.SetBalance(ctx, addr, amt.Add(bal))
} }
// RemoveBalance decrements the neuron balance of an address. // RemoveBalance decrements the evm denom balance of an address.
func (k Keeper) RemoveBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdkmath.Int) error { func (k Keeper) RemoveBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdkmath.Int) error {
if amt.IsNegative() { if amt.IsNegative() {
return fmt.Errorf("cannot remove a negative amount from balance: %d", amt) return fmt.Errorf("cannot remove a negative amount from balance: %d", amt)

View File

@ -37,6 +37,7 @@ import (
"github.com/tendermint/tendermint/version" "github.com/tendermint/tendermint/version"
"github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/evmutil/keeper" "github.com/0glabs/0g-chain/x/evmutil/keeper"
"github.com/0glabs/0g-chain/x/evmutil/types" "github.com/0glabs/0g-chain/x/evmutil/types"
) )
@ -81,14 +82,14 @@ func (suite *Suite) SetupTest() {
suite.Addrs = addrs suite.Addrs = addrs
evmGenesis := evmtypes.DefaultGenesisState() evmGenesis := evmtypes.DefaultGenesisState()
evmGenesis.Params.EvmDenom = keeper.EvmDenom evmGenesis.Params.EvmDenom = chaincfg.EvmDenom
feemarketGenesis := feemarkettypes.DefaultGenesisState() feemarketGenesis := feemarkettypes.DefaultGenesisState()
feemarketGenesis.Params.EnableHeight = 1 feemarketGenesis.Params.EnableHeight = 1
feemarketGenesis.Params.NoBaseFee = false feemarketGenesis.Params.NoBaseFee = false
cdc := suite.App.AppCodec() cdc := suite.App.AppCodec()
coins := sdk.NewCoins(sdk.NewInt64Coin("ua0gi", 1000_000_000_000)) coins := sdk.NewCoins(sdk.NewInt64Coin(chaincfg.GasDenom, 1000_000_000_000_000_000))
authGS := app.NewFundedGenStateWithSameCoins(cdc, coins, []sdk.AccAddress{ authGS := app.NewFundedGenStateWithSameCoins(cdc, coins, []sdk.AccAddress{
sdk.AccAddress(suite.Key1.PubKey().Address()), sdk.AccAddress(suite.Key1.PubKey().Address()),
sdk.AccAddress(suite.Key2.PubKey().Address()), sdk.AccAddress(suite.Key2.PubKey().Address()),
@ -185,28 +186,28 @@ func (suite *Suite) ModuleBalance(denom string) sdk.Int {
} }
func (suite *Suite) FundAccountWithZgChain(addr sdk.AccAddress, coins sdk.Coins) { func (suite *Suite) FundAccountWithZgChain(addr sdk.AccAddress, coins sdk.Coins) {
ua0gi := coins.AmountOf("ua0gi") GasDenomAmt := coins.AmountOf(chaincfg.GasDenom)
if ua0gi.IsPositive() { if GasDenomAmt.IsPositive() {
err := suite.App.FundAccount(suite.Ctx, addr, sdk.NewCoins(sdk.NewCoin("ua0gi", ua0gi))) err := suite.App.FundAccount(suite.Ctx, addr, sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, GasDenomAmt)))
suite.Require().NoError(err) suite.Require().NoError(err)
} }
neuron := coins.AmountOf("neuron") evmDenomAmt := coins.AmountOf(chaincfg.EvmDenom)
if neuron.IsPositive() { if evmDenomAmt.IsPositive() {
err := suite.Keeper.SetBalance(suite.Ctx, addr, neuron) err := suite.Keeper.SetBalance(suite.Ctx, addr, evmDenomAmt)
suite.Require().NoError(err) suite.Require().NoError(err)
} }
} }
func (suite *Suite) FundModuleAccountWithZgChain(moduleName string, coins sdk.Coins) { func (suite *Suite) FundModuleAccountWithZgChain(moduleName string, coins sdk.Coins) {
ua0gi := coins.AmountOf("ua0gi") GasDenomAmt := coins.AmountOf(chaincfg.GasDenom)
if ua0gi.IsPositive() { if GasDenomAmt.IsPositive() {
err := suite.App.FundModuleAccount(suite.Ctx, moduleName, sdk.NewCoins(sdk.NewCoin("ua0gi", ua0gi))) err := suite.App.FundModuleAccount(suite.Ctx, moduleName, sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, GasDenomAmt)))
suite.Require().NoError(err) suite.Require().NoError(err)
} }
neuron := coins.AmountOf("neuron") evmDenomAmt := coins.AmountOf(chaincfg.EvmDenom)
if neuron.IsPositive() { if evmDenomAmt.IsPositive() {
addr := suite.AccountKeeper.GetModuleAddress(moduleName) addr := suite.AccountKeeper.GetModuleAddress(moduleName)
err := suite.Keeper.SetBalance(suite.Ctx, addr, neuron) err := suite.Keeper.SetBalance(suite.Ctx, addr, evmDenomAmt)
suite.Require().NoError(err) suite.Require().NoError(err)
} }
} }
@ -217,7 +218,7 @@ func (suite *Suite) DeployERC20() types.InternalEVMAddress {
suite.App.FundModuleAccount( suite.App.FundModuleAccount(
suite.Ctx, suite.Ctx,
types.ModuleName, types.ModuleName,
sdk.NewCoins(sdk.NewCoin("ua0gi", sdkmath.NewInt(0))), sdk.NewCoins(sdk.NewCoin(chaincfg.GasDenom, sdkmath.NewInt(0))),
) )
contractAddr, err := suite.Keeper.DeployTestMintableERC20Contract(suite.Ctx, "USDC", "USDC", uint8(18)) contractAddr, err := suite.Keeper.DeployTestMintableERC20Contract(suite.Ctx, "USDC", "USDC", uint8(18))
@ -318,7 +319,7 @@ func (suite *Suite) SendTx(
// Mint the max gas to the FeeCollector to ensure balance in case of refund // Mint the max gas to the FeeCollector to ensure balance in case of refund
suite.MintFeeCollector(sdk.NewCoins( suite.MintFeeCollector(sdk.NewCoins(
sdk.NewCoin( sdk.NewCoin(
"ua0gi", chaincfg.GasDenom,
sdkmath.NewInt(baseFee.Int64()*int64(gasRes.Gas*2)), sdkmath.NewInt(baseFee.Int64()*int64(gasRes.Gas*2)),
))) )))

View File

@ -28,7 +28,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// allowed to be converted between ERC20 and sdk.Coin // allowed to be converted between ERC20 and sdk.Coin
type ConversionPair struct { type ConversionPair struct {
// ERC20 address of the token on the 0gChain EVM // ERC20 address of the token on the 0gChain EVM
ZgChainERC20Address HexBytes `protobuf:"bytes,1,opt,name=zgChain_erc20_address,json=zgChainErc20Address,proto3,casttype=HexBytes" json:"zgChain_erc20_address,omitempty"` ZgChainERC20Address HexBytes `protobuf:"bytes,1,opt,name=zgchain_erc20_address,json=zgchainErc20Address,proto3,casttype=HexBytes" json:"zgchain_erc20_address,omitempty"`
// Denom of the corresponding sdk.Coin // Denom of the corresponding sdk.Coin
Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"`
} }
@ -134,20 +134,20 @@ var fileDescriptor_6bad9d4ffa6874ec = []byte{
0x62, 0xd2, 0xd5, 0xa9, 0x08, 0x67, 0x2c, 0x92, 0x9e, 0x08, 0xed, 0x09, 0xf1, 0x22, 0x6d, 0x12, 0x62, 0xd2, 0xd5, 0xa9, 0x08, 0x67, 0x2c, 0x92, 0x9e, 0x08, 0xed, 0x09, 0xf1, 0x22, 0x6d, 0x12,
0x89, 0x58, 0xa0, 0xda, 0x92, 0x53, 0xad, 0x40, 0xb5, 0x02, 0x6d, 0xd4, 0xb9, 0xe0, 0x22, 0xdb, 0x89, 0x58, 0xa0, 0xda, 0x92, 0x53, 0xad, 0x40, 0xb5, 0x02, 0x6d, 0xd4, 0xb9, 0xe0, 0x22, 0xdb,
0xeb, 0xe9, 0x94, 0xa3, 0xed, 0x67, 0x00, 0x0f, 0xcc, 0x9d, 0xe4, 0x8e, 0x78, 0x11, 0x7a, 0x80, 0xeb, 0xe9, 0x94, 0xa3, 0xed, 0x67, 0x00, 0x0f, 0xcc, 0x9d, 0xe4, 0x8e, 0x78, 0x11, 0x7a, 0x80,
0x87, 0x4b, 0x6e, 0x8e, 0x89, 0x17, 0xda, 0x2c, 0xa2, 0x3d, 0xc3, 0x26, 0xae, 0x1b, 0x31, 0x29, 0x87, 0x4b, 0x4e, 0xc7, 0xc4, 0x0b, 0x6d, 0x16, 0xd1, 0x9e, 0x61, 0x13, 0xd7, 0x8d, 0x98, 0x94,
0x55, 0xd0, 0x02, 0x9d, 0xea, 0xe0, 0x34, 0x59, 0x37, 0x6b, 0xa3, 0x1c, 0x18, 0x5a, 0x66, 0xcf, 0x2a, 0x68, 0x81, 0x4e, 0x75, 0x70, 0x9a, 0xac, 0x9b, 0xb5, 0x11, 0x37, 0x53, 0x60, 0x68, 0x99,
0xe8, 0xe7, 0xeb, 0x9f, 0x75, 0xb3, 0x72, 0xc3, 0xe6, 0x83, 0x45, 0xcc, 0xa4, 0x55, 0x2b, 0x0c, 0x3d, 0xa3, 0x9f, 0xaf, 0x7f, 0xd6, 0xcd, 0xca, 0x0d, 0x9b, 0x0f, 0x16, 0x31, 0x93, 0x56, 0xad,
0xc3, 0x54, 0x50, 0x00, 0xa8, 0x0e, 0xff, 0xb9, 0x2c, 0x14, 0x81, 0xfa, 0xa7, 0x05, 0x3a, 0xff, 0x30, 0x0c, 0x53, 0x41, 0x01, 0xa0, 0x3a, 0xfc, 0xe7, 0xb2, 0x50, 0x04, 0xea, 0x9f, 0x16, 0xe8,
0xad, 0x3c, 0x5c, 0x95, 0x5e, 0xde, 0x9b, 0x4a, 0xfb, 0x15, 0xc0, 0xe3, 0xbe, 0xef, 0x8b, 0x27, 0xfc, 0xb7, 0xf2, 0x70, 0x55, 0x7a, 0x79, 0x6f, 0x2a, 0xed, 0x57, 0x00, 0x8f, 0xfb, 0xbe, 0x2f,
0xe6, 0x9a, 0x42, 0x06, 0x42, 0x9a, 0xa2, 0xd0, 0xdf, 0x8b, 0x47, 0x16, 0xa2, 0x13, 0x58, 0xa5, 0x9e, 0x98, 0x6b, 0x0a, 0x19, 0x08, 0x69, 0x8a, 0x42, 0x7f, 0x2f, 0x1e, 0x59, 0x88, 0x4e, 0x60,
0x59, 0x6f, 0xe7, 0x0a, 0x90, 0x29, 0xf6, 0xf2, 0xee, 0x3a, 0xad, 0x10, 0x82, 0xa5, 0x90, 0x04, 0x95, 0x66, 0xbd, 0x9d, 0x2b, 0x40, 0xa6, 0xd8, 0xcb, 0xbb, 0xeb, 0xb4, 0x42, 0x08, 0x96, 0x42,
0xac, 0xb0, 0x67, 0x33, 0x3a, 0x82, 0x65, 0xb9, 0x08, 0x1c, 0xe1, 0xab, 0x7f, 0xb3, 0xb6, 0x48, 0x12, 0xb0, 0xc2, 0x9e, 0xcd, 0xe8, 0x08, 0x96, 0xe5, 0x22, 0x70, 0x84, 0xaf, 0xfe, 0xcd, 0xda,
0xa8, 0x01, 0x2b, 0x2e, 0xa3, 0x5e, 0x40, 0x7c, 0xa9, 0x96, 0x5a, 0xa0, 0xb3, 0x6f, 0xed, 0x72, 0x22, 0xa1, 0x06, 0xac, 0xb8, 0x8c, 0x7a, 0x01, 0xf1, 0xa5, 0x5a, 0x6a, 0x81, 0xce, 0xbe, 0xb5,
0x7e, 0xa0, 0xc1, 0xed, 0xe6, 0x1b, 0x83, 0x8f, 0x04, 0x83, 0xcf, 0x04, 0x83, 0x55, 0x82, 0xc1, 0xcb, 0xf9, 0x81, 0x06, 0xb7, 0x9b, 0x6f, 0x0c, 0x3e, 0x12, 0x0c, 0x3e, 0x13, 0x0c, 0x56, 0x09,
0x26, 0xc1, 0xe0, 0x6d, 0x8b, 0x95, 0xd5, 0x16, 0x2b, 0x5f, 0x5b, 0xac, 0x8c, 0xce, 0xb9, 0x17, 0x06, 0x9b, 0x04, 0x83, 0xb7, 0x2d, 0x56, 0x56, 0x5b, 0xac, 0x7c, 0x6d, 0xb1, 0x32, 0x3a, 0xe7,
0x8f, 0xa7, 0x8e, 0x46, 0x45, 0xa0, 0x1b, 0xdc, 0x27, 0x8e, 0xd4, 0x0d, 0x7e, 0x41, 0xd3, 0x6b, 0x5e, 0x3c, 0x9e, 0x3a, 0x1a, 0x15, 0x81, 0x6e, 0x70, 0x9f, 0x38, 0x52, 0x37, 0xf8, 0x45, 0x76,
0xeb, 0xf3, 0xdd, 0x4f, 0xc5, 0x8b, 0x09, 0x93, 0x4e, 0x39, 0x7b, 0xed, 0xcb, 0xdf, 0x00, 0x00, 0x6d, 0x7d, 0xbe, 0xfb, 0xa9, 0x78, 0x31, 0x61, 0xd2, 0x29, 0x67, 0xaf, 0x7d, 0xf9, 0x1b, 0x00,
0x00, 0xff, 0xff, 0x25, 0x71, 0x3e, 0xe1, 0xc5, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfa, 0x07, 0x29, 0xab, 0xc5, 0x01, 0x00, 0x00,
} }
func (this *ConversionPair) VerboseEqual(that interface{}) error { func (this *ConversionPair) VerboseEqual(that interface{}) error {

View File

@ -3,6 +3,7 @@ package types_test
import ( import (
"testing" "testing"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/x/evmutil/testutil" "github.com/0glabs/0g-chain/x/evmutil/testutil"
"github.com/0glabs/0g-chain/x/evmutil/types" "github.com/0glabs/0g-chain/x/evmutil/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -142,7 +143,7 @@ func TestConversionPairs_Validate(t *testing.T) {
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"),
"a0gi", chaincfg.GasDenom,
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"),
@ -162,7 +163,7 @@ func TestConversionPairs_Validate(t *testing.T) {
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
"a0gi", chaincfg.GasDenom,
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"),
@ -183,16 +184,16 @@ func TestConversionPairs_Validate(t *testing.T) {
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"),
"a0gi", chaincfg.GasDenom,
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"),
"a0gi", chaincfg.GasDenom,
), ),
), ),
errArgs{ errArgs{
expectPass: false, expectPass: false,
contains: "found duplicate enabled conversion pair denom a0gi", contains: "found duplicate enabled conversion pair denom " + chaincfg.GasDenom,
}, },
}, },
{ {
@ -208,7 +209,7 @@ func TestConversionPairs_Validate(t *testing.T) {
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"),
"a0gi", chaincfg.GasDenom,
), ),
), ),
errArgs{ errArgs{
@ -240,12 +241,12 @@ func TestAllowedCosmosCoinERC20Token_Validate(t *testing.T) {
}{ }{
{ {
name: "valid token", name: "valid token",
token: types.NewAllowedCosmosCoinERC20Token("uatom", "0g-wrapped ATOM", "kATOM", 6), token: types.NewAllowedCosmosCoinERC20Token("uatom", "0gChain-wrapped ATOM", "kATOM", 6),
expErr: "", expErr: "",
}, },
{ {
name: "valid - highest allowed decimals", name: "valid - highest allowed decimals",
token: types.NewAllowedCosmosCoinERC20Token("uatom", "0g-wrapped ATOM", "kATOM", 255), token: types.NewAllowedCosmosCoinERC20Token("uatom", "0gChain-wrapped ATOM", "kATOM", 255),
expErr: "", expErr: "",
}, },
{ {
@ -280,7 +281,7 @@ func TestAllowedCosmosCoinERC20Token_Validate(t *testing.T) {
}, },
{ {
name: "invalid - decimals higher than uint8", name: "invalid - decimals higher than uint8",
token: types.NewAllowedCosmosCoinERC20Token("uatom", "0g-wrapped ATOM", "kATOM", 256), token: types.NewAllowedCosmosCoinERC20Token("uatom", "0gChain-wrapped ATOM", "kATOM", 256),
expErr: "decimals must be less than 256", expErr: "decimals must be less than 256",
}, },
} }

View File

@ -107,11 +107,11 @@ func (suite *ParamsTestSuite) TestParams_Validate() {
invalidConversionPairs := types.NewConversionPairs( invalidConversionPairs := types.NewConversionPairs(
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"),
"a0gi", chaincfg.GasDenom,
), ),
types.NewConversionPair( types.NewConversionPair(
testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"),
"a0gi", // duplicate denom! chaincfg.GasDenom, // duplicate denom!
), ),
) )
validAllowedCosmosDenoms := types.NewAllowedCosmosCoinERC20Tokens( validAllowedCosmosDenoms := types.NewAllowedCosmosCoinERC20Tokens(

View File

@ -139,7 +139,7 @@ type MsgConvertERC20ToCoin struct {
// 0gChain bech32 address that will receive the converted sdk.Coin. // 0gChain bech32 address that will receive the converted sdk.Coin.
Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"`
// EVM 0x hex address of the ERC20 contract. // EVM 0x hex address of the ERC20 contract.
ZgChainERC20Address string `protobuf:"bytes,3,opt,name=zgChain_erc20_address,json=zgChainErc20Address,proto3" json:"zgChain_erc20_address,omitempty"` ZgChainERC20Address string `protobuf:"bytes,3,opt,name=zgchain_erc20_address,json=zgchainErc20Address,proto3" json:"zgchain_erc20_address,omitempty"`
// ERC20 token amount to convert. // ERC20 token amount to convert.
Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"` Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"`
} }
@ -452,7 +452,7 @@ func init() {
func init() { proto.RegisterFile("zgc/evmutil/v1beta1/tx.proto", fileDescriptor_b60fa1a7a6ac0cc3) } func init() { proto.RegisterFile("zgc/evmutil/v1beta1/tx.proto", fileDescriptor_b60fa1a7a6ac0cc3) }
var fileDescriptor_b60fa1a7a6ac0cc3 = []byte{ var fileDescriptor_b60fa1a7a6ac0cc3 = []byte{
// 563 bytes of a gzipped FileDescriptorProto // 564 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x55, 0xc1, 0x6e, 0xd3, 0x30, 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x55, 0xc1, 0x6e, 0xd3, 0x30,
0x18, 0xae, 0xb7, 0x69, 0xa2, 0xe6, 0x96, 0x6e, 0xa2, 0x0b, 0x23, 0x9d, 0x8a, 0x06, 0xd3, 0xa4, 0x18, 0xae, 0xb7, 0x69, 0xa2, 0xe6, 0x96, 0x6e, 0xa2, 0x0b, 0x23, 0x9d, 0x8a, 0x06, 0xd3, 0xa4,
0x26, 0x69, 0x40, 0x08, 0x21, 0x2e, 0xb4, 0x1a, 0xd2, 0x04, 0xbb, 0x84, 0x9e, 0x76, 0xa9, 0x92, 0x26, 0x69, 0x40, 0x08, 0x21, 0x2e, 0xb4, 0x1a, 0xd2, 0x04, 0xbb, 0x84, 0x9e, 0x76, 0xa9, 0x92,
@ -471,24 +471,24 @@ var fileDescriptor_b60fa1a7a6ac0cc3 = []byte{
0x6c, 0xdd, 0xb5, 0xd6, 0x74, 0x99, 0x2d, 0xf2, 0x93, 0x9a, 0xd4, 0x23, 0x15, 0xb6, 0x04, 0x36, 0x6c, 0xdd, 0xb5, 0xd6, 0x74, 0x99, 0x2d, 0xf2, 0x93, 0x9a, 0xd4, 0x23, 0x15, 0xb6, 0x04, 0x36,
0x1b, 0xf0, 0x41, 0xa1, 0x3e, 0x1b, 0xf1, 0x21, 0xa3, 0x1c, 0x35, 0xbf, 0x2c, 0xe4, 0x1d, 0xc4, 0x1b, 0xf0, 0x41, 0xa1, 0x3e, 0x1b, 0xf1, 0x21, 0xa3, 0x1c, 0x35, 0xbf, 0x2c, 0xe4, 0x1d, 0xc4,
0xb1, 0x1e, 0x8b, 0x80, 0xca, 0xfa, 0x5f, 0x0e, 0xf2, 0x3a, 0x9f, 0x5e, 0xd5, 0x59, 0x62, 0xef, 0xb1, 0x1e, 0x8b, 0x80, 0xca, 0xfa, 0x5f, 0x0e, 0xf2, 0x3a, 0x9f, 0x5e, 0xd5, 0x59, 0x62, 0xef,
0xd2, 0xc1, 0x1b, 0xb8, 0x3a, 0xc1, 0xdd, 0x03, 0x87, 0xd0, 0x3e, 0x0a, 0x3c, 0xcb, 0xec, 0x3b, 0xd2, 0xc1, 0x1b, 0xb8, 0x3a, 0xc1, 0xde, 0x81, 0x43, 0x68, 0x1f, 0x05, 0x9e, 0x65, 0xf6, 0x9d,
0x09, 0x30, 0x36, 0x54, 0xed, 0xdc, 0x0b, 0xa7, 0x8d, 0xda, 0x7e, 0x02, 0x88, 0xa5, 0xc8, 0x3c, 0x04, 0x18, 0x1b, 0xaa, 0x76, 0xee, 0x85, 0xd3, 0x46, 0x6d, 0x1f, 0x77, 0x23, 0x40, 0x2c, 0x45,
0x76, 0x4d, 0xb2, 0x76, 0x22, 0x92, 0xdc, 0x54, 0x7a, 0x59, 0x39, 0x96, 0x62, 0xf6, 0xcb, 0xd3, 0xe6, 0xb1, 0x6b, 0x92, 0xb5, 0x13, 0x91, 0xe4, 0xa6, 0xd2, 0xcb, 0xca, 0xb1, 0x14, 0xb3, 0x5f,
0x69, 0xa3, 0xf2, 0x73, 0xda, 0x78, 0x84, 0x89, 0x38, 0x18, 0xb9, 0xba, 0xc7, 0x7c, 0x79, 0x87, 0x9e, 0x4e, 0x1b, 0x95, 0x9f, 0xd3, 0xc6, 0x23, 0x4c, 0xc4, 0xc1, 0xc8, 0xd5, 0x3d, 0xe6, 0xcb,
0xf2, 0xa7, 0xc5, 0x07, 0xef, 0x0d, 0xf1, 0x61, 0x88, 0xb8, 0xbe, 0x4b, 0xc5, 0xf9, 0x49, 0x0b, 0x3b, 0x94, 0x3f, 0x2d, 0x3e, 0x78, 0x6f, 0x88, 0x0f, 0x43, 0xc4, 0xf5, 0x5d, 0x2a, 0xce, 0x4f,
0x4a, 0xb9, 0xbb, 0x54, 0x14, 0x57, 0x2c, 0x57, 0x8f, 0xac, 0x62, 0x9f, 0x01, 0xbc, 0x9f, 0xaf, 0x5a, 0x50, 0xca, 0xdd, 0xa5, 0xa2, 0xb8, 0x62, 0xb9, 0x7a, 0x64, 0x15, 0xfb, 0x0c, 0xe0, 0xfd,
0x69, 0x94, 0x21, 0x7f, 0xf3, 0xe5, 0x75, 0xfb, 0xcf, 0xf7, 0xbb, 0x09, 0x1f, 0x96, 0x68, 0xc9, 0x7c, 0x4d, 0xa3, 0x0c, 0xf9, 0x9b, 0x2f, 0xaf, 0xdb, 0x7f, 0xbe, 0xdf, 0x4d, 0xf8, 0xb0, 0x44,
0x34, 0x1f, 0x83, 0x3f, 0xfb, 0x20, 0xc5, 0xbd, 0x0e, 0x98, 0x7f, 0x0b, 0xaa, 0x1f, 0xc3, 0xcd, 0x4b, 0xa6, 0xf9, 0x18, 0xfc, 0xd9, 0x07, 0x29, 0xee, 0x75, 0xc0, 0xfc, 0x5b, 0x50, 0xfd, 0x18,
0x52, 0x35, 0xa9, 0x6e, 0xeb, 0xd3, 0x12, 0x5c, 0xdc, 0xe3, 0x58, 0x11, 0x50, 0x29, 0x98, 0xb1, 0x6e, 0x96, 0xaa, 0x49, 0x75, 0x5b, 0x9f, 0x96, 0xe0, 0xe2, 0x1e, 0xc7, 0x8a, 0x80, 0x4a, 0xc1,
0x6d, 0xbd, 0x60, 0xc8, 0xf5, 0xc2, 0x7e, 0x57, 0xad, 0xeb, 0x63, 0xd3, 0xd3, 0x73, 0xa7, 0xe6, 0x8c, 0x6d, 0xeb, 0x05, 0x43, 0xae, 0x17, 0xf6, 0xbb, 0x6a, 0x5d, 0x1f, 0x9b, 0x9e, 0x9e, 0x3b,
0xe7, 0x62, 0xde, 0xa9, 0x39, 0xec, 0xdc, 0x53, 0x0b, 0xfa, 0x4b, 0xf9, 0x08, 0x60, 0xfd, 0x9f, 0x35, 0x3f, 0x17, 0xf3, 0x4e, 0xcd, 0x61, 0xe7, 0x9e, 0x5a, 0xd0, 0x5f, 0xca, 0x47, 0x00, 0xeb,
0xcd, 0x65, 0xce, 0xb5, 0x71, 0x85, 0xa1, 0x3e, 0xbf, 0x29, 0x23, 0x13, 0x72, 0x0c, 0xa0, 0x5a, 0xff, 0x6c, 0x2e, 0x73, 0xae, 0x8d, 0x2b, 0x0c, 0xf5, 0xf9, 0x4d, 0x19, 0x99, 0x90, 0x63, 0x00,
0xd2, 0x31, 0xd6, 0xb5, 0x13, 0x67, 0x1c, 0xf5, 0xc5, 0xcd, 0x39, 0xa9, 0x9c, 0xce, 0xdb, 0x8b, 0xd5, 0x92, 0x8e, 0xb1, 0xae, 0x9d, 0x38, 0xe3, 0xa8, 0x2f, 0x6e, 0xce, 0x49, 0xe5, 0x74, 0xde,
0x5f, 0x1a, 0xf8, 0x1e, 0x6a, 0xe0, 0x34, 0xd4, 0xc0, 0x59, 0xa8, 0x81, 0x8b, 0x50, 0x03, 0x5f, 0x5e, 0xfc, 0xd2, 0xc0, 0xf7, 0x50, 0x03, 0xa7, 0xa1, 0x06, 0xce, 0x42, 0x0d, 0x5c, 0x84, 0x1a,
0x67, 0x5a, 0xe5, 0x6c, 0xa6, 0x55, 0x7e, 0xcc, 0xb4, 0xca, 0xfe, 0x76, 0x6e, 0xf0, 0x4d, 0x7c, 0xf8, 0x3a, 0xd3, 0x2a, 0x67, 0x33, 0xad, 0xf2, 0x63, 0xa6, 0x55, 0xf6, 0xb7, 0x73, 0x83, 0x6f,
0xe8, 0xb8, 0xdc, 0x30, 0x71, 0xcb, 0x8b, 0x1e, 0x0e, 0xe3, 0x28, 0xfb, 0x54, 0xc4, 0x0f, 0x80, 0xe2, 0x43, 0xc7, 0xe5, 0x86, 0x89, 0x5b, 0xf1, 0xc3, 0x61, 0x1c, 0x65, 0x9f, 0x8a, 0xf8, 0x01,
0xbb, 0x1c, 0x3f, 0xe0, 0x4f, 0x7e, 0x07, 0x00, 0x00, 0xff, 0xff, 0x6e, 0x5d, 0x0b, 0x0a, 0x46, 0x70, 0x97, 0xe3, 0x07, 0xfc, 0xc9, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x2f, 0xc2, 0xb2, 0xda,
0x06, 0x00, 0x00, 0x46, 0x06, 0x00, 0x00,
} }
func (this *MsgConvertCoinToERC20) VerboseEqual(that interface{}) error { func (this *MsgConvertCoinToERC20) VerboseEqual(that interface{}) error {

View File

@ -1,53 +0,0 @@
package v0_15
import (
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// ModuleName The name that will be used throughout the module
ModuleName = "issuance"
)
// GenesisState is the state that must be provided at genesis for the issuance module
type GenesisState struct {
Params Params `json:"params" yaml:"params"`
Supplies AssetSupplies `json:"supplies" yaml:"supplies"`
}
// Params governance parameters for the issuance module
type Params struct {
Assets Assets `json:"assets" yaml:"assets"`
}
// Assets slice of Asset
type Assets []Asset
// Asset type for assets in the issuance module
type Asset struct {
Owner sdk.AccAddress `json:"owner" yaml:"owner"`
Denom string `json:"denom" yaml:"denom"`
BlockedAddresses []sdk.AccAddress `json:"blocked_addresses" yaml:"blocked_addresses"`
Paused bool `json:"paused" yaml:"paused"`
Blockable bool `json:"blockable" yaml:"blockable"`
RateLimit RateLimit `json:"rate_limit" yaml:"rate_limit"`
}
// RateLimit parameters for rate-limiting the supply of an issued asset
type RateLimit struct {
Active bool `json:"active" yaml:"active"`
Limit sdkmath.Int `json:"limit" yaml:"limit"`
TimePeriod time.Duration `json:"time_period" yaml:"time_period"`
}
// AssetSupplies is a slice of AssetSupply
type AssetSupplies []AssetSupply
// AssetSupply contains information about an asset's rate-limited supply (the total supply of the asset is tracked in the top-level supply module)
type AssetSupply struct {
CurrentSupply sdk.Coin `json:"current_supply" yaml:"current_supply"`
TimeElapsed time.Duration `json:"time_elapsed" yaml:"time_elapsed"`
}

View File

@ -1,48 +0,0 @@
package v0_16
import (
v015issuance "github.com/0glabs/0g-chain/x/issuance/legacy/v0_15"
v016issuance "github.com/0glabs/0g-chain/x/issuance/types"
)
func migrateParams(params v015issuance.Params) v016issuance.Params {
assets := make([]v016issuance.Asset, len(params.Assets))
for i, asset := range params.Assets {
blockedAddresses := make([]string, len(asset.BlockedAddresses))
for i, addr := range asset.BlockedAddresses {
blockedAddresses[i] = addr.String()
}
assets[i] = v016issuance.Asset{
Owner: asset.Owner.String(),
Denom: asset.Denom,
BlockedAddresses: blockedAddresses,
Paused: asset.Paused,
Blockable: asset.Blockable,
RateLimit: v016issuance.RateLimit{
Active: asset.RateLimit.Active,
Limit: asset.RateLimit.Limit,
TimePeriod: asset.RateLimit.TimePeriod,
},
}
}
return v016issuance.Params{Assets: assets}
}
func migrateSupplies(oldSupplies v015issuance.AssetSupplies) []v016issuance.AssetSupply {
supplies := make([]v016issuance.AssetSupply, len(oldSupplies))
for i, supply := range oldSupplies {
supplies[i] = v016issuance.AssetSupply{
CurrentSupply: supply.CurrentSupply,
TimeElapsed: supply.TimeElapsed,
}
}
return supplies
}
// Migrate converts v0.15 issuance state and returns it in v0.16 format
func Migrate(oldState v015issuance.GenesisState) *v016issuance.GenesisState {
return &v016issuance.GenesisState{
Params: migrateParams(oldState.Params),
Supplies: migrateSupplies(oldState.Supplies),
}
}

View File

@ -1,177 +0,0 @@
package v0_16
import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
app "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
v015issuance "github.com/0glabs/0g-chain/x/issuance/legacy/v0_15"
v016issuance "github.com/0glabs/0g-chain/x/issuance/types"
)
type migrateTestSuite struct {
suite.Suite
addresses []sdk.AccAddress
v15genstate v015issuance.GenesisState
cdc codec.Codec
legacyCdc *codec.LegacyAmino
}
func (s *migrateTestSuite) SetupTest() {
chaincfg.SetSDKConfig()
s.v15genstate = v015issuance.GenesisState{
Params: v015issuance.Params{},
Supplies: v015issuance.AssetSupplies{},
}
config := app.MakeEncodingConfig()
s.cdc = config.Marshaler
legacyCodec := codec.NewLegacyAmino()
s.legacyCdc = legacyCodec
_, accAddresses := app.GeneratePrivKeyAddressPairs(10)
s.addresses = accAddresses
}
func (s *migrateTestSuite) TestMigrate_JSON() {
// Migrate v15 issuance to v16
data := `{
"params": {
"assets": [
{
"blockable": true,
"blocked_addresses": null,
"denom": "hbtc",
"owner": "0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8",
"paused": false,
"rate_limit": {
"active": false,
"limit": "0",
"time_period": "0"
}
}
]
},
"supplies": [
{
"current_supply": { "denom": "ua0gi", "amount": "100" },
"time_elapsed": "3600000000000"
},
{
"current_supply": { "denom": "bnb", "amount": "300" },
"time_elapsed": "300000000000"
}
]
}`
err := s.legacyCdc.UnmarshalJSON([]byte(data), &s.v15genstate)
s.Require().NoError(err)
genstate := Migrate(s.v15genstate)
// Compare expect v16 issuance json with migrated json
expected := `{
"params": {
"assets": [
{
"blockable": true,
"blocked_addresses": [],
"denom": "hbtc",
"owner": "0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8",
"paused": false,
"rate_limit": {
"active": false,
"limit": "0",
"time_period": "0s"
}
}
]
},
"supplies": [
{
"current_supply": { "denom": "ua0gi", "amount": "100" },
"time_elapsed": "3600s"
},
{
"current_supply": { "denom": "bnb", "amount": "300" },
"time_elapsed": "300s"
}
]
}`
actual := s.cdc.MustMarshalJSON(genstate)
s.Require().NoError(err)
s.Require().JSONEq(expected, string(actual))
}
func (s *migrateTestSuite) TestMigrate_Params() {
s.v15genstate.Params = v015issuance.Params{
Assets: v015issuance.Assets{
{
Owner: s.addresses[0],
Denom: "ua0gi",
BlockedAddresses: s.addresses[1:2],
Paused: true,
Blockable: true,
RateLimit: v015issuance.RateLimit{
Active: true,
Limit: sdkmath.NewInt(10),
TimePeriod: 1 * time.Hour,
},
},
},
}
expectedParams := v016issuance.Params{
Assets: []v016issuance.Asset{
{
Owner: s.addresses[0].String(),
Denom: "ua0gi",
BlockedAddresses: []string{s.addresses[1].String()},
Paused: true,
Blockable: true,
RateLimit: v016issuance.RateLimit{
Active: true,
Limit: sdkmath.NewInt(10),
TimePeriod: 1 * time.Hour,
},
},
},
}
genState := Migrate(s.v15genstate)
s.Require().Equal(expectedParams, genState.Params)
}
func (s *migrateTestSuite) TestMigrate_Supplies() {
s.v15genstate.Supplies = v015issuance.AssetSupplies{
{
CurrentSupply: sdk.NewCoin("ua0gi", sdkmath.NewInt(100)),
TimeElapsed: time.Duration(1 * time.Hour),
},
{
CurrentSupply: sdk.NewCoin("bnb", sdkmath.NewInt(300)),
TimeElapsed: time.Duration(5 * time.Minute),
},
}
expected := []v016issuance.AssetSupply{
{
CurrentSupply: sdk.NewCoin("ua0gi", sdkmath.NewInt(100)),
TimeElapsed: time.Duration(1 * time.Hour),
},
{
CurrentSupply: sdk.NewCoin("bnb", sdkmath.NewInt(300)),
TimeElapsed: time.Duration(5 * time.Minute),
},
}
genState := Migrate(s.v15genstate)
s.Require().Equal(expected, genState.Supplies)
}
func TestIssuanceMigrateTestSuite(t *testing.T) {
suite.Run(t, new(migrateTestSuite))
}

View File

@ -1,46 +0,0 @@
package v0_15
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// ModuleName The name that will be used throughout the module
ModuleName = "pricefeed"
)
// GenesisState - pricefeed state that must be provided at genesis
type GenesisState struct {
Params Params `json:"params" yaml:"params"`
PostedPrices PostedPrices `json:"posted_prices" yaml:"posted_prices"`
}
// Params params for pricefeed. Can be altered via governance
type Params struct {
Markets Markets `json:"markets" yaml:"markets"` // Array containing the markets supported by the pricefeed
}
// Markets array type for oracle
type Markets []Market
// Market an asset in the pricefeed
type Market struct {
MarketID string `json:"market_id" yaml:"market_id"`
BaseAsset string `json:"base_asset" yaml:"base_asset"`
QuoteAsset string `json:"quote_asset" yaml:"quote_asset"`
Oracles []sdk.AccAddress `json:"oracles" yaml:"oracles"`
Active bool `json:"active" yaml:"active"`
}
// PostedPrices type for an array of PostedPrice
type PostedPrices []PostedPrice
// PostedPrice price for market posted by a specific oracle
type PostedPrice struct {
MarketID string `json:"market_id" yaml:"market_id"`
OracleAddress sdk.AccAddress `json:"oracle_address" yaml:"oracle_address"`
Price sdk.Dec `json:"price" yaml:"price"`
Expiry time.Time `json:"expiry" yaml:"expiry"`
}

View File

@ -1,134 +0,0 @@
package v0_16
import (
v015pricefeed "github.com/0glabs/0g-chain/x/pricefeed/legacy/v0_15"
v016pricefeed "github.com/0glabs/0g-chain/x/pricefeed/types"
"github.com/cosmos/cosmos-sdk/types"
)
var NewIBCMarkets = []v016pricefeed.Market{
{
MarketID: "atom:usd",
BaseAsset: "atom",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "atom:usd:30",
BaseAsset: "atom",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "akt:usd",
BaseAsset: "akt",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "akt:usd:30",
BaseAsset: "akt",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "luna:usd",
BaseAsset: "luna",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "luna:usd:30",
BaseAsset: "luna",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "osmo:usd",
BaseAsset: "osmo",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "osmo:usd:30",
BaseAsset: "osmo",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "ust:usd",
BaseAsset: "ust",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
{
MarketID: "ust:usd:30",
BaseAsset: "ust",
QuoteAsset: "usd",
Oracles: nil,
Active: true,
},
}
func migrateParams(params v015pricefeed.Params) v016pricefeed.Params {
markets := make(v016pricefeed.Markets, len(params.Markets))
for i, market := range params.Markets {
markets[i] = v016pricefeed.Market{
MarketID: market.MarketID,
BaseAsset: market.BaseAsset,
QuoteAsset: market.QuoteAsset,
Oracles: market.Oracles,
Active: market.Active,
}
}
markets = addIbcMarkets(markets)
return v016pricefeed.Params{Markets: markets}
}
func addIbcMarkets(markets v016pricefeed.Markets) v016pricefeed.Markets {
var oracles []types.AccAddress
if len(markets) > 0 {
oracles = markets[0].Oracles
}
for _, newMarket := range NewIBCMarkets {
// newMarket is a copy, should not affect other uses of NewIBCMarkets
newMarket.Oracles = oracles
markets = append(markets, newMarket)
}
return markets
}
func migratePostedPrices(oldPostedPrices v015pricefeed.PostedPrices) v016pricefeed.PostedPrices {
newPrices := make(v016pricefeed.PostedPrices, len(oldPostedPrices))
for i, price := range oldPostedPrices {
newPrices[i] = v016pricefeed.PostedPrice{
MarketID: price.MarketID,
OracleAddress: price.OracleAddress,
Price: price.Price,
Expiry: price.Expiry,
}
}
return newPrices
}
// Migrate converts v0.15 pricefeed state and returns it in v0.16 format
func Migrate(oldState v015pricefeed.GenesisState) *v016pricefeed.GenesisState {
return &v016pricefeed.GenesisState{
Params: migrateParams(oldState.Params),
PostedPrices: migratePostedPrices(oldState.PostedPrices),
}
}

View File

@ -1,353 +0,0 @@
package v0_16
import (
"testing"
"time"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
app "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
v015pricefeed "github.com/0glabs/0g-chain/x/pricefeed/legacy/v0_15"
v016pricefeed "github.com/0glabs/0g-chain/x/pricefeed/types"
)
type migrateTestSuite struct {
suite.Suite
addresses []sdk.AccAddress
v15genstate v015pricefeed.GenesisState
cdc codec.Codec
legacyCdc *codec.LegacyAmino
}
func (s *migrateTestSuite) SetupTest() {
chaincfg.SetSDKConfig()
s.v15genstate = v015pricefeed.GenesisState{
Params: v015pricefeed.Params{},
PostedPrices: v015pricefeed.PostedPrices{},
}
config := app.MakeEncodingConfig()
s.cdc = config.Marshaler
legacyCodec := codec.NewLegacyAmino()
s.legacyCdc = legacyCodec
_, accAddresses := app.GeneratePrivKeyAddressPairs(10)
s.addresses = accAddresses
}
func (s *migrateTestSuite) TestMigrate_JSON() {
// Migrate v15 pricefeed to v16
v15Params := `{
"params": {
"markets": [
{
"active": true,
"base_asset": "bnb",
"market_id": "bnb:usd",
"oracles": ["0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"],
"quote_asset": "usd"
},
{
"active": true,
"base_asset": "bnb",
"market_id": "bnb:usd:30",
"oracles": ["0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"],
"quote_asset": "usd"
}
]
},
"posted_prices": [
{
"expiry": "2022-07-20T00:00:00Z",
"market_id": "bnb:usd",
"oracle_address": "0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8",
"price": "215.962650000000001782"
},
{
"expiry": "2022-07-20T00:00:00Z",
"market_id": "bnb:usd:30",
"oracle_address": "0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8",
"price": "217.962650000000001782"
}
]
}`
expectedV16Params := `{
"params": {
"markets": [
{
"market_id": "bnb:usd",
"base_asset": "bnb",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "bnb:usd:30",
"base_asset": "bnb",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "atom:usd",
"base_asset": "atom",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "atom:usd:30",
"base_asset": "atom",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "akt:usd",
"base_asset": "akt",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "akt:usd:30",
"base_asset": "akt",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "luna:usd",
"base_asset": "luna",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "luna:usd:30",
"base_asset": "luna",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "osmo:usd",
"base_asset": "osmo",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "osmo:usd:30",
"base_asset": "osmo",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "ust:usd",
"base_asset": "ust",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
},
{
"market_id": "ust:usd:30",
"base_asset": "ust",
"quote_asset": "usd",
"oracles": [
"0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8"
],
"active": true
}
]
},
"posted_prices": [
{
"market_id": "bnb:usd",
"oracle_address": "0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8",
"price": "215.962650000000001782",
"expiry": "2022-07-20T00:00:00Z"
},
{
"market_id": "bnb:usd:30",
"oracle_address": "0g1ffv7nhd3z6sych2qpqkk03ec6hzkmufyhp5hf8",
"price": "217.962650000000001782",
"expiry": "2022-07-20T00:00:00Z"
}
]
}`
err := s.legacyCdc.UnmarshalJSON([]byte(v15Params), &s.v15genstate)
s.Require().NoError(err)
genstate := Migrate(s.v15genstate)
// v16 pricefeed json should be the same as v15 but with IBC markets added
actual := s.cdc.MustMarshalJSON(genstate)
s.Require().NoError(err)
s.Require().JSONEq(expectedV16Params, string(actual))
}
func (s *migrateTestSuite) TestMigrate_Params() {
s.v15genstate.Params = v015pricefeed.Params{
Markets: v015pricefeed.Markets{
{
MarketID: "market-1",
BaseAsset: "a0gi",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
},
}
expectedParams := v016pricefeed.Params{
Markets: v016pricefeed.Markets{
{
MarketID: "market-1",
BaseAsset: "a0gi",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "atom:usd",
BaseAsset: "atom",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "atom:usd:30",
BaseAsset: "atom",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "akt:usd",
BaseAsset: "akt",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "akt:usd:30",
BaseAsset: "akt",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "luna:usd",
BaseAsset: "luna",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "luna:usd:30",
BaseAsset: "luna",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "osmo:usd",
BaseAsset: "osmo",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "osmo:usd:30",
BaseAsset: "osmo",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "ust:usd",
BaseAsset: "ust",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
{
MarketID: "ust:usd:30",
BaseAsset: "ust",
QuoteAsset: "usd",
Oracles: s.addresses,
Active: true,
},
},
}
genState := Migrate(s.v15genstate)
s.Require().Equal(expectedParams, genState.Params)
}
func (s *migrateTestSuite) TestMigrate_PostedPrices() {
s.v15genstate.PostedPrices = v015pricefeed.PostedPrices{
{
MarketID: "market-1",
OracleAddress: s.addresses[0],
Price: sdk.MustNewDecFromStr("1.2"),
Expiry: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC),
},
{
MarketID: "market-2",
OracleAddress: s.addresses[1],
Price: sdk.MustNewDecFromStr("1.899"),
Expiry: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC),
},
}
expected := v016pricefeed.PostedPrices{
{
MarketID: "market-1",
OracleAddress: s.addresses[0],
Price: sdk.MustNewDecFromStr("1.2"),
Expiry: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC),
},
{
MarketID: "market-2",
OracleAddress: s.addresses[1],
Price: sdk.MustNewDecFromStr("1.899"),
Expiry: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC),
},
}
genState := Migrate(s.v15genstate)
s.Require().Equal(expected, genState.PostedPrices)
}
func TestPriceFeedMigrateTestSuite(t *testing.T) {
suite.Run(t, new(migrateTestSuite))
}

View File

@ -3,13 +3,14 @@ package types
import ( import (
"testing" "testing"
"github.com/0glabs/0g-chain/chaincfg"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func TestRawPriceKey_Iteration(t *testing.T) { func TestRawPriceKey_Iteration(t *testing.T) {
// An iterator key should only match price keys with the same market // An iterator key should only match price keys with the same market
iteratorKey := RawPriceIteratorKey("a0gi:usd") iteratorKey := RawPriceIteratorKey(chaincfg.GasDenom + ":usd")
addr := sdk.AccAddress("test addr") addr := sdk.AccAddress("test addr")
@ -20,12 +21,12 @@ func TestRawPriceKey_Iteration(t *testing.T) {
}{ }{
{ {
name: "equal marketID is included in iteration", name: "equal marketID is included in iteration",
priceKey: RawPriceKey("a0gi:usd", addr), priceKey: RawPriceKey(chaincfg.GasDenom+":usd", addr),
expectErr: false, expectErr: false,
}, },
{ {
name: "prefix overlapping marketID excluded from iteration", name: "prefix overlapping marketID excluded from iteration",
priceKey: RawPriceKey("a0gi:usd:30", addr), priceKey: RawPriceKey(chaincfg.GasDenom+":usd:30", addr),
expectErr: true, expectErr: true,
}, },
} }

Some files were not shown because too many files have changed in this diff Show More