Compare commits

...

80 Commits

Author SHA1 Message Date
0g-wh
e3b7446a05 add Upload Release Assets workflow (#49)
Some checks are pending
Continuous Integration (Commit) / lint (push) Waiting to run
* Create upload-release-assets.yml
2024-08-02 13:03:00 +08:00
Solovyov1796
d82675f503 update gitignore 2024-08-02 13:03:00 +08:00
Solovyov1796
8068bf7923 merge testnet script 2024-08-02 13:03:00 +08:00
0g-wh
907eea75ef add cosmovisor init script 2024-08-02 13:03:00 +08:00
Solovyov1796
0934f2346f use 0glabs' cometbft 2024-08-02 13:02:58 +08:00
0xsatoshi
540e1a1734 enable vesting msgs 2024-08-02 13:02:30 +08:00
0xsatoshi
08a50bcbd1 fix 2024-08-02 13:02:29 +08:00
0xsatoshi
2862336f03 fix 2024-08-02 13:02:09 +08:00
MiniFrenchBread
377fdd6778 refactor: epoch quorum storage 2024-08-02 13:01:48 +08:00
MiniFrenchBread
49307038eb feat: getQuorumRow 2024-08-02 13:01:48 +08:00
Solovyov1796
df10d41116 keep the EthSecp256k1 from cosmos for compatible 2024-08-02 13:01:48 +08:00
Solovyov1796
f0fbbb41cc recover "rename denoms" in 3 files 2024-08-02 13:01:48 +08:00
Solovyov1796
f373f2590d use chaincfg.MakeCoinForGasDenom 2024-08-02 13:01:47 +08:00
Solovyov1796
e7d5d98d59 custom inflation calculation function 2024-08-02 13:01:47 +08:00
MiniFrenchBread
e7f1517146 chore: remove tmp output 2024-08-02 13:01:25 +08:00
MiniFrenchBread
077df745e5 fix: decimals 2024-08-02 13:01:25 +08:00
MiniFrenchBread
5c71991b81 refactor: delegator 2024-08-02 13:01:25 +08:00
MiniFrenchBread
c575f8ba30 fix: localtestnet.sh 2024-08-02 13:01:25 +08:00
MiniFrenchBread
482057cf9f tidy 2024-08-02 13:01:25 +08:00
MiniFrenchBread
e3fcedd2b6 merge testnet/v0.1.x 2024-08-02 13:00:43 +08:00
Solovyov1796
f66c922327 remove the EthSecp256k1 from cosmos 2024-08-02 12:59:26 +08:00
Solovyov1796
849335487e rename denoms 2024-08-02 12:59:25 +08:00
Solovyov1796
19dd651fe8 fix unit test 2024-08-02 12:59:16 +08:00
Solovyov1796
43a6812a34 remove module's legacy code 2024-08-02 12:58:35 +08:00
Solovyov1796
fcb9042e74 recover go mod file 2024-08-02 12:58:27 +08:00
Solovyov1796
bac49bffbf remove das module 2024-08-02 12:57:53 +08:00
MiniFrenchBread
92fde64d1d feat: add get functions 2024-08-02 12:56:16 +08:00
MiniFrenchBread
4ef0aa0d44 fix: da signers begin block 2024-08-02 12:56:16 +08:00
MiniFrenchBread
cb81641f7d feat: max quorum num 2024-08-02 12:56:16 +08:00
MiniFrenchBread
a1f4ff7070 fix: quorum 2024-08-02 12:56:16 +08:00
MiniFrenchBread
c869eb01a5 feat: quorum 2024-08-02 12:56:16 +08:00
MiniFrenchBread
149fa8b50b fix: defaultGenesis 2024-08-02 12:56:16 +08:00
MiniFrenchBread
0751c15d9b feat: update dasigners proto api 2024-08-02 12:56:16 +08:00
MiniFrenchBread
7afeaf015d fix: dasigners module 2024-08-02 12:56:16 +08:00
MiniFrenchBread
eb61c996ad chore: dependency 2024-08-02 12:56:15 +08:00
MiniFrenchBread
613e2d459d feat: precompile 2024-08-02 12:51:20 +08:00
Solovyov1796
5a5341adb9 rename the app name showed in usage (#10) 2024-08-02 12:41:31 +08:00
Peter Zhang
fd66a420b7 update max validator count 2024-08-02 12:41:31 +08:00
Peter Zhang
b8b4a08235 update checkout branch 2024-08-02 12:41:31 +08:00
Solovyov1796
8ac0f3ec27 update init-genesis.sh for devnet and testnet 2024-08-02 12:41:31 +08:00
Solovyov1796
ff340b4717 fix unit test 2024-08-02 12:41:30 +08:00
Solovyov1796
a4486a680e recv both cosmos denom and evm denom from bank keeper 2024-08-02 12:41:14 +08:00
0xsatoshi
6609ea5293 fix 2024-08-02 12:41:14 +08:00
0xsatoshi
67b6975c72 fix 2024-08-02 12:41:13 +08:00
Solovyov1796
143dff2d9f update scripts 2024-08-02 12:40:56 +08:00
Solovyov1796
191bfd72c2 update env vars 2024-08-02 12:40:56 +08:00
Peter Zhang
bf9ab3fc7c modify deploy script 2024-08-02 12:40:56 +08:00
Solovyov1796
7b4b4e1a32 update 2024-08-02 12:40:56 +08:00
Solovyov1796
3d18f3164f fix unit test for x 2024-08-02 12:40:55 +08:00
Solovyov1796
764794f5c5 add scripts for devnet 2024-08-02 12:40:41 +08:00
Solovyov1796
3743e80727 fix panic 2024-08-02 12:40:41 +08:00
Solovyov1796
5e5e003123 merge script from branch v0.1.0 2024-08-02 12:40:41 +08:00
Solovyov1796
f6b7c1d56c fix test 2024-08-02 12:40:41 +08:00
Solovyov1796
e54c2f6fb8 add 0g code 2024-08-02 12:40:40 +08:00
Solovyov1796
b69e44123b rename kava 2024-08-02 12:39:55 +08:00
Solovyov1796
7f625389a7 add vrf 2024-08-02 12:36:23 +08:00
Solovyov1796
154b1af1c4 revise file structure in cmd 2024-08-02 12:35:00 +08:00
Solovyov1796
54425ab766 add chaincfg to save all configration of chain 2024-08-02 12:35:00 +08:00
Solovyov1796
de2559f6cc update build file 2024-08-02 12:35:00 +08:00
Solovyov1796
54feea3d12 revise proto files 2024-08-02 12:34:58 +08:00
Solovyov1796
b8c8971119 remove useless modules 2024-08-02 12:34:39 +08:00
Solovyov1796
4a55eb9259 rename go mod path 2024-08-02 12:22:00 +08:00
Peter Zhang
64bff1b331 add deploy scripts 2024-08-02 12:16:11 +08:00
Peter Zhang
36281975c8 add deploy scripts 2024-08-02 12:16:11 +08:00
drklee3
34625da5b4 Add v0.25.0 upgrade guide and staking rewards doc (#1769)
* Add upgrade guide and staking rewards doc

* Update date

* Update date for upgrade vs failure

* Use height 7637650 for upgrade

* Adjust bolding

* Use linux/amd64 in docs

* Upgrade height at 7637070
2024-08-02 12:16:11 +08:00
drklee3
a83a32d3d2 Add upgrade handler and upgrade e2e tests (#1739)
- Add upgrade handler for mainnet, testnet, and e2e test
- Set validator minimum commission to 5%
- Initialize `x/community` parameters
- Add `banktypes.MsgSend` authz grant for `x/kavadist` for gov proposals
- Set `x/gov` Quorum param to 20%
- Set `x/incentive` earn rewards param for bkava to 600K KAVA per year
2024-08-02 12:16:11 +08:00
Draco
614d4e40fe
Update cosmos-sdk to v0.47.7 (#1811)
* Update cometbft, cosmos, ethermint, and ibc-go

* Replace github.com/tendermint/tendermint by github.com/cometbft/cometbft

* Replace github.com/tendermint/tm-db by github.com/cometbft/cometbft-db

* Replace gogo/protobuf with cosmos/gogoproto & simapp replacement

* Replace cosmos-sdk/simapp/helpers with cosmos-sdk/testutil/sims

* Remove no longer used simulations

* Replace ibchost with ibcexported
See https://github.com/cosmos/ibc-go/blob/v7.2.2/docs/migrations/v6-to-v7.md#ibc-module-constants

* Add new consensus params keeper

* Add consensus keeper to blockers

* Fix keeper and module issues in app.go

* Add IsSendEnabledCoins and update SetParams interface changes

* Fix protobuf build for cosmos 47 (#1800)

* fix cp errors by using -f; fix lint by only linting our proto dir;
and use proofs.proto directly from ics23 for ibc-go v7

* run proto-all; commit updated third party deps and swagger changes

* regenerate proto files

* use correct gocosmos build plugin for buf

* re-gen all protobuf files to update paths for new gocosmos plugin

* update protoc and buf to latest versions

* fix staking keeper issues in app.go

* update tally handler for gov changes

* chain id fix and flag fixes

* update deps for cometbft 47.7 upgrade

* remove all module legacy queriers

* update stakingKeeper to pointer

* Replace ModuleCdc from govv1beta1 to govcodec

* remove simulations

* abci.LastCommitInfo → abci.CommitInfo

* Remove unused code in keys.go

* simapp.MakeTestEncodingConfig -> moduletestutil.MakeTestEncodingConfi

* Fix chain id issues in tests

* Fix remaining unit test issues

* Update changelog for upgrade

* Fix e2e tests using updated kvtool

* Update protonet to v47 compatible genesis

* Bump cometbft-db to v0.9.1-kava.1

* Update kvtool

* Remove extra changelog

* Fix merged rocksdb issues

* go mod cleanup

* Bump cometbft-db to v9 and go to 1.21

* Bump rocksdb version to v8.10.0

* Update kvtool to latest version

* Update gin to v1.9.0

* Use ibctm.ModuleName in app_test

* Fallback to genesis chain id instead of client toml

* Remove all simulations

* Fix cdp migrations issue with v47

* Update dependencies to correct tags

---------

Co-authored-by: Nick DeLuca <nickdeluca08@gmail.com>
2024-02-06 17:54:10 -05:00
Levi Schoen
7efee6d536
ensure pricefeed is updated every x/cdp begin blocker (#1819) 2024-02-02 16:16:35 -05:00
Levi Schoen
c59a491788
feat(x/cdp): update begin bloocker to run liquidations every X blocks based off params (#1818)
* (feat) update x/cdp to run every X blocks based off params (#1814)

* add new cdp module param to protonet genesis

* update cdp / cdp related tests for new module param

* update telemetry docs and setup for collecting against local node

* update kvool commit for new cdp param

(cherry picked from commit 4d62f47773)

* add tests for configurable x/cdp begin blocker interval param
add migration for default value of param

* make adjustments based off pr feedback

* fix proto back compat check
2024-02-02 13:21:11 -05:00
Nick DeLuca
2bccb6deaf
Revert "(feat) update x/cdp to run every X blocks based off params" (#1816) 2024-01-25 09:35:56 -07:00
Levi Schoen
7b5de0a12a
add github action for manually triggering protonet cd (#1815) 2024-01-24 18:12:34 -05:00
Levi Schoen
4d62f47773
(feat) update x/cdp to run every X blocks based off params (#1814)
* add new cdp module param to protonet genesis

* update cdp / cdp related tests for new module param

* update telemetry docs and setup for collecting against local node

* update kvool commit for new cdp param
2024-01-24 17:10:07 -05:00
drklee3
3767030005
feat(cli): Add rocksdb compact command (#1804)
* Add rocksdb compact command

* Increase compaction log output to 1 min

* Use GetClient/ServerContextFromCmd

* Update cmd info

* Add doc to logColumnFamilyMetadata

* Update RocksDBCmd docs

* Add changelog entry

* Load latest options from rocksdb

* Allow application.db to be compacted

* Rename more store -> db

* Ensure compaction stats output does not run when db is closed

* Add flag for custom stat output interval, return error
2024-01-19 10:17:13 -08:00
Robert Pirtle
58621577ae
feat(cli): add shard CLI command (#1785)
* stub out shard CLI command

* prune blocks before and after desired range

* update rollback to use patched cometbft

* temp override for local patched versions

* handle pruning cometbft & block store state

* include docs & support -1 for "latest"

* update changelog

* add --only-app-state flag to match cosmos-sdk prune cmd

* give -1 magic number a name & reuse home from ctx

* refactor to only open state.db & blockstore.db once

* write rollback progress to one line

* prevent attempting rollback of future blocks

* make shard inclusive of endblock

* use tagged cosmo-sdk & cometbft versions
2024-01-05 11:25:53 -08:00
Evgeniy Scherbina
f00727fe85
Add release/v0.25.x branch to backporting flow (#1799) 2023-12-21 15:23:59 -05:00
Evgeniy Scherbina
b170f3bdd5
Update ethermint (#1798) 2023-12-21 15:23:44 -05:00
Levi Schoen
1aa1348944 add docs and docker config for local and remote app telemetry collection and display 2023-12-14 09:56:44 -08:00
Draco
ffd306ef52
Kava gRPC Client (#1784)
* add grpc client

* add e2e tests for grpc client

* add grpc client readme

* doc update

* fix more doc issues

* remove util namespace & move grpc client to chain

* rename GrpcClient to Grpc

* add 3rd party query clients

* fix invalid url in readme

* update e2e tests to use grpc client (#1787)
2023-12-13 12:17:37 -05:00
Robert Pirtle
c63fab1317
release: update docs & changelog for v0.25.0 (#1794) 2023-12-07 10:21:02 -08:00
Levi Schoen
f70349ab02 update ethermint with patches for traceTx/traceBlock 2023-12-06 11:19:14 -08:00
1325 changed files with 38403 additions and 188706 deletions

10
.github/mergify.yml vendored
View File

@ -25,6 +25,7 @@ pull_request_rules:
- release/v0.21.x - release/v0.21.x
- release/v0.23.x - release/v0.23.x
- release/v0.24.x - release/v0.24.x
- release/v0.25.x
- name: Backport patches to the release/v0.17.x branch - name: Backport patches to the release/v0.17.x branch
conditions: conditions:
@ -79,3 +80,12 @@ pull_request_rules:
backport: backport:
branches: branches:
- release/v0.24.x - release/v0.24.x
- name: Backport patches to the release/v0.25.x branch
conditions:
- base=master
- label=A:backport/v0.25.x
actions:
backport:
branches:
- release/v0.25.x

View File

@ -80,7 +80,7 @@ printf "original evm util module params\n %s" , "$originalEvmUtilParams"
# change the params of the chain like a god - make it so 🖖🏽 # change the params of the chain like a god - make it so 🖖🏽
# make sure to update god committee member permissions for the module # make sure to update god committee member permissions for the module
# and params being updated (see below for example) # and params being updated (see below for example)
# https://github.com/Kava-Labs/kava/pull/1556/files#diff-0bd6043650c708661f37bbe6fa5b29b52149e0ec0069103c3954168fc9f12612R900-R903 # https://github.com/0glabs/0g-chain/pull/1556/files#diff-0bd6043650c708661f37bbe6fa5b29b52149e0ec0069103c3954168fc9f12612R900-R903
kava tx committee submit-proposal 1 "$proposalFileName" --gas 2000000 --gas-prices 0.01ukava --from god -y kava tx committee submit-proposal 1 "$proposalFileName" --gas 2000000 --gas-prices 0.01ukava --from god -y
# fetch current module params # fetch current module params

View File

@ -155,7 +155,7 @@ printf "original evm util module params\n %s" , "$originalEvmUtilParams"
# change the params of the chain like a god - make it so 🖖🏽 # change the params of the chain like a god - make it so 🖖🏽
# make sure to update god committee member permissions for the module # make sure to update god committee member permissions for the module
# and params being updated (see below for example) # and params being updated (see below for example)
# https://github.com/Kava-Labs/kava/pull/1556/files#diff-0bd6043650c708661f37bbe6fa5b29b52149e0ec0069103c3954168fc9f12612R900-R903 # https://github.com/0glabs/0g-chain/pull/1556/files#diff-0bd6043650c708661f37bbe6fa5b29b52149e0ec0069103c3954168fc9f12612R900-R903
# committee 1 is the stability committee. on internal testnet, this has only one member. # committee 1 is the stability committee. on internal testnet, this has only one member.
kava tx committee submit-proposal 1 "$proposalFileName" --gas 2000000 --gas-prices 0.01ukava --from god -y kava tx committee submit-proposal 1 "$proposalFileName" --gas 2000000 --gas-prices 0.01ukava --from god -y

View File

@ -147,7 +147,7 @@ printf "original evm util module params\n %s" , "$originalEvmUtilParams"
# change the params of the chain like a god - make it so 🖖🏽 # change the params of the chain like a god - make it so 🖖🏽
# make sure to update god committee member permissions for the module # make sure to update god committee member permissions for the module
# and params being updated (see below for example) # and params being updated (see below for example)
# https://github.com/Kava-Labs/kava/pull/1556/files#diff-0bd6043650c708661f37bbe6fa5b29b52149e0ec0069103c3954168fc9f12612R900-R903 # https://github.com/0glabs/0g-chain/pull/1556/files#diff-0bd6043650c708661f37bbe6fa5b29b52149e0ec0069103c3954168fc9f12612R900-R903
kava tx committee submit-proposal 1 "$proposalFileName" --gas 2000000 --gas-prices 0.01ukava --from god -y kava tx committee submit-proposal 1 "$proposalFileName" --gas 2000000 --gas-prices 0.01ukava --from god -y
# vote on the proposal. this assumes no other committee proposal has ever been submitted (id=1) # vote on the proposal. this assumes no other committee proposal has ever been submitted (id=1)

View File

@ -0,0 +1,56 @@
name: Manual Deployment (Protonet)
# allow to be triggered manually
on: workflow_dispatch
jobs:
# in order:
# enter standby (prevents autoscaling group from killing node during deploy)
# stop kava
# take ebs + zfs snapshots
# download updated binary and genesis
# reset application database state (only done on internal testnet)
reset-chain-to-zero-state:
# only start cd pipeline if last ci run was successful
if: ${{ github.event.workflow_run.conclusion == 'success' }}
uses: ./.github/workflows/cd-reset-internal-testnet.yml
with:
aws-region: us-east-1
chain-id: proto_2221-17000
ssm-document-name: kava-testnet-internal-node-update
playbook-name: reset-protonet-playbook.yml
playbook-infrastructure-branch: master
secrets: inherit
# start kava with new binary and genesis state on api, peer and seed nodes, place nodes in service once they start and are synched to live
start-chain-api:
uses: ./.github/workflows/cd-start-chain.yml
with:
aws-region: us-east-1
chain-id: proto_2221-17000
ssm-document-name: kava-testnet-internal-node-update
playbook-name: start-chain-api-playbook.yml
playbook-infrastructure-branch: master
secrets: inherit
needs: [reset-chain-to-zero-state]
# setup test and development accounts and balances, deploy contracts by calling the chain's api
seed-chain-state:
uses: ./.github/workflows/cd-seed-chain.yml
with:
chain-api-url: https://rpc.app.protonet.us-east.production.kava.io:443
chain-id: proto_2221-17000
seed-script-filename: seed-protonet.sh
erc20-deployer-network-name: protonet
genesis_validator_addresses: "kavavaloper14w4avgdvqrlpww6l5dhgj4egfn6ln7gmtp7r2m"
kava_version_filepath: ./ci/env/kava-protonet/KAVA.VERSION
secrets: inherit
needs: [start-chain-api]
post-pipeline-metrics:
uses: ./.github/workflows/metric-pipeline.yml
if: always() # always run so we metric failures and successes
with:
aws-region: us-east-1
metric-name: kava.deploys.testnet.proto
namespace: Kava/ContinuousDeployment
secrets: inherit
needs: [seed-chain-state]

View File

@ -29,7 +29,7 @@ jobs:
- name: build rocksdb dependency - name: build rocksdb dependency
run: bash ${GITHUB_WORKSPACE}/.github/scripts/install-rocksdb.sh run: bash ${GITHUB_WORKSPACE}/.github/scripts/install-rocksdb.sh
env: env:
ROCKSDB_VERSION: v8.1.1 ROCKSDB_VERSION: v8.10.0
- name: Build and upload release artifacts - name: Build and upload release artifacts
run: bash ${GITHUB_WORKSPACE}/.github/scripts/publish-internal-release-artifacts.sh run: bash ${GITHUB_WORKSPACE}/.github/scripts/publish-internal-release-artifacts.sh
env: env:

View File

@ -1,7 +1,7 @@
name: Continuous Integration (Rocksdb Build) name: Continuous Integration (Rocksdb Build)
env: env:
ROCKSDB_VERSION: v8.1.1 ROCKSDB_VERSION: v8.10.0
on: on:
workflow_call: workflow_call:

View File

@ -0,0 +1,25 @@
name: Upload Release Assets
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.20'
- name: Build
run: make build
- name: Rename file
run: mv ./out/linux/0gchaind ./out/linux/0gchaind-linux-${{ github.ref_name }}
- name: Upload Release Asset
uses: softprops/action-gh-release@v2
with:
files: ./out/linux/0gchaind-linux-${{ github.ref_name }}
env:
GITHUB_TOKEN: ${{ secrets.ZG_UPLOAD_ASSET }}

5
.gitignore vendored
View File

@ -41,3 +41,8 @@ build/linux
# Go workspace files # Go workspace files
go.work go.work
go.work.sum go.work.sum
.build/0gchaind
.build/da
# runtime
run

View File

@ -38,16 +38,25 @@ Ref: https://keepachangelog.com/en/1.0.0/
### Features ### Features
- (cli) [#1785] Add `shard` CLI command to support creating partitions of data for standalone nodes
- (cdp) [#1818] Add module param and logic for running x/cdp begin blocker every `n` blocks
- (cli) [#1804] Add `rocksdb compact` command for manual DB compaction of state or blockstore.
- (cosmos-sdk) [#1811] Upgrades app to cosmos-sdk v0.47.7
## [v0.25.0]
### Features
- (community) [#1704] Add module params - (community) [#1704] Add module params
- (community) [#1706] Add disable inflation upgrade - (community) [#1706] Add disable inflation upgrade
- (community) [#1745] Enable params update via governance with `MsgUpdateParams` - (community) [#1745] Enable params update via governance with `MsgUpdateParams`
- (client) [#1784] Add Kava gRPC client
### Bug Fixes ### Bug Fixes
- (ethermint) [#1788] Fixes issue where tracing a transaction could show it's status as successful when isolated in simulation even if the tx when executed on the chain failed due to an error such as exhausting the block gas meter
- (evmutil) [#1655] Initialize x/evmutil module account in InitGenesis - (evmutil) [#1655] Initialize x/evmutil module account in InitGenesis
- (deps) [#1770] Bump ledger-cosmos-go to v0.13.1 to resolve signing error with
cosmos ledger app 2.34.12 cosmos ledger app 2.34.12
- (rockdb) [#1776] Fix resolution of rocksdb database path
## State Machine Breaking ## State Machine Breaking
@ -59,9 +68,19 @@ Ref: https://keepachangelog.com/en/1.0.0/
- (community) [#1755] Keep funds in `x/community` in `CommunityPoolLendWithdrawProposal` handler - (community) [#1755] Keep funds in `x/community` in `CommunityPoolLendWithdrawProposal` handler
- (staking) [#1761] Set validator minimum commission to 5% for all validators under 5% - (staking) [#1761] Set validator minimum commission to 5% for all validators under 5%
## [v0.24.1](https://github.com/Kava-Labs/kava/releases/tag/v0.24.1) ## [v0.24.3]
### Bug Fixes
- (deps) [#1770] Bump ledger-cosmos-go to v0.13.1 to resolve signing error with
- (rocksdb) [#1767] Fix resolution of rocksdb database path introduced in v0.24.2
**Note**: There was a bug released as v0.24.2. The tag has been removed and the commit should not be used.
## [v0.24.1]
### Features ### Features
- (metrics) [#1668] Adds non-state breaking x/metrics module for custom telemetry. - (metrics) [#1668] Adds non-state breaking x/metrics module for custom telemetry.
- (metrics) [#1669] Add performance timing metrics to all Begin/EndBlockers - (metrics) [#1669] Add performance timing metrics to all Begin/EndBlockers
- (community) [#1751] Add `AnnualizedRewards` query endpoint - (community) [#1751] Add `AnnualizedRewards` query endpoint
@ -305,7 +324,10 @@ the [changelog](https://github.com/cosmos/cosmos-sdk/blob/v0.38.4/CHANGELOG.md).
- [#257](https://github.com/Kava-Labs/kava/pulls/257) Include scripts to run - [#257](https://github.com/Kava-Labs/kava/pulls/257) Include scripts to run
large-scale simulations remotely using aws-batch large-scale simulations remotely using aws-batch
[#1776]: https://github.com/Kava-Labs/kava/pull/1776 [#1811]: https://github.com/Kava-Labs/kava/pull/1811
[#1804]: https://github.com/Kava-Labs/kava/pull/1804
[#1785]: https://github.com/Kava-Labs/kava/pull/1785
[#1784]: https://github.com/Kava-Labs/kava/pull/1784
[#1770]: https://github.com/Kava-Labs/kava/pull/1770 [#1770]: https://github.com/Kava-Labs/kava/pull/1770
[#1755]: https://github.com/Kava-Labs/kava/pull/1755 [#1755]: https://github.com/Kava-Labs/kava/pull/1755
[#1761]: https://github.com/Kava-Labs/kava/pull/1761 [#1761]: https://github.com/Kava-Labs/kava/pull/1761
@ -359,10 +381,12 @@ the [changelog](https://github.com/cosmos/cosmos-sdk/blob/v0.38.4/CHANGELOG.md).
[#750]: https://github.com/Kava-Labs/kava/pull/750 [#750]: https://github.com/Kava-Labs/kava/pull/750
[#751]: https://github.com/Kava-Labs/kava/pull/751 [#751]: https://github.com/Kava-Labs/kava/pull/751
[#780]: https://github.com/Kava-Labs/kava/pull/780 [#780]: https://github.com/Kava-Labs/kava/pull/780
[unreleased]: https://github.com/Kava-Labs/kava/compare/v0.24.0...HEAD [unreleased]: https://github.com/Kava-Labs/kava/compare/v0.25.0...HEAD
[v0.25.0]: https://github.com/Kava-Labs/kava/compare/v0.25.0...v0.24.3
[v0.24.3]: https://github.com/Kava-Labs/kava/compare/v0.24.3...v0.24.1
[v0.24.1]: https://github.com/Kava-Labs/kava/compare/v0.24.1...v0.24.0
[v0.24.0]: https://github.com/Kava-Labs/kava/compare/v0.24.0...v0.23.2 [v0.24.0]: https://github.com/Kava-Labs/kava/compare/v0.24.0...v0.23.2
[v0.23.2]: https://github.com/Kava-Labs/kava/compare/v0.23.1...v0.23.2 [v0.23.2]: https://github.com/Kava-Labs/kava/compare/v0.23.1...v0.23.2
[v0.23.1]: https://github.com/Kava-Labs/kava/compare/v0.23.0...v0.23.1
[v0.23.0]: https://github.com/Kava-Labs/kava/compare/v0.21.1...v0.23.0 [v0.23.0]: https://github.com/Kava-Labs/kava/compare/v0.21.1...v0.23.0
[v0.16.1]: https://github.com/Kava-Labs/kava/compare/v0.16.0...v0.16.1 [v0.16.1]: https://github.com/Kava-Labs/kava/compare/v0.16.0...v0.16.1
[v0.16.0]: https://github.com/Kava-Labs/kava/compare/v0.15.2...v0.16.0 [v0.16.0]: https://github.com/Kava-Labs/kava/compare/v0.15.2...v0.16.0

View File

@ -7,7 +7,7 @@ FROM golang:1.20-alpine AS build-env
RUN apk add bash git make libc-dev gcc linux-headers eudev-dev jq curl RUN apk add bash git make libc-dev gcc linux-headers eudev-dev jq curl
# Set working directory for the build # Set working directory for the build
WORKDIR /root/kava WORKDIR /root/0g-chain
# default home directory is /root # default home directory is /root
# Copy dependency files first to facilitate dependency caching # Copy dependency files first to facilitate dependency caching
@ -32,6 +32,6 @@ RUN --mount=type=cache,target=/root/.cache/go-build \
FROM alpine:3.15 FROM alpine:3.15
RUN apk add bash jq curl RUN apk add bash jq curl
COPY --from=build-env /go/bin/kava /bin/kava COPY --from=build-env /go/bin/0gchaind /bin/0gchaind
CMD ["kava"] CMD ["0gchaind"]

View File

@ -1,4 +1,4 @@
FROM golang:1.20-bullseye AS kava-builder FROM golang:1.20-bullseye AS chain-builder
# Set up dependencies # Set up dependencies
RUN apt-get update \ RUN apt-get update \
@ -10,7 +10,7 @@ WORKDIR /root
# default home directory is /root # default home directory is /root
# install rocksdb # install rocksdb
ARG rocksdb_version=v8.1.1 ARG rocksdb_version=v8.10.0
ENV ROCKSDB_VERSION=$rocksdb_version ENV ROCKSDB_VERSION=$rocksdb_version
RUN git clone https://github.com/facebook/rocksdb.git \ RUN git clone https://github.com/facebook/rocksdb.git \
@ -19,7 +19,7 @@ RUN git clone https://github.com/facebook/rocksdb.git \
&& make -j$(nproc) install-shared \ && make -j$(nproc) install-shared \
&& ldconfig && ldconfig
WORKDIR /root/kava WORKDIR /root/0gchain
# Copy dependency files first to facilitate dependency caching # Copy dependency files first to facilitate dependency caching
COPY ./go.mod ./ COPY ./go.mod ./
COPY ./go.sum ./ COPY ./go.sum ./
@ -32,13 +32,13 @@ RUN --mount=type=cache,target=/root/.cache/go-build \
# Add source files # Add source files
COPY . . COPY . .
ARG kava_database_backend=rocksdb ARG 0gchain_database_backend=rocksdb
ENV KAVA_DATABASE_BACKEND=$kava_database_backend ENV 0GCHAIN_DATABASE_BACKEND=$0gchain_database_backend
# Mount go build and mod caches as container caches, persisted between builder invocations # Mount go build and mod caches as container caches, persisted between builder invocations
RUN --mount=type=cache,target=/root/.cache/go-build \ RUN --mount=type=cache,target=/root/.cache/go-build \
--mount=type=cache,target=/go/pkg/mod \ --mount=type=cache,target=/go/pkg/mod \
make install COSMOS_BUILD_OPTIONS=$KAVA_DATABASE_BACKEND make install COSMOS_BUILD_OPTIONS=$0GCHAIN_DATABASE_BACKEND
FROM ubuntu:22.04 FROM ubuntu:22.04
@ -48,10 +48,10 @@ RUN apt-get update \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# copy rocksdb shared objects # copy rocksdb shared objects
COPY --from=kava-builder /usr/local/lib/ /usr/local/lib/ COPY --from=chain-builder /usr/local/lib/ /usr/local/lib/
RUN ldconfig RUN ldconfig
# copy kava binary # copy 0g-chain binary
COPY --from=kava-builder /go/bin/kava /bin/kava COPY --from=chain-builder /go/bin/0gchaind /bin/0gchaind
CMD ["kava"] CMD ["0gchaind"]

View File

@ -1,8 +1,10 @@
################################################################################ ################################################################################
### Project Info ### ### Project Info ###
################################################################################ ################################################################################
PROJECT_NAME := kava# unique namespace for project PROJECT_NAME := 0g-chain# unique namespace for project
BINARY_NAME := 0gchaind
MAIN_ENTRY := ./cmd/$(BINARY_NAME)
DOCKER_IMAGE_NAME := 0glabs/$(PROJECT_NAME)
GO_BIN ?= go GO_BIN ?= go
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD) GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
@ -28,7 +30,7 @@ VERSION := $(GIT_COMMIT_SHORT)
VERSION_NUMBER := $(VERSION) VERSION_NUMBER := $(VERSION)
endif endif
TENDERMINT_VERSION := $(shell $(GO_BIN) list -m github.com/tendermint/tendermint | sed 's:.* ::') TENDERMINT_VERSION := $(shell $(GO_BIN) list -m github.com/cometbft/cometbft | sed 's:.* ::')
COSMOS_SDK_VERSION := $(shell $(GO_BIN) list -m github.com/cosmos/cosmos-sdk | sed 's:.* ::') COSMOS_SDK_VERSION := $(shell $(GO_BIN) list -m github.com/cosmos/cosmos-sdk | sed 's:.* ::')
.PHONY: print-git-info .PHONY: print-git-info
@ -37,7 +39,7 @@ print-git-info:
.PHONY: print-version .PHONY: print-version
print-version: print-version:
@echo "kava $(VERSION)\ntendermint $(TENDERMINT_VERSION)\ncosmos $(COSMOS_SDK_VERSION)" @echo "$(BINARY_NAME) $(VERSION)\ntendermint $(TENDERMINT_VERSION)\ncosmos $(COSMOS_SDK_VERSION)"
################################################################################ ################################################################################
### Project Settings ### ### Project Settings ###
@ -45,7 +47,7 @@ print-version:
LEDGER_ENABLED ?= true LEDGER_ENABLED ?= true
DOCKER:=docker DOCKER:=docker
DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace bufbuild/buf DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace bufbuild/buf
HTTPS_GIT := https://github.com/Kava-Labs/kava.git HTTPS_GIT := https://github.com/0glabs/0g-chain.git
################################################################################ ################################################################################
### Machine Info ### ### Machine Info ###
@ -76,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
@ -142,12 +144,12 @@ build_tags_comma_sep := $(subst $(whitespace),$(comma),$(build_tags))
# process linker flags # process linker flags
ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=kava \ ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=$(PROJECT_NAME) \
-X github.com/cosmos/cosmos-sdk/version.AppName=kava \ -X github.com/cosmos/cosmos-sdk/version.AppName=$(PROJECT_NAME) \
-X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION_NUMBER) \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION_NUMBER) \
-X github.com/cosmos/cosmos-sdk/version.Commit=$(GIT_COMMIT) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(GIT_COMMIT) \
-X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \ -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \
-X github.com/tendermint/tendermint/version.TMCoreSemVer=$(TENDERMINT_VERSION) -X github.com/cometbft/cometbft/version.TMCoreSemVer=$(TENDERMINT_VERSION)
# DB backend selection # DB backend selection
ifeq (cleveldb,$(findstring cleveldb,$(COSMOS_BUILD_OPTIONS))) ifeq (cleveldb,$(findstring cleveldb,$(COSMOS_BUILD_OPTIONS)))
@ -188,16 +190,16 @@ all: install
build: go.sum build: go.sum
ifeq ($(OS), Windows_NT) ifeq ($(OS), Windows_NT)
$(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/kava.exe ./cmd/kava $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/$(BINARY_NAME).exe $(MAIN_ENTRY)
else else
$(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/kava ./cmd/kava $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/$(BINARY_NAME) $(MAIN_ENTRY)
endif endif
build-linux: go.sum build-linux: go.sum
LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build
install: go.sum install: go.sum
$(GO_BIN) install -mod=readonly $(BUILD_FLAGS) ./cmd/kava $(GO_BIN) install -mod=readonly $(BUILD_FLAGS) $(MAIN_ENTRY)
######################################## ########################################
### Tools & dependencies ### Tools & dependencies
@ -219,6 +221,7 @@ go.sum: go.mod
# Set to exclude riot links as they trigger false positives # Set to exclude riot links as they trigger false positives
link-check: link-check:
@$(GO_BIN) get -u github.com/raviqqe/liche@f57a5d1c5be4856454cb26de155a65a4fd856ee3 @$(GO_BIN) get -u github.com/raviqqe/liche@f57a5d1c5be4856454cb26de155a65a4fd856ee3
# TODO: replace kava in following line with project name
liche -r . --exclude "^http://127.*|^https://riot.im/app*|^http://kava-testnet*|^https://testnet-dex*|^https://kava3.data.kava.io*|^https://ipfs.io*|^https://apps.apple.com*|^https://kava.quicksync.io*" liche -r . --exclude "^http://127.*|^https://riot.im/app*|^http://kava-testnet*|^https://testnet-dex*|^https://kava3.data.kava.io*|^https://ipfs.io*|^https://apps.apple.com*|^https://kava.quicksync.io*"
@ -233,26 +236,26 @@ format:
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs misspell -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs misspell -w
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/tendermint find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/tendermint
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/cosmos/cosmos-sdk find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/cosmos/cosmos-sdk
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/kava-labs/kava find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/0glabs/0g-chain
.PHONY: format .PHONY: format
############################################################################### ###############################################################################
### Localnet ### ### Localnet ###
############################################################################### ###############################################################################
# Build docker image and tag as kava/kava:local # Build docker image and tag as 0glabs/0g-chain:local
docker-build: docker-build:
DOCKER_BUILDKIT=1 $(DOCKER) build -t kava/kava:local . DOCKER_BUILDKIT=1 $(DOCKER) build -t $(DOCKER_IMAGE_NAME):local .
docker-build-rocksdb: docker-build-rocksdb:
DOCKER_BUILDKIT=1 $(DOCKER) build -f Dockerfile-rocksdb -t kava/kava:local . DOCKER_BUILDKIT=1 $(DOCKER) build -f Dockerfile-rocksdb -t $(DOCKER_IMAGE_NAME):local .
build-docker-local-kava: build-docker-local-0gchain:
@$(MAKE) -C networks/local @$(MAKE) -C networks/local
# Run a 4-node testnet locally # Run a 4-node testnet locally
localnet-start: build-linux localnet-stop localnet-start: build-linux localnet-stop
@if ! [ -f build/node0/kvd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/kvd:Z kava/kavanode testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi @if ! [ -f build/node0/kvd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/kvd:Z $(DOCKER_IMAGE_NAME)-node testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi
docker-compose up -d docker-compose up -d
localnet-stop: localnet-stop:
@ -261,7 +264,7 @@ localnet-stop:
# Launch a new single validator chain # Launch a new single validator chain
start: start:
./contrib/devnet/init-new-chain.sh ./contrib/devnet/init-new-chain.sh
kava start $(BINARY_NAME) start
#proto-format: #proto-format:
#@echo "Formatting Protobuf files" #@echo "Formatting Protobuf files"
@ -302,7 +305,7 @@ test:
@$(GO_BIN) test $$($(GO_BIN) list ./... | grep -v 'contrib' | grep -v 'tests/e2e') @$(GO_BIN) test $$($(GO_BIN) list ./... | grep -v 'contrib' | grep -v 'tests/e2e')
test-rocksdb: test-rocksdb:
@go test -tags=rocksdb ./cmd/kava/opendb @go test -tags=rocksdb $(MAIN_ENTRY)/opendb
# Run cli integration tests # Run cli integration tests
# `-p 4` to use 4 cores, `-tags cli_test` to tell $(GO_BIN) not to ignore the cli package # `-p 4` to use 4 cores, `-tags cli_test` to tell $(GO_BIN) not to ignore the cli package
@ -318,18 +321,19 @@ test-migrate:
# This submits an AWS Batch job to run a lot of sims, each within a docker image. Results are uploaded to S3 # This submits an AWS Batch job to run a lot of sims, each within a docker image. Results are uploaded to S3
start-remote-sims: start-remote-sims:
# build the image used for running sims in, and tag it # build the image used for running sims in, and tag it
docker build -f simulations/Dockerfile -t kava/kava-sim:master . docker build -f simulations/Dockerfile -t $(DOCKER_IMAGE_NAME)-sim:master .
# push that image to the hub # push that image to the hub
docker push kava/kava-sim:master docker push $(DOCKER_IMAGE_NAME)-sim:master
# submit an array job on AWS Batch, using 1000 seeds, spot instances # submit an array job on AWS Batch, using 1000 seeds, spot instances
aws batch submit-job \ aws batch submit-job \
-—job-name "master-$(VERSION)" \ -—job-name "master-$(VERSION)" \
-—job-queue “simulation-1-queue-spot" \ -—job-queue “simulation-1-queue-spot" \
-—array-properties size=1000 \ -—array-properties size=1000 \
-—job-definition kava-sim-master \ -—job-definition $(BINARY_NAME)-sim-master \
-—container-override environment=[{SIM_NAME=master-$(VERSION)}] -—container-override environment=[{SIM_NAME=master-$(VERSION)}]
update-kvtool: update-kvtool:
git submodule init || true
git submodule update git submodule update
cd tests/e2e/kvtool && make install cd tests/e2e/kvtool && make install

View File

@ -1,36 +1,29 @@
<!---
<p align="center"> <p align="center">
<img src="./kava-logo.svg" width="300"> <img src="./0g-logo.svg" width="300">
</p> </p>
--->
# 0G Chain
<div align="center"> <div align="center">
[![version](https://img.shields.io/github/tag/kava-labs/kava.svg)](https://github.com/kava-labs/kava/releases/latest) ### [Telegram](https://t.me/web3_0glabs) | [Discord](https://discord.com/invite/0glabs)
[![CircleCI](https://circleci.com/gh/Kava-Labs/kava/tree/master.svg?style=shield)](https://circleci.com/gh/Kava-Labs/kava/tree/master)
[![Go Report Card](https://goreportcard.com/badge/github.com/kava-labs/kava)](https://goreportcard.com/report/github.com/kava-labs/kava)
[![API Reference](https://godoc.org/github.com/Kava-Labs/kava?status.svg)](https://godoc.org/github.com/Kava-Labs/kava)
[![GitHub](https://img.shields.io/github/license/kava-labs/kava.svg)](https://github.com/Kava-Labs/kava/blob/master/LICENSE.md)
[![Twitter Follow](https://img.shields.io/twitter/follow/KAVA_CHAIN.svg?label=Follow&style=social)](https://twitter.com/KAVA_CHAIN)
[![Discord Chat](https://img.shields.io/discord/704389840614981673.svg)](https://discord.com/invite/kQzh3Uv)
</div> </div>
<div align="center"> Reference implementation of 0G Chain, the first modular AI chain. Built using the [cosmos-sdk](https://github.com/cosmos/cosmos-sdk).
### [Telegram](https://t.me/kavalabs) | [Medium](https://medium.com/kava-labs) | [Discord](https://discord.gg/JJYnuCx)
</div>
Reference implementation of Kava, a blockchain for cross-chain DeFi. Built using the [cosmos-sdk](https://github.com/cosmos/cosmos-sdk).
<!---
## Mainnet ## Mainnet
The current recommended version of the software for mainnet is [v0.24.1](https://github.com/Kava-Labs/kava/releases/tag/v0.24.1). The master branch of this repository often contains considerable development work since the last mainnet release and is __not__ runnable on mainnet. The current recommended version of the software for mainnet is [v0.25.0](https://github.com/Kava-Labs/kava/releases/tag/v0.25.0) The master branch of this repository often contains considerable development work since the last mainnet release and is __not__ runnable on mainnet.
### Installation and Setup ### Installation and Setup
For detailed instructions see [the Kava docs](https://docs.kava.io/docs/participate/validator-node). For detailed instructions see [the Kava docs](https://docs.kava.io/docs/participate/validator-node).
```bash ```bash
git checkout v0.24.1 git checkout v0.25.0
make install make install
``` ```
@ -63,3 +56,4 @@ If you find a security issue, please report it to security [at] kava.io. Dependi
Copyright © Kava Labs, Inc. All rights reserved. Copyright © Kava Labs, Inc. All rights reserved.
Licensed under the [Apache v2 License](LICENSE.md). Licensed under the [Apache v2 License](LICENSE.md).
--->

View File

@ -11,15 +11,15 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/cometbft/cometbft-db"
"github.com/tendermint/tendermint/libs/log" abci "github.com/cometbft/cometbft/abci/types"
dbm "github.com/tendermint/tm-db" "github.com/cometbft/cometbft/libs/log"
"cosmossdk.io/simapp"
"github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/simapp/helpers"
"github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/store"
"github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
@ -32,15 +32,10 @@ import (
"github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/supply" "github.com/cosmos/cosmos-sdk/x/supply"
"github.com/kava-labs/kava/x/auction" "github.com/0glabs/0g-chain/x/bep3"
"github.com/kava-labs/kava/x/bep3" "github.com/0glabs/0g-chain/x/committee"
"github.com/kava-labs/kava/x/cdp" "github.com/0glabs/0g-chain/x/pricefeed"
"github.com/kava-labs/kava/x/committee" validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting"
"github.com/kava-labs/kava/x/incentive"
"github.com/kava-labs/kava/x/kavadist"
"github.com/kava-labs/kava/x/pricefeed"
"github.com/kava-labs/kava/x/swap"
validatorvesting "github.com/kava-labs/kava/x/validator-vesting"
) )
type StoreKeysPrefixes struct { type StoreKeysPrefixes struct {
@ -280,7 +275,7 @@ func TestAppStateDeterminism(t *testing.T) {
config.ExportParamsPath = "" config.ExportParamsPath = ""
config.OnOperation = false config.OnOperation = false
config.AllInvariants = false config.AllInvariants = false
config.ChainID = helpers.SimAppChainID config.ChainID = sims.SimAppChainID
numTimesToRunPerSeed := 2 numTimesToRunPerSeed := 2
appHashList := make([]json.RawMessage, numTimesToRunPerSeed) appHashList := make([]json.RawMessage, numTimesToRunPerSeed)

View File

@ -8,8 +8,13 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
abci "github.com/cometbft/cometbft/abci/types"
tmbytes "github.com/cometbft/cometbft/libs/bytes"
ctypes "github.com/cometbft/cometbft/rpc/core/types"
jsonrpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types"
"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"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
@ -18,10 +23,6 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
jsonrpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
) )
type SimulateRequestTestSuite struct { type SimulateRequestTestSuite struct {
@ -51,9 +52,9 @@ func (suite *SimulateRequestTestSuite) TearDownTest() {
} }
func (suite *SimulateRequestTestSuite) TestSimulateRequest() { func (suite *SimulateRequestTestSuite) TestSimulateRequest() {
fromAddr, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") fromAddr, err := sdk.AccAddressFromBech32("0g1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea")
suite.Require().NoError(err) suite.Require().NoError(err)
toAddr, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") toAddr, err := sdk.AccAddressFromBech32("0g1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w")
suite.Require().NoError(err) suite.Require().NoError(err)
simRequest := app.SimulateRequest{ simRequest := app.SimulateRequest{
@ -61,11 +62,11 @@ func (suite *SimulateRequestTestSuite) TestSimulateRequest() {
bank.MsgSend{ bank.MsgSend{
FromAddress: fromAddr, FromAddress: fromAddr,
ToAddress: toAddr, ToAddress: toAddr,
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), Amount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e6)),
}, },
}, },
Fee: auth.StdFee{ Fee: auth.StdFee{
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5e4))), Amount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(5e4)),
Gas: 1e6, Gas: 1e6,
}, },
Memo: "test memo", Memo: "test memo",

View File

@ -5,16 +5,16 @@ import (
"runtime/debug" "runtime/debug"
errorsmod "cosmossdk.io/errors" errorsmod "cosmossdk.io/errors"
tmlog "github.com/cometbft/cometbft/libs/log"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante" authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
ibcante "github.com/cosmos/ibc-go/v6/modules/core/ante" ibcante "github.com/cosmos/ibc-go/v7/modules/core/ante"
ibckeeper "github.com/cosmos/ibc-go/v6/modules/core/keeper" ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper"
evmante "github.com/evmos/ethermint/app/ante" evmante "github.com/evmos/ethermint/app/ante"
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
tmlog "github.com/tendermint/tendermint/libs/log"
) )
// HandlerOptions extend the SDK's AnteHandler options by requiring the IBC // HandlerOptions extend the SDK's AnteHandler options by requiring the IBC

View File

@ -7,9 +7,13 @@ import (
"time" "time"
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
tmdb "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
@ -17,17 +21,15 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
tmdb "github.com/tendermint/tm-db"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
bep3types "github.com/kava-labs/kava/x/bep3/types" "github.com/0glabs/0g-chain/chaincfg"
pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" bep3types "github.com/0glabs/0g-chain/x/bep3/types"
pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
app.SetSDKConfig() chaincfg.SetSDKConfig()
os.Exit(m.Run()) os.Exit(m.Run())
} }
@ -52,20 +54,21 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) {
App: *app.NewApp( App: *app.NewApp(
log.NewNopLogger(), log.NewNopLogger(),
tmdb.NewMemDB(), tmdb.NewMemDB(),
app.DefaultNodeHome, chaincfg.DefaultNodeHome,
nil, nil,
encodingConfig, encodingConfig,
opts, opts,
baseapp.SetChainID(app.TestChainId),
), ),
} }
chainID := "kavatest_1-1" chainID := app.TestChainId
tApp = tApp.InitializeFromGenesisStatesWithTimeAndChainID( tApp = tApp.InitializeFromGenesisStatesWithTimeAndChainID(
time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC),
chainID, chainID,
app.NewFundedGenStateWithSameCoins( app.NewFundedGenStateWithSameCoins(
tApp.AppCodec(), tApp.AppCodec(),
sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e9)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e9)),
testAddresses, testAddresses,
), ),
newBep3GenStateMulti(tApp.AppCodec(), deputy), newBep3GenStateMulti(tApp.AppCodec(), deputy),
@ -106,18 +109,18 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) {
for _, tc := range testcases { for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
stdTx, err := helpers.GenSignedMockTx( stdTx, err := sims.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())), rand.New(rand.NewSource(time.Now().UnixNano())),
encodingConfig.TxConfig, encodingConfig.TxConfig,
[]sdk.Msg{ []sdk.Msg{
banktypes.NewMsgSend( banktypes.NewMsgSend(
tc.address, tc.address,
testAddresses[0], testAddresses[0],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 1_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1_000_000)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee
helpers.DefaultGenTxGas, sims.DefaultGenTxGas,
chainID, chainID,
[]uint64{0}, []uint64{0},
[]uint64{0}, // fixed sequence numbers will cause tests to fail sig verification if the same address is used twice []uint64{0}, // fixed sequence numbers will cause tests to fail sig verification if the same address is used twice
@ -209,7 +212,7 @@ func TestAppAnteHandler_RejectMsgsInAuthz(t *testing.T) {
return msg return msg
} }
chainID := "kavatest_1-1" chainID := app.TestChainId
encodingConfig := app.MakeEncodingConfig() encodingConfig := app.MakeEncodingConfig()
testcases := []struct { testcases := []struct {
@ -238,12 +241,12 @@ func TestAppAnteHandler_RejectMsgsInAuthz(t *testing.T) {
chainID, chainID,
) )
stdTx, err := helpers.GenSignedMockTx( stdTx, err := sims.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())), rand.New(rand.NewSource(time.Now().UnixNano())),
encodingConfig.TxConfig, encodingConfig.TxConfig,
[]sdk.Msg{tc.msg}, []sdk.Msg{tc.msg},
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee
helpers.DefaultGenTxGas, sims.DefaultGenTxGas,
chainID, chainID,
[]uint64{0}, []uint64{0},
[]uint64{0}, []uint64{0},

View File

@ -5,13 +5,14 @@ import (
"testing" "testing"
"time" "time"
"github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/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
@ -38,18 +39,18 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_NotCheckTx(t *testing.T) {
fetcher := mockAddressFetcher(testAddresses[1:]...) fetcher := mockAddressFetcher(testAddresses[1:]...)
decorator := ante.NewAuthenticatedMempoolDecorator(fetcher) decorator := ante.NewAuthenticatedMempoolDecorator(fetcher)
tx, err := helpers.GenSignedMockTx( tx, err := sims.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())), rand.New(rand.NewSource(time.Now().UnixNano())),
txConfig, txConfig,
[]sdk.Msg{ []sdk.Msg{
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100_000_000)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee
helpers.DefaultGenTxGas, sims.DefaultGenTxGas,
"testing-chain-id", "testing-chain-id",
[]uint64{0}, []uint64{0},
[]uint64{0}, []uint64{0},
@ -73,23 +74,23 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Pass(t *testing.T) {
decorator := ante.NewAuthenticatedMempoolDecorator(fetcher) decorator := ante.NewAuthenticatedMempoolDecorator(fetcher)
tx, err := helpers.GenSignedMockTx( tx, err := sims.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())), rand.New(rand.NewSource(time.Now().UnixNano())),
txConfig, txConfig,
[]sdk.Msg{ []sdk.Msg{
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[2], testAddresses[2],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee
helpers.DefaultGenTxGas, sims.DefaultGenTxGas,
"testing-chain-id", "testing-chain-id",
[]uint64{0, 123}, []uint64{0, 123},
[]uint64{0, 123}, []uint64{0, 123},
@ -114,18 +115,18 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Reject(t *testing.T) {
decorator := ante.NewAuthenticatedMempoolDecorator(fetcher) decorator := ante.NewAuthenticatedMempoolDecorator(fetcher)
tx, err := helpers.GenSignedMockTx( tx, err := sims.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())), rand.New(rand.NewSource(time.Now().UnixNano())),
txConfig, txConfig,
[]sdk.Msg{ []sdk.Msg{
banktypes.NewMsgSend( banktypes.NewMsgSend(
testAddresses[0], testAddresses[0],
testAddresses[1], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
}, },
sdk.NewCoins(), // no fee sdk.NewCoins(), // no fee
helpers.DefaultGenTxGas, sims.DefaultGenTxGas,
"testing-chain-id", "testing-chain-id",
[]uint64{0}, []uint64{0},
[]uint64{0}, []uint64{0},

View File

@ -5,7 +5,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/authz" "github.com/cosmos/cosmos-sdk/x/authz"
@ -14,8 +14,9 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/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("ukava", 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("ukava", 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("ukava", 100e6)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100e6)),
), ),
&evmtypes.MsgEthereumTx{}, &evmtypes.MsgEthereumTx{},
}, },
@ -212,12 +213,12 @@ func TestAuthzLimiterDecorator(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
tx, err := helpers.GenSignedMockTx( tx, err := sims.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())), rand.New(rand.NewSource(time.Now().UnixNano())),
txConfig, txConfig,
tc.msgs, tc.msgs,
sdk.NewCoins(), sdk.NewCoins(),
helpers.DefaultGenTxGas, sims.DefaultGenTxGas,
"testing-chain-id", "testing-chain-id",
[]uint64{0}, []uint64{0},
[]uint64{0}, []uint64{0},

View File

@ -9,7 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/types/tx/signing"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
@ -20,6 +20,11 @@ import (
ethtypes "github.com/ethereum/go-ethereum/core/types" ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/crypto/tmhash"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
tmversion "github.com/cometbft/cometbft/proto/tendermint/version"
"github.com/cometbft/cometbft/version"
"github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/crypto/ethsecp256k1"
"github.com/evmos/ethermint/ethereum/eip712" "github.com/evmos/ethermint/ethereum/eip712"
"github.com/evmos/ethermint/tests" "github.com/evmos/ethermint/tests"
@ -27,23 +32,17 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/tmhash"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
"github.com/tendermint/tendermint/version"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
cdptypes "github.com/kava-labs/kava/x/cdp/types" "github.com/0glabs/0g-chain/chaincfg"
evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
evmutiltestutil "github.com/kava-labs/kava/x/evmutil/testutil" evmutiltestutil "github.com/0glabs/0g-chain/x/evmutil/testutil"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
hardtypes "github.com/kava-labs/kava/x/hard/types" pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types"
) )
const ( const (
ChainID = "kavatest_1-1" ChainID = app.TestChainId
USDCCoinDenom = "erc20/usdc" USDCCoinDenom = "erc20/usdc"
USDCCDPType = "erc20-usdc" USDCCDPType = "erc20-usdc"
) )
@ -138,6 +137,7 @@ func (suite *EIP712TestSuite) createTestEIP712CosmosTxBuilder(
func (suite *EIP712TestSuite) SetupTest() { func (suite *EIP712TestSuite) SetupTest() {
tApp := app.NewTestApp() tApp := app.NewTestApp()
suite.tApp = tApp suite.tApp = tApp
cdc := tApp.AppCodec() cdc := tApp.AppCodec()
suite.evmutilKeeper = tApp.GetEvmutilKeeper() suite.evmutilKeeper = tApp.GetEvmutilKeeper()
@ -157,7 +157,7 @@ func (suite *EIP712TestSuite) SetupTest() {
// Genesis states // Genesis states
evmGs := evmtypes.NewGenesisState( evmGs := evmtypes.NewGenesisState(
evmtypes.NewParams( evmtypes.NewParams(
"akava", // evmDenom chaincfg.EvmDenom, // evmDenom
false, // allowedUnprotectedTxs false, // allowedUnprotectedTxs
true, // enableCreate true, // enableCreate
true, // enableCall true, // enableCall
@ -172,47 +172,6 @@ func (suite *EIP712TestSuite) SetupTest() {
feemarketGenesis.Params.EnableHeight = 1 feemarketGenesis.Params.EnableHeight = 1
feemarketGenesis.Params.NoBaseFee = false feemarketGenesis.Params.NoBaseFee = false
cdpGenState := cdptypes.DefaultGenesisState()
cdpGenState.Params.GlobalDebtLimit = sdk.NewInt64Coin("usdx", 53000000000000)
cdpGenState.Params.CollateralParams = cdptypes.CollateralParams{
{
Denom: USDCCoinDenom,
Type: USDCCDPType,
LiquidationRatio: sdk.MustNewDecFromStr("1.01"),
DebtLimit: sdk.NewInt64Coin("usdx", 500000000000),
StabilityFee: sdk.OneDec(),
AuctionSize: sdkmath.NewIntFromUint64(10000000000),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
SpotMarketID: "usdc:usd",
LiquidationMarketID: "usdc:usd:30",
ConversionFactor: sdkmath.NewInt(18),
},
}
hardGenState := hardtypes.DefaultGenesisState()
hardGenState.Params.MoneyMarkets = []hardtypes.MoneyMarket{
{
Denom: "usdx",
BorrowLimit: hardtypes.BorrowLimit{
HasMaxLimit: true,
MaximumLimit: sdk.MustNewDecFromStr("100000000000"),
LoanToValue: sdk.MustNewDecFromStr("1"),
},
SpotMarketID: "usdx:usd",
ConversionFactor: sdkmath.NewInt(1_000_000),
InterestRateModel: hardtypes.InterestRateModel{
BaseRateAPY: sdk.MustNewDecFromStr("0.05"),
BaseMultiplier: sdk.MustNewDecFromStr("2"),
Kink: sdk.MustNewDecFromStr("0.8"),
JumpMultiplier: sdk.MustNewDecFromStr("10"),
},
ReserveFactor: sdk.MustNewDecFromStr("0.05"),
KeeperRewardPercentage: sdk.ZeroDec(),
},
}
pricefeedGenState := pricefeedtypes.DefaultGenesisState() pricefeedGenState := pricefeedtypes.DefaultGenesisState()
pricefeedGenState.Params.Markets = []pricefeedtypes.Market{ pricefeedGenState.Params.Markets = []pricefeedtypes.Market{
{ {
@ -261,15 +220,13 @@ func (suite *EIP712TestSuite) SetupTest() {
genState := app.GenesisState{ genState := app.GenesisState{
evmtypes.ModuleName: cdc.MustMarshalJSON(evmGs), evmtypes.ModuleName: cdc.MustMarshalJSON(evmGs),
feemarkettypes.ModuleName: cdc.MustMarshalJSON(feemarketGenesis), feemarkettypes.ModuleName: cdc.MustMarshalJSON(feemarketGenesis),
cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenState),
hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGenState),
pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState), pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState),
} }
// funds our test accounts with some ukava // funds our test accounts with some gas denom
coinsGenState := app.NewFundedGenStateWithSameCoins( coinsGenState := app.NewFundedGenStateWithSameCoins(
tApp.AppCodec(), tApp.AppCodec(),
sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e9)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e9)),
[]sdk.AccAddress{suite.testAddr, suite.testAddr2}, []sdk.AccAddress{suite.testAddr, suite.testAddr2},
) )
@ -334,6 +291,11 @@ func (suite *EIP712TestSuite) SetupTest() {
) )
suite.usdcEVMAddr = pair.GetAddress() suite.usdcEVMAddr = pair.GetAddress()
// update consensus params
cParams := tApp.GetConsensusParams(suite.ctx)
cParams.Block.MaxGas = sims.DefaultGenTxGas * 20
tApp.StoreConsensusParams(suite.ctx, cParams)
// Add a contract to evmutil conversion pair // Add a contract to evmutil conversion pair
evmutilParams := suite.evmutilKeeper.GetParams(suite.ctx) evmutilParams := suite.evmutilKeeper.GetParams(suite.ctx)
evmutilParams.EnabledConversionPairs = evmutilParams.EnabledConversionPairs =
@ -351,45 +313,17 @@ func (suite *EIP712TestSuite) SetupTest() {
params := evmKeeper.GetParams(suite.ctx) params := evmKeeper.GetParams(suite.ctx)
params.EIP712AllowedMsgs = []evmtypes.EIP712AllowedMsg{ params.EIP712AllowedMsgs = []evmtypes.EIP712AllowedMsg{
{ {
MsgTypeUrl: "/kava.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: "kava_erc20_address", Type: "string"}, {Name: "zgchain_erc20_address", Type: "string"},
{Name: "amount", Type: "string"}, {Name: "amount", Type: "string"},
}, },
}, },
{ {
MsgTypeUrl: "/kava.cdp.v1beta1.MsgCreateCDP", MsgTypeUrl: "/zgc.evmutil.v1beta1.MsgConvertCoinToERC20",
MsgValueTypeName: "MsgValueCDPCreate",
ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "sender", Type: "string"},
{Name: "collateral", Type: "Coin"},
{Name: "principal", Type: "Coin"},
{Name: "collateral_type", Type: "string"},
},
},
{
MsgTypeUrl: "/kava.cdp.v1beta1.MsgDeposit",
MsgValueTypeName: "MsgValueCDPDeposit",
ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "depositor", Type: "string"},
{Name: "owner", Type: "string"},
{Name: "collateral", Type: "Coin"},
{Name: "collateral_type", Type: "string"},
},
},
{
MsgTypeUrl: "/kava.hard.v1beta1.MsgDeposit",
MsgValueTypeName: "MsgValueHardDeposit",
ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "depositor", Type: "string"},
{Name: "amount", Type: "Coin[]"},
},
},
{
MsgTypeUrl: "/kava.evmutil.v1beta1.MsgConvertCoinToERC20",
MsgValueTypeName: "MsgValueEVMConvertCoinToERC20", MsgValueTypeName: "MsgValueEVMConvertCoinToERC20",
ValueTypes: []evmtypes.EIP712MsgAttrType{ ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "initiator", Type: "string"}, {Name: "initiator", Type: "string"},
@ -397,23 +331,6 @@ func (suite *EIP712TestSuite) SetupTest() {
{Name: "amount", Type: "Coin"}, {Name: "amount", Type: "Coin"},
}, },
}, },
{
MsgTypeUrl: "/kava.cdp.v1beta1.MsgRepayDebt",
MsgValueTypeName: "MsgValueCDPRepayDebt",
ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "sender", Type: "string"},
{Name: "collateral_type", Type: "string"},
{Name: "payment", Type: "Coin"},
},
},
{
MsgTypeUrl: "/kava.hard.v1beta1.MsgWithdraw",
MsgValueTypeName: "MsgValueHardWithdraw",
ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "depositor", Type: "string"},
{Name: "amount", Type: "Coin[]"},
},
},
} }
evmKeeper.SetParams(suite.ctx, params) evmKeeper.SetParams(suite.ctx, params)
@ -459,7 +376,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("ukava", 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))
@ -481,40 +398,43 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx bool failCheckTx bool
errMsg string errMsg string
}{ }{
{ // TODO: need fix
name: "processes deposit eip712 messages successfully", // {
usdcDepositAmt: 100, // name: "processes deposit eip712 messages successfully",
usdxToMintAmt: 99, // usdcDepositAmt: 100,
}, // usdxToMintAmt: 99,
// },
{ {
name: "fails when convertion more erc20 usdc than balance", name: "fails when convertion more erc20 usdc than balance",
usdcDepositAmt: 51_000, usdcDepositAmt: 51_000,
usdxToMintAmt: 100, usdxToMintAmt: 100,
errMsg: "transfer amount exceeds balance", errMsg: "transfer amount exceeds balance",
}, },
{ // TODO: need fix
name: "fails when minting more usdx than allowed", // {
usdcDepositAmt: 100, // name: "fails when minting more usdx than allowed",
usdxToMintAmt: 100, // usdcDepositAmt: 100,
errMsg: "proposed collateral ratio is below liquidation ratio", // usdxToMintAmt: 100,
}, // errMsg: "proposed collateral ratio is below liquidation ratio",
{ // },
name: "fails when trying to convert usdc for another address", // TODO: need fix
usdcDepositAmt: 100, // {
usdxToMintAmt: 90, // name: "fails when trying to convert usdc for another address",
errMsg: "unauthorized", // usdcDepositAmt: 100,
failCheckTx: true, // usdxToMintAmt: 90,
updateMsgs: func(msgs []sdk.Msg) []sdk.Msg { // errMsg: "unauthorized",
convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin( // failCheckTx: true,
suite.testEVMAddr2, // updateMsgs: func(msgs []sdk.Msg) []sdk.Msg {
suite.testAddr, // convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin(
suite.usdcEVMAddr, // suite.testEVMAddr2,
suite.getEVMAmount(100), // suite.testAddr,
) // suite.usdcEVMAddr,
msgs[0] = &convertMsg // suite.getEVMAmount(100),
return msgs // )
}, // msgs[0] = &convertMsg
}, // return msgs
// },
// },
{ {
name: "fails when trying to convert erc20 for non-whitelisted contract", name: "fails when trying to convert erc20 for non-whitelisted contract",
usdcDepositAmt: 100, usdcDepositAmt: 100,
@ -541,7 +461,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
var option *codectypes.Any var option *codectypes.Any
option, _ = codectypes.NewAnyWithValue(&etherminttypes.ExtensionOptionsWeb3Tx{ option, _ = codectypes.NewAnyWithValue(&etherminttypes.ExtensionOptionsWeb3Tx{
FeePayer: suite.testAddr.String(), FeePayer: suite.testAddr.String(),
TypedDataChainID: 1, TypedDataChainID: 2221,
FeePayerSig: []byte("sig"), FeePayerSig: []byte("sig"),
}) })
builder, _ := txBuilder.(authtx.ExtensionOptionsTxBuilder) builder, _ := txBuilder.(authtx.ExtensionOptionsTxBuilder)
@ -556,7 +476,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, "ukava") 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
}, },
@ -568,9 +488,9 @@ 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("ukava", 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(sims.DefaultGenTxGas*10), gasAmt, msgs,
) )
}, },
}, },
@ -581,9 +501,9 @@ 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("ukava", 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(sims.DefaultGenTxGas*10), gasAmt, msgs,
) )
}, },
}, },
@ -601,29 +521,17 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
suite.usdcEVMAddr, suite.usdcEVMAddr,
usdcAmt, usdcAmt,
) )
usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(tc.usdxToMintAmt))
mintMsg := cdptypes.NewMsgCreateCDP(
suite.testAddr,
sdk.NewCoin(USDCCoinDenom, usdcAmt),
sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt),
USDCCDPType,
)
lendMsg := hardtypes.NewMsgDeposit(
suite.testAddr,
sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)),
)
msgs := []sdk.Msg{ msgs := []sdk.Msg{
&convertMsg, &convertMsg,
&mintMsg,
&lendMsg,
} }
if tc.updateMsgs != nil { if tc.updateMsgs != nil {
msgs = tc.updateMsgs(msgs) msgs = tc.updateMsgs(msgs)
} }
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", 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(sims.DefaultGenTxGas*10), gasAmt, msgs,
) )
if tc.updateTx != nil { if tc.updateTx != nil {
txBuilder = tc.updateTx(txBuilder, msgs) txBuilder = tc.updateTx(txBuilder, msgs)
@ -659,17 +567,17 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
suite.Require().Equal(sdk.ZeroInt(), amt.Amount) suite.Require().Equal(sdk.ZeroInt(), amt.Amount)
// validate cdp // validate cdp
cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) // cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType)
suite.Require().True(found) // suite.Require().True(found)
suite.Require().Equal(suite.testAddr, cdp.Owner) // suite.Require().Equal(suite.testAddr, cdp.Owner)
suite.Require().Equal(sdk.NewCoin(USDCCoinDenom, suite.getEVMAmount(100)), cdp.Collateral) // suite.Require().Equal(sdk.NewCoin(USDCCoinDenom, suite.getEVMAmount(100)), cdp.Collateral)
suite.Require().Equal(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000)), cdp.Principal) // suite.Require().Equal(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000)), cdp.Principal)
// validate hard // validate hard
hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) // hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().True(found) // suite.Require().True(found)
suite.Require().Equal(suite.testAddr, hardDeposit.Depositor) // suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) // suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
} else { } else {
suite.Require().NotEqual(resDeliverTx.Code, uint32(0), resCheckTx.Log) suite.Require().NotEqual(resDeliverTx.Code, uint32(0), resCheckTx.Log)
suite.Require().Contains(resDeliverTx.Log, tc.errMsg) suite.Require().Contains(resDeliverTx.Log, tc.errMsg)
@ -689,27 +597,15 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.usdcEVMAddr, suite.usdcEVMAddr,
usdcAmt, usdcAmt,
) )
usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(99))
mintMsg := cdptypes.NewMsgCreateCDP(
suite.testAddr,
sdk.NewCoin(USDCCoinDenom, usdcAmt),
sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt),
USDCCDPType,
)
lendMsg := hardtypes.NewMsgDeposit(
suite.testAddr,
sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)),
)
depositMsgs := []sdk.Msg{ depositMsgs := []sdk.Msg{
&convertMsg, &convertMsg,
&mintMsg,
&lendMsg,
} }
// deliver deposit msg // deliver deposit msg
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", 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(sims.DefaultGenTxGas*10), gasAmt, depositMsgs,
) )
txBytes, err := encodingConfig.TxConfig.TxEncoder()(txBuilder.GetTx()) txBytes, err := encodingConfig.TxConfig.TxEncoder()(txBuilder.GetTx())
suite.Require().NoError(err) suite.Require().NoError(err)
@ -721,10 +617,10 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log) suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log)
// validate hard // validate hard
hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) // hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().True(found) // suite.Require().True(found)
suite.Require().Equal(suite.testAddr, hardDeposit.Depositor) // suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) // suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
// validate erc20 balance // validate erc20 balance
coinBal, err := suite.evmutilKeeper.QueryERC20BalanceOf(suite.ctx, suite.usdcEVMAddr, suite.testEVMAddr) coinBal, err := suite.evmutilKeeper.QueryERC20BalanceOf(suite.ctx, suite.usdcEVMAddr, suite.testEVMAddr)
@ -737,24 +633,13 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.testEVMAddr.String(), suite.testEVMAddr.String(),
sdk.NewCoin(USDCCoinDenom, usdcAmt), sdk.NewCoin(USDCCoinDenom, usdcAmt),
) )
cdpWithdrawMsg := cdptypes.NewMsgRepayDebt(
suite.testAddr,
USDCCDPType,
sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt),
)
hardWithdrawMsg := hardtypes.NewMsgWithdraw(
suite.testAddr,
sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)),
)
withdrawMsgs := []sdk.Msg{ withdrawMsgs := []sdk.Msg{
&hardWithdrawMsg,
&cdpWithdrawMsg,
&withdrawConvertMsg, &withdrawConvertMsg,
} }
// deliver withdraw msg // deliver withdraw msg
txBuilder = suite.createTestEIP712CosmosTxBuilder( txBuilder = suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, withdrawMsgs, suite.testAddr, suite.testPrivKey, ChainID, uint64(sims.DefaultGenTxGas*10), gasAmt, withdrawMsgs,
) )
txBytes, err = encodingConfig.TxConfig.TxEncoder()(txBuilder.GetTx()) txBytes, err = encodingConfig.TxConfig.TxEncoder()(txBuilder.GetTx())
suite.Require().NoError(err) suite.Require().NoError(err)
@ -766,10 +651,10 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log) suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log)
// validate hard & cdp should be repayed // validate hard & cdp should be repayed
_, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) // _, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().False(found) // suite.Require().False(found)
_, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) // _, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType)
suite.Require().False(found) // suite.Require().False(found)
// validate user cosmos erc20/usd balance // validate user cosmos erc20/usd balance
bk := suite.tApp.GetBankKeeper() bk := suite.tApp.GetBankKeeper()

View File

@ -4,15 +4,16 @@ import (
"strings" "strings"
"testing" "testing"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
tmtime "github.com/cometbft/cometbft/types/time"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/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: "akava", EvmDenom: chaincfg.EvmDenom,
}) })
testCases := []struct { testCases := []struct {
@ -44,29 +45,29 @@ func TestEvmMinGasFilter(t *testing.T) {
mustParseDecCoins(""), mustParseDecCoins(""),
}, },
{ {
"zero ukava gas price", "zero ua0gi gas price",
mustParseDecCoins("0ukava"), mustParseDecCoins("0ua0gi"),
mustParseDecCoins("0ukava"), mustParseDecCoins("0ua0gi"),
}, },
{ {
"non-zero ukava gas price", "non-zero ua0gi gas price",
mustParseDecCoins("0.001ukava"), mustParseDecCoins("0.001ua0gi"),
mustParseDecCoins("0.001ukava"), mustParseDecCoins("0.001ua0gi"),
}, },
{ {
"zero ukava gas price, min akava price", "zero ua0gi gas price, min neuron price",
mustParseDecCoins("0ukava;100000akava"), mustParseDecCoins("0ua0gi;100000neuron"),
mustParseDecCoins("0ukava"), // akava is removed mustParseDecCoins("0ua0gi"), // neuron is removed
}, },
{ {
"zero ukava gas price, min akava price, other token", "zero ua0gi gas price, min neuron price, other token",
mustParseDecCoins("0ukava;100000akava;0.001other"), mustParseDecCoins("0ua0gi;100000neuron;0.001other"),
mustParseDecCoins("0ukava;0.001other"), // akava is removed mustParseDecCoins("0ua0gi;0.001other"), // neuron is removed
}, },
{ {
"non-zero ukava gas price, min akava price", "non-zero ua0gi gas price, min neuron price",
mustParseDecCoins("0.25ukava;100000akava;0.001other"), mustParseDecCoins("0.25ua0gi;100000neuron;0.001other"),
mustParseDecCoins("0.25ukava;0.001other"), // akava is removed mustParseDecCoins("0.25ua0gi;0.001other"), // neuron is removed
}, },
} }

View File

@ -4,7 +4,6 @@ import (
errorsmod "cosmossdk.io/errors" errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
) )
var _ sdk.AnteDecorator = VestingAccountDecorator{} var _ sdk.AnteDecorator = VestingAccountDecorator{}
@ -17,9 +16,9 @@ type VestingAccountDecorator struct {
func NewVestingAccountDecorator() VestingAccountDecorator { func NewVestingAccountDecorator() VestingAccountDecorator {
return VestingAccountDecorator{ return VestingAccountDecorator{
disabledMsgTypeUrls: []string{ disabledMsgTypeUrls: []string{
sdk.MsgTypeURL(&vesting.MsgCreateVestingAccount{}), // sdk.MsgTypeURL(&vesting.MsgCreateVestingAccount{}),
sdk.MsgTypeURL(&vesting.MsgCreatePermanentLockedAccount{}), // sdk.MsgTypeURL(&vesting.MsgCreatePermanentLockedAccount{}),
sdk.MsgTypeURL(&vesting.MsgCreatePeriodicVestingAccount{}), // sdk.MsgTypeURL(&vesting.MsgCreatePeriodicVestingAccount{}),
}, },
} }
} }

View File

@ -7,13 +7,14 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/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("ukava", 100_000_000)), 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("ukava", 100_000_000)), 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("ukava", 100_000_000)), sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
), ),
false, false,
"", "",
@ -72,14 +73,14 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
tx, err := helpers.GenSignedMockTx( tx, err := sims.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())), rand.New(rand.NewSource(time.Now().UnixNano())),
txConfig, txConfig,
[]sdk.Msg{ []sdk.Msg{
tt.msg, tt.msg,
}, },
sdk.NewCoins(), sdk.NewCoins(),
helpers.DefaultGenTxGas, sims.DefaultGenTxGas,
"testing-chain-id", "testing-chain-id",
[]uint64{0}, []uint64{0},
[]uint64{0}, []uint64{0},

View File

@ -3,11 +3,13 @@ package app
import ( import (
"fmt" "fmt"
"io" "io"
stdlog "log"
"net/http" "net/http"
"os"
"path/filepath"
sdkmath "cosmossdk.io/math"
dbm "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
tmjson "github.com/cometbft/cometbft/libs/json"
tmlog "github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node"
@ -23,9 +25,11 @@ import (
"github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/auth/vesting"
vestingkeeper "github.com/cosmos/cosmos-sdk/x/auth/vesting/keeper"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
"github.com/cosmos/cosmos-sdk/x/authz" "github.com/cosmos/cosmos-sdk/x/authz"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
@ -36,11 +40,13 @@ import (
"github.com/cosmos/cosmos-sdk/x/capability" "github.com/cosmos/cosmos-sdk/x/capability"
capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
consensus "github.com/cosmos/cosmos-sdk/x/consensus"
consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper"
consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types"
"github.com/cosmos/cosmos-sdk/x/crisis" "github.com/cosmos/cosmos-sdk/x/crisis"
crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper"
crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
distr "github.com/cosmos/cosmos-sdk/x/distribution" distr "github.com/cosmos/cosmos-sdk/x/distribution"
distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client"
distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/evidence" "github.com/cosmos/cosmos-sdk/x/evidence"
@ -72,104 +78,71 @@ import (
upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client"
upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
transfer "github.com/cosmos/ibc-go/v6/modules/apps/transfer" transfer "github.com/cosmos/ibc-go/v7/modules/apps/transfer"
ibctransferkeeper "github.com/cosmos/ibc-go/v6/modules/apps/transfer/keeper" ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper"
ibctransfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"
ibc "github.com/cosmos/ibc-go/v6/modules/core" ibc "github.com/cosmos/ibc-go/v7/modules/core"
ibcclient "github.com/cosmos/ibc-go/v6/modules/core/02-client" ibcclient "github.com/cosmos/ibc-go/v7/modules/core/02-client"
ibcclientclient "github.com/cosmos/ibc-go/v6/modules/core/02-client/client" ibcclientclient "github.com/cosmos/ibc-go/v7/modules/core/02-client/client"
ibcclienttypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types"
porttypes "github.com/cosmos/ibc-go/v6/modules/core/05-port/types" porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types"
ibchost "github.com/cosmos/ibc-go/v6/modules/core/24-host" ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported"
ibckeeper "github.com/cosmos/ibc-go/v6/modules/core/keeper" ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper"
ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint"
evmante "github.com/evmos/ethermint/app/ante" evmante "github.com/evmos/ethermint/app/ante"
ethermintconfig "github.com/evmos/ethermint/server/config" ethermintconfig "github.com/evmos/ethermint/server/config"
"github.com/evmos/ethermint/x/evm" "github.com/evmos/ethermint/x/evm"
evmkeeper "github.com/evmos/ethermint/x/evm/keeper" evmkeeper "github.com/evmos/ethermint/x/evm/keeper"
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/evmos/ethermint/x/evm/vm/geth"
"github.com/evmos/ethermint/x/feemarket" "github.com/evmos/ethermint/x/feemarket"
feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
"github.com/gorilla/mux" "github.com/gorilla/mux"
abci "github.com/tendermint/tendermint/abci/types" abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json" tmjson "github.com/tendermint/tendermint/libs/json"
tmlog "github.com/tendermint/tendermint/libs/log" tmlog "github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
"github.com/kava-labs/kava/app/ante" "github.com/0glabs/0g-chain/app/ante"
kavaparams "github.com/kava-labs/kava/app/params" chainparams "github.com/0glabs/0g-chain/app/params"
"github.com/kava-labs/kava/x/auction" "github.com/0glabs/0g-chain/chaincfg"
auctionkeeper "github.com/kava-labs/kava/x/auction/keeper" dasignersprecompile "github.com/0glabs/0g-chain/precompiles/dasigners"
auctiontypes "github.com/kava-labs/kava/x/auction/types"
"github.com/kava-labs/kava/x/bep3"
bep3keeper "github.com/kava-labs/kava/x/bep3/keeper"
bep3types "github.com/kava-labs/kava/x/bep3/types"
"github.com/kava-labs/kava/x/cdp"
cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper"
cdptypes "github.com/kava-labs/kava/x/cdp/types"
"github.com/kava-labs/kava/x/committee"
committeeclient "github.com/kava-labs/kava/x/committee/client"
committeekeeper "github.com/kava-labs/kava/x/committee/keeper"
committeetypes "github.com/kava-labs/kava/x/committee/types"
"github.com/kava-labs/kava/x/community"
communityclient "github.com/kava-labs/kava/x/community/client"
communitykeeper "github.com/kava-labs/kava/x/community/keeper"
communitytypes "github.com/kava-labs/kava/x/community/types"
earn "github.com/kava-labs/kava/x/earn"
earnclient "github.com/kava-labs/kava/x/earn/client"
earnkeeper "github.com/kava-labs/kava/x/earn/keeper"
earntypes "github.com/kava-labs/kava/x/earn/types"
evmutil "github.com/kava-labs/kava/x/evmutil"
evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types"
"github.com/kava-labs/kava/x/hard"
hardkeeper "github.com/kava-labs/kava/x/hard/keeper"
hardtypes "github.com/kava-labs/kava/x/hard/types"
"github.com/kava-labs/kava/x/incentive"
incentivekeeper "github.com/kava-labs/kava/x/incentive/keeper"
incentivetypes "github.com/kava-labs/kava/x/incentive/types"
issuance "github.com/kava-labs/kava/x/issuance"
issuancekeeper "github.com/kava-labs/kava/x/issuance/keeper"
issuancetypes "github.com/kava-labs/kava/x/issuance/types"
"github.com/kava-labs/kava/x/kavadist"
kavadistclient "github.com/kava-labs/kava/x/kavadist/client"
kavadistkeeper "github.com/kava-labs/kava/x/kavadist/keeper"
kavadisttypes "github.com/kava-labs/kava/x/kavadist/types"
"github.com/kava-labs/kava/x/liquid"
liquidkeeper "github.com/kava-labs/kava/x/liquid/keeper"
liquidtypes "github.com/kava-labs/kava/x/liquid/types"
metrics "github.com/kava-labs/kava/x/metrics"
metricstypes "github.com/kava-labs/kava/x/metrics/types"
pricefeed "github.com/kava-labs/kava/x/pricefeed"
pricefeedkeeper "github.com/kava-labs/kava/x/pricefeed/keeper"
pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types"
"github.com/kava-labs/kava/x/router"
routerkeeper "github.com/kava-labs/kava/x/router/keeper"
routertypes "github.com/kava-labs/kava/x/router/types"
savings "github.com/kava-labs/kava/x/savings"
savingskeeper "github.com/kava-labs/kava/x/savings/keeper"
savingstypes "github.com/kava-labs/kava/x/savings/types"
"github.com/kava-labs/kava/x/swap"
swapkeeper "github.com/kava-labs/kava/x/swap/keeper"
swaptypes "github.com/kava-labs/kava/x/swap/types"
validatorvesting "github.com/kava-labs/kava/x/validator-vesting"
validatorvestingrest "github.com/kava-labs/kava/x/validator-vesting/client/rest"
validatorvestingtypes "github.com/kava-labs/kava/x/validator-vesting/types"
)
const ( "github.com/0glabs/0g-chain/x/bep3"
appName = "kava" bep3keeper "github.com/0glabs/0g-chain/x/bep3/keeper"
bep3types "github.com/0glabs/0g-chain/x/bep3/types"
"github.com/0glabs/0g-chain/x/committee"
committeeclient "github.com/0glabs/0g-chain/x/committee/client"
committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper"
committeetypes "github.com/0glabs/0g-chain/x/committee/types"
council "github.com/0glabs/0g-chain/x/council/v1"
councilkeeper "github.com/0glabs/0g-chain/x/council/v1/keeper"
counciltypes "github.com/0glabs/0g-chain/x/council/v1/types"
dasigners "github.com/0glabs/0g-chain/x/dasigners/v1"
dasignerskeeper "github.com/0glabs/0g-chain/x/dasigners/v1/keeper"
dasignerstypes "github.com/0glabs/0g-chain/x/dasigners/v1/types"
evmutil "github.com/0glabs/0g-chain/x/evmutil"
evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
issuance "github.com/0glabs/0g-chain/x/issuance"
issuancekeeper "github.com/0glabs/0g-chain/x/issuance/keeper"
issuancetypes "github.com/0glabs/0g-chain/x/issuance/types"
pricefeed "github.com/0glabs/0g-chain/x/pricefeed"
pricefeedkeeper "github.com/0glabs/0g-chain/x/pricefeed/keeper"
pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting"
validatorvestingrest "github.com/0glabs/0g-chain/x/validator-vesting/client/rest"
validatorvestingtypes "github.com/0glabs/0g-chain/x/validator-vesting/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/vm"
) )
var ( var (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome string
// ModuleBasics manages simple versions of full app modules. // ModuleBasics manages simple versions of full app modules.
// It's used for things such as codec registration and genesis file verification. // It's used for things such as codec registration and genesis file verification.
ModuleBasics = module.NewBasicManager( ModuleBasics = module.NewBasicManager(
genutil.AppModuleBasic{}, genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator),
auth.AppModuleBasic{}, auth.AppModuleBasic{},
bank.AppModuleBasic{}, bank.AppModuleBasic{},
capability.AppModuleBasic{}, capability.AppModuleBasic{},
@ -177,22 +150,17 @@ var (
distr.AppModuleBasic{}, distr.AppModuleBasic{},
gov.NewAppModuleBasic([]govclient.ProposalHandler{ gov.NewAppModuleBasic([]govclient.ProposalHandler{
paramsclient.ProposalHandler, paramsclient.ProposalHandler,
distrclient.ProposalHandler,
upgradeclient.LegacyProposalHandler, upgradeclient.LegacyProposalHandler,
upgradeclient.LegacyCancelProposalHandler, upgradeclient.LegacyCancelProposalHandler,
ibcclientclient.UpdateClientProposalHandler, ibcclientclient.UpdateClientProposalHandler,
ibcclientclient.UpgradeProposalHandler, ibcclientclient.UpgradeProposalHandler,
kavadistclient.ProposalHandler,
committeeclient.ProposalHandler, committeeclient.ProposalHandler,
earnclient.DepositProposalHandler,
earnclient.WithdrawProposalHandler,
communityclient.LendDepositProposalHandler,
communityclient.LendWithdrawProposalHandler,
}), }),
params.AppModuleBasic{}, params.AppModuleBasic{},
crisis.AppModuleBasic{}, crisis.AppModuleBasic{},
slashing.AppModuleBasic{}, slashing.AppModuleBasic{},
ibc.AppModuleBasic{}, ibc.AppModuleBasic{},
ibctm.AppModuleBasic{},
upgrade.AppModuleBasic{}, upgrade.AppModuleBasic{},
evidence.AppModuleBasic{}, evidence.AppModuleBasic{},
authzmodule.AppModuleBasic{}, authzmodule.AppModuleBasic{},
@ -200,25 +168,15 @@ var (
vesting.AppModuleBasic{}, vesting.AppModuleBasic{},
evm.AppModuleBasic{}, evm.AppModuleBasic{},
feemarket.AppModuleBasic{}, feemarket.AppModuleBasic{},
kavadist.AppModuleBasic{},
auction.AppModuleBasic{},
issuance.AppModuleBasic{}, issuance.AppModuleBasic{},
bep3.AppModuleBasic{}, bep3.AppModuleBasic{},
pricefeed.AppModuleBasic{}, pricefeed.AppModuleBasic{},
swap.AppModuleBasic{},
cdp.AppModuleBasic{},
hard.AppModuleBasic{},
committee.AppModuleBasic{}, committee.AppModuleBasic{},
incentive.AppModuleBasic{},
savings.AppModuleBasic{},
validatorvesting.AppModuleBasic{}, validatorvesting.AppModuleBasic{},
evmutil.AppModuleBasic{}, evmutil.AppModuleBasic{},
liquid.AppModuleBasic{},
earn.AppModuleBasic{},
router.AppModuleBasic{},
mint.AppModuleBasic{}, mint.AppModuleBasic{},
community.AppModuleBasic{}, council.AppModuleBasic{},
metrics.AppModuleBasic{}, dasigners.AppModuleBasic{},
) )
// module account permissions // module account permissions
@ -233,27 +191,15 @@ var (
ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner},
evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // used for secure addition and subtraction of balance using module account evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // used for secure addition and subtraction of balance using module account
evmutiltypes.ModuleName: {authtypes.Minter, authtypes.Burner}, evmutiltypes.ModuleName: {authtypes.Minter, authtypes.Burner},
kavadisttypes.KavaDistMacc: {authtypes.Minter},
auctiontypes.ModuleName: nil,
issuancetypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner}, issuancetypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner},
bep3types.ModuleName: {authtypes.Burner, authtypes.Minter}, bep3types.ModuleName: {authtypes.Burner, authtypes.Minter},
swaptypes.ModuleName: nil,
cdptypes.ModuleName: {authtypes.Minter, authtypes.Burner},
cdptypes.LiquidatorMacc: {authtypes.Minter, authtypes.Burner},
hardtypes.ModuleAccountName: {authtypes.Minter},
savingstypes.ModuleAccountName: nil,
liquidtypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner},
earntypes.ModuleAccountName: nil,
kavadisttypes.FundModuleAccount: nil,
minttypes.ModuleName: {authtypes.Minter}, minttypes.ModuleName: {authtypes.Minter},
communitytypes.ModuleName: nil,
} }
) )
// Verify app interface at compile time // Verify app interface at compile time
var ( var (
_ servertypes.Application = (*App)(nil) _ servertypes.Application = (*App)(nil)
_ servertypes.ApplicationQueryService = (*App)(nil)
) )
// Options bundles several configuration params for an App. // Options bundles several configuration params for an App.
@ -266,7 +212,6 @@ type Options struct {
MempoolAuthAddresses []sdk.AccAddress MempoolAuthAddresses []sdk.AccAddress
EVMTrace string EVMTrace string
EVMMaxGasWanted uint64 EVMMaxGasWanted uint64
TelemetryOptions metricstypes.TelemetryOptions
} }
// DefaultOptions is a sensible default Options value. // DefaultOptions is a sensible default Options value.
@ -275,7 +220,7 @@ var DefaultOptions = Options{
EVMMaxGasWanted: ethermintconfig.DefaultMaxTxGasWanted, EVMMaxGasWanted: ethermintconfig.DefaultMaxTxGasWanted,
} }
// App is the Kava ABCI application. // App is the 0gChain ABCI application.
type App struct { type App struct {
*baseapp.BaseApp *baseapp.BaseApp
@ -293,7 +238,7 @@ type App struct {
accountKeeper authkeeper.AccountKeeper accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper bankKeeper bankkeeper.Keeper
capabilityKeeper *capabilitykeeper.Keeper capabilityKeeper *capabilitykeeper.Keeper
stakingKeeper stakingkeeper.Keeper stakingKeeper *stakingkeeper.Keeper
distrKeeper distrkeeper.Keeper distrKeeper distrkeeper.Keeper
govKeeper govkeeper.Keeper govKeeper govkeeper.Keeper
paramsKeeper paramskeeper.Keeper paramsKeeper paramskeeper.Keeper
@ -323,6 +268,7 @@ type App struct {
routerKeeper routerkeeper.Keeper routerKeeper routerkeeper.Keeper
mintKeeper mintkeeper.Keeper mintKeeper mintkeeper.Keeper
communityKeeper communitykeeper.Keeper communityKeeper communitykeeper.Keeper
consensusParamsKeeper consensusparamkeeper.Keeper
// make scoped keepers public for test purposes // make scoped keepers public for test purposes
ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedIBCKeeper capabilitykeeper.ScopedKeeper
@ -339,12 +285,6 @@ type App struct {
} }
func init() { func init() {
userHomeDir, err := os.UserHomeDir()
if err != nil {
stdlog.Printf("Failed to get home dir %v", err)
}
DefaultNodeHome = filepath.Join(userHomeDir, ".kava")
} }
// NewApp returns a reference to an initialized App. // NewApp returns a reference to an initialized App.
@ -353,7 +293,7 @@ func NewApp(
db dbm.DB, db dbm.DB,
homePath string, homePath string,
traceStore io.Writer, traceStore io.Writer,
encodingConfig kavaparams.EncodingConfig, encodingConfig chainparams.EncodingConfig,
options Options, options Options,
baseAppOptions ...func(*baseapp.BaseApp), baseAppOptions ...func(*baseapp.BaseApp),
) *App { ) *App {
@ -361,7 +301,7 @@ func NewApp(
legacyAmino := encodingConfig.Amino legacyAmino := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry interfaceRegistry := encodingConfig.InterfaceRegistry
bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...) bApp := baseapp.NewBaseApp(chaincfg.AppName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetVersion(version.Version) bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry) bApp.SetInterfaceRegistry(interfaceRegistry)
@ -369,20 +309,22 @@ func NewApp(
keys := sdk.NewKVStoreKeys( keys := sdk.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey,
distrtypes.StoreKey, slashingtypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey,
upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey,
evmtypes.StoreKey, feemarkettypes.StoreKey, authzkeeper.StoreKey, evmtypes.StoreKey, feemarkettypes.StoreKey, authzkeeper.StoreKey,
capabilitytypes.StoreKey, kavadisttypes.StoreKey, auctiontypes.StoreKey, capabilitytypes.StoreKey,
issuancetypes.StoreKey, bep3types.StoreKey, pricefeedtypes.StoreKey, issuancetypes.StoreKey, bep3types.StoreKey, pricefeedtypes.StoreKey,
swaptypes.StoreKey, cdptypes.StoreKey, hardtypes.StoreKey, communitytypes.StoreKey, swaptypes.StoreKey, cdptypes.StoreKey, hardtypes.StoreKey, communitytypes.StoreKey,
committeetypes.StoreKey, incentivetypes.StoreKey, evmutiltypes.StoreKey, committeetypes.StoreKey, incentivetypes.StoreKey, evmutiltypes.StoreKey,
savingstypes.StoreKey, earntypes.StoreKey, minttypes.StoreKey, savingstypes.StoreKey, earntypes.StoreKey, minttypes.StoreKey,
consensusparamtypes.StoreKey, crisistypes.StoreKey,
) )
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey)
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
// Authority for gov proposals, using the x/gov module account address // Authority for gov proposals, using the x/gov module account address
govAuthorityAddr := authtypes.NewModuleAddress(govtypes.ModuleName) govAuthAddr := authtypes.NewModuleAddress(govtypes.ModuleName)
govAuthAddrStr := govAuthAddr.String()
app := &App{ app := &App{
BaseApp: bApp, BaseApp: bApp,
@ -408,8 +350,6 @@ func NewApp(
slashingSubspace := app.paramsKeeper.Subspace(slashingtypes.ModuleName) slashingSubspace := app.paramsKeeper.Subspace(slashingtypes.ModuleName)
govSubspace := app.paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) govSubspace := app.paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable())
crisisSubspace := app.paramsKeeper.Subspace(crisistypes.ModuleName) crisisSubspace := app.paramsKeeper.Subspace(crisistypes.ModuleName)
kavadistSubspace := app.paramsKeeper.Subspace(kavadisttypes.ModuleName)
auctionSubspace := app.paramsKeeper.Subspace(auctiontypes.ModuleName)
issuanceSubspace := app.paramsKeeper.Subspace(issuancetypes.ModuleName) issuanceSubspace := app.paramsKeeper.Subspace(issuancetypes.ModuleName)
bep3Subspace := app.paramsKeeper.Subspace(bep3types.ModuleName) bep3Subspace := app.paramsKeeper.Subspace(bep3types.ModuleName)
pricefeedSubspace := app.paramsKeeper.Subspace(pricefeedtypes.ModuleName) pricefeedSubspace := app.paramsKeeper.Subspace(pricefeedtypes.ModuleName)
@ -418,19 +358,19 @@ func NewApp(
hardSubspace := app.paramsKeeper.Subspace(hardtypes.ModuleName) hardSubspace := app.paramsKeeper.Subspace(hardtypes.ModuleName)
incentiveSubspace := app.paramsKeeper.Subspace(incentivetypes.ModuleName) incentiveSubspace := app.paramsKeeper.Subspace(incentivetypes.ModuleName)
savingsSubspace := app.paramsKeeper.Subspace(savingstypes.ModuleName) savingsSubspace := app.paramsKeeper.Subspace(savingstypes.ModuleName)
ibcSubspace := app.paramsKeeper.Subspace(ibchost.ModuleName) ibcSubspace := app.paramsKeeper.Subspace(ibcexported.ModuleName)
ibctransferSubspace := app.paramsKeeper.Subspace(ibctransfertypes.ModuleName) ibctransferSubspace := app.paramsKeeper.Subspace(ibctransfertypes.ModuleName)
feemarketSubspace := app.paramsKeeper.Subspace(feemarkettypes.ModuleName) feemarketSubspace := app.paramsKeeper.Subspace(feemarkettypes.ModuleName)
evmSubspace := app.paramsKeeper.Subspace(evmtypes.ModuleName) evmSubspace := app.paramsKeeper.Subspace(evmtypes.ModuleName)
evmutilSubspace := app.paramsKeeper.Subspace(evmutiltypes.ModuleName) evmutilSubspace := app.paramsKeeper.Subspace(evmutiltypes.ModuleName)
earnSubspace := app.paramsKeeper.Subspace(earntypes.ModuleName)
mintSubspace := app.paramsKeeper.Subspace(minttypes.ModuleName) mintSubspace := app.paramsKeeper.Subspace(minttypes.ModuleName)
bApp.SetParamStore( // set the BaseApp's parameter store
app.paramsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable()), app.consensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], govAuthAddrStr)
) bApp.SetParamStore(&app.consensusParamsKeeper)
app.capabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey]) app.capabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey])
scopedIBCKeeper := app.capabilityKeeper.ScopeToModule(ibchost.ModuleName) scopedIBCKeeper := app.capabilityKeeper.ScopeToModule(ibcexported.ModuleName)
scopedTransferKeeper := app.capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) scopedTransferKeeper := app.capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName)
app.capabilityKeeper.Seal() app.capabilityKeeper.Seal()
@ -438,23 +378,27 @@ func NewApp(
app.accountKeeper = authkeeper.NewAccountKeeper( app.accountKeeper = authkeeper.NewAccountKeeper(
appCodec, appCodec,
keys[authtypes.StoreKey], keys[authtypes.StoreKey],
authSubspace,
authtypes.ProtoBaseAccount, authtypes.ProtoBaseAccount,
mAccPerms, mAccPerms,
sdk.GetConfig().GetBech32AccountAddrPrefix(), sdk.GetConfig().GetBech32AccountAddrPrefix(),
govAuthAddrStr,
) )
app.bankKeeper = bankkeeper.NewBaseKeeper( app.bankKeeper = bankkeeper.NewBaseKeeper(
appCodec, appCodec,
keys[banktypes.StoreKey], keys[banktypes.StoreKey],
app.accountKeeper, app.accountKeeper,
bankSubspace,
app.loadBlockedMaccAddrs(), app.loadBlockedMaccAddrs(),
govAuthAddrStr,
) )
app.vestingKeeper = vestingkeeper.NewVestingKeeper(app.accountKeeper, app.bankKeeper, keys[vestingtypes.StoreKey])
app.stakingKeeper = stakingkeeper.NewKeeper( app.stakingKeeper = stakingkeeper.NewKeeper(
appCodec, appCodec,
keys[stakingtypes.StoreKey], keys[stakingtypes.StoreKey],
app.accountKeeper, app.accountKeeper,
app.bankKeeper, app.bankKeeper,
govAuthAddrStr,
app.vestingKeeper,
stakingSubspace, stakingSubspace,
) )
app.authzKeeper = authzkeeper.NewKeeper( app.authzKeeper = authzkeeper.NewKeeper(
@ -466,42 +410,45 @@ func NewApp(
app.distrKeeper = distrkeeper.NewKeeper( app.distrKeeper = distrkeeper.NewKeeper(
appCodec, appCodec,
keys[distrtypes.StoreKey], keys[distrtypes.StoreKey],
distrSubspace,
app.accountKeeper, app.accountKeeper,
app.bankKeeper, app.bankKeeper,
&app.stakingKeeper, app.stakingKeeper,
authtypes.FeeCollectorName, authtypes.FeeCollectorName,
govAuthAddrStr,
) )
app.slashingKeeper = slashingkeeper.NewKeeper( app.slashingKeeper = slashingkeeper.NewKeeper(
appCodec, appCodec,
app.legacyAmino,
keys[slashingtypes.StoreKey], keys[slashingtypes.StoreKey],
&app.stakingKeeper, app.stakingKeeper,
slashingSubspace, govAuthAddrStr,
) )
app.crisisKeeper = crisiskeeper.NewKeeper( app.crisisKeeper = *crisiskeeper.NewKeeper(
crisisSubspace, appCodec,
keys[crisistypes.StoreKey],
options.InvariantCheckPeriod, options.InvariantCheckPeriod,
app.bankKeeper, app.bankKeeper,
authtypes.FeeCollectorName, authtypes.FeeCollectorName,
govAuthAddrStr,
) )
app.upgradeKeeper = upgradekeeper.NewKeeper( app.upgradeKeeper = *upgradekeeper.NewKeeper(
options.SkipUpgradeHeights, options.SkipUpgradeHeights,
keys[upgradetypes.StoreKey], keys[upgradetypes.StoreKey],
appCodec, appCodec,
homePath, homePath,
app.BaseApp, app.BaseApp,
govAuthorityAddr.String(), govAuthAddrStr,
) )
app.evidenceKeeper = *evidencekeeper.NewKeeper( app.evidenceKeeper = *evidencekeeper.NewKeeper(
appCodec, appCodec,
keys[evidencetypes.StoreKey], keys[evidencetypes.StoreKey],
&app.stakingKeeper, app.stakingKeeper,
app.slashingKeeper, app.slashingKeeper,
) )
app.ibcKeeper = ibckeeper.NewKeeper( app.ibcKeeper = ibckeeper.NewKeeper(
appCodec, appCodec,
keys[ibchost.StoreKey], keys[ibcexported.StoreKey],
ibcSubspace, ibcSubspace,
app.stakingKeeper, app.stakingKeeper,
app.upgradeKeeper, app.upgradeKeeper,
@ -511,7 +458,7 @@ func NewApp(
// Create Ethermint keepers // Create Ethermint keepers
app.feeMarketKeeper = feemarketkeeper.NewKeeper( app.feeMarketKeeper = feemarketkeeper.NewKeeper(
appCodec, appCodec,
govAuthorityAddr, govAuthAddr,
keys[feemarkettypes.StoreKey], keys[feemarkettypes.StoreKey],
tkeys[feemarkettypes.TransientKey], tkeys[feemarkettypes.TransientKey],
feemarketSubspace, feemarketSubspace,
@ -526,14 +473,23 @@ func NewApp(
) )
evmBankKeeper := evmutilkeeper.NewEvmBankKeeper(app.evmutilKeeper, app.bankKeeper, app.accountKeeper) evmBankKeeper := evmutilkeeper.NewEvmBankKeeper(app.evmutilKeeper, app.bankKeeper, app.accountKeeper)
// dasigners keeper
app.dasignersKeeper = dasignerskeeper.NewKeeper(keys[dasignerstypes.StoreKey], appCodec, app.stakingKeeper)
// precopmiles
precompiles := make(map[common.Address]vm.PrecompiledContract)
daSignersPrecompile, err := dasignersprecompile.NewDASignersPrecompile(app.dasignersKeeper)
if err != nil {
panic("initialize precompile failed")
}
precompiles[daSignersPrecompile.Address()] = daSignersPrecompile
// evm keeper
app.evmKeeper = evmkeeper.NewKeeper( app.evmKeeper = evmkeeper.NewKeeper(
appCodec, keys[evmtypes.StoreKey], tkeys[evmtypes.TransientKey], appCodec, keys[evmtypes.StoreKey], tkeys[evmtypes.TransientKey],
govAuthorityAddr, govAuthAddr,
app.accountKeeper, evmBankKeeper, app.stakingKeeper, app.feeMarketKeeper, app.accountKeeper, evmBankKeeper, app.stakingKeeper, app.feeMarketKeeper,
nil, // precompiled contracts
geth.NewEVM,
options.EVMTrace, options.EVMTrace,
evmSubspace, evmSubspace,
precompiles,
) )
app.evmutilKeeper.SetEvmKeeper(app.evmKeeper) app.evmutilKeeper.SetEvmKeeper(app.evmKeeper)
@ -557,13 +513,6 @@ func NewApp(
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferIBCModule) ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferIBCModule)
app.ibcKeeper.SetRouter(ibcRouter) app.ibcKeeper.SetRouter(ibcRouter)
app.auctionKeeper = auctionkeeper.NewKeeper(
appCodec,
keys[auctiontypes.StoreKey],
auctionSubspace,
app.bankKeeper,
app.accountKeeper,
)
app.issuanceKeeper = issuancekeeper.NewKeeper( app.issuanceKeeper = issuancekeeper.NewKeeper(
appCodec, appCodec,
keys[issuancetypes.StoreKey], keys[issuancetypes.StoreKey],
@ -614,7 +563,7 @@ func NewApp(
appCodec, appCodec,
app.accountKeeper, app.accountKeeper,
app.bankKeeper, app.bankKeeper,
&app.stakingKeeper, app.stakingKeeper,
&app.distrKeeper, &app.distrKeeper,
) )
savingsKeeper := savingskeeper.NewKeeper( savingsKeeper := savingskeeper.NewKeeper(
@ -650,11 +599,11 @@ func NewApp(
app.mintKeeper = mintkeeper.NewKeeper( app.mintKeeper = mintkeeper.NewKeeper(
appCodec, appCodec,
keys[minttypes.StoreKey], keys[minttypes.StoreKey],
mintSubspace,
app.stakingKeeper, app.stakingKeeper,
app.accountKeeper, app.accountKeeper,
app.bankKeeper, app.bankKeeper,
authtypes.FeeCollectorName, authtypes.FeeCollectorName,
govAuthAddrStr,
) )
// x/community's deposit/withdraw to lend proposals depend on hard keeper. // x/community's deposit/withdraw to lend proposals depend on hard keeper.
@ -669,7 +618,7 @@ func NewApp(
&app.mintKeeper, &app.mintKeeper,
&app.kavadistKeeper, &app.kavadistKeeper,
app.stakingKeeper, app.stakingKeeper,
govAuthorityAddr, govAuthAddr,
) )
app.incentiveKeeper = incentivekeeper.NewKeeper( app.incentiveKeeper = incentivekeeper.NewKeeper(
@ -692,17 +641,15 @@ func NewApp(
app.routerKeeper = routerkeeper.NewKeeper( app.routerKeeper = routerkeeper.NewKeeper(
&app.earnKeeper, &app.earnKeeper,
app.liquidKeeper, app.liquidKeeper,
&app.stakingKeeper, app.stakingKeeper,
) )
// create committee keeper with router // create committee keeper with router
committeeGovRouter := govv1beta1.NewRouter() committeeGovRouter := govv1beta1.NewRouter()
committeeGovRouter. committeeGovRouter.
AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler).
AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)).
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)). AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.upgradeKeeper))
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.upgradeKeeper))
// Note: the committee proposal handler is not registered on the committee router. This means committees cannot create or update other committees. // Note: the committee proposal handler is not registered on the committee router. This means committees cannot create or update other committees.
// Adding the committee proposal handler to the router is possible but awkward as the handler depends on the keeper which depends on the handler. // Adding the committee proposal handler to the router is possible but awkward as the handler depends on the keeper which depends on the handler.
app.committeeKeeper = committeekeeper.NewKeeper( app.committeeKeeper = committeekeeper.NewKeeper(
@ -715,19 +662,12 @@ func NewApp(
) )
// register the staking hooks // register the staking hooks
// NOTE: These keepers are passed by reference above, so they will contain these hooks. app.stakingKeeper.SetHooks(
app.stakingKeeper = *(app.stakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks( stakingtypes.NewMultiStakingHooks(
app.distrKeeper.Hooks(), app.distrKeeper.Hooks(),
app.slashingKeeper.Hooks(), app.slashingKeeper.Hooks(),
app.incentiveKeeper.Hooks(), app.incentiveKeeper.Hooks(),
))) ))
app.swapKeeper = *swapKeeper.SetHooks(app.incentiveKeeper.Hooks())
app.cdpKeeper = *cdpKeeper.SetHooks(cdptypes.NewMultiCDPHooks(app.incentiveKeeper.Hooks()))
app.hardKeeper = *hardKeeper.SetHooks(hardtypes.NewMultiHARDHooks(app.incentiveKeeper.Hooks()))
app.savingsKeeper = savingsKeeper // savings incentive hooks disabled
app.earnKeeper = *earnKeeper.SetHooks(app.incentiveKeeper.Hooks())
// create gov keeper with router // create gov keeper with router
// NOTE this must be done after any keepers referenced in the gov router (ie committee) are defined // NOTE this must be done after any keepers referenced in the gov router (ie committee) are defined
@ -735,80 +675,74 @@ func NewApp(
govRouter. govRouter.
AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.upgradeKeeper)). AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.upgradeKeeper)).
AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper)). AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper)).
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)).
AddRoute(kavadisttypes.RouterKey, kavadist.NewCommunityPoolMultiSpendProposalHandler(app.kavadistKeeper)).
AddRoute(earntypes.RouterKey, earn.NewCommunityPoolProposalHandler(app.earnKeeper)). AddRoute(earntypes.RouterKey, earn.NewCommunityPoolProposalHandler(app.earnKeeper)).
AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)). AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)).
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)).
AddRoute(committeetypes.RouterKey, committee.NewProposalHandler(app.committeeKeeper)) AddRoute(committeetypes.RouterKey, committee.NewProposalHandler(app.committeeKeeper))
govConfig := govtypes.DefaultConfig() govConfig := govtypes.DefaultConfig()
app.govKeeper = govkeeper.NewKeeper( govKeeper := govkeeper.NewKeeper(
appCodec, appCodec,
keys[govtypes.StoreKey], keys[govtypes.StoreKey],
govSubspace,
app.accountKeeper, app.accountKeeper,
app.bankKeeper, app.bankKeeper,
&app.stakingKeeper, app.stakingKeeper,
govRouter,
app.MsgServiceRouter(), app.MsgServiceRouter(),
govConfig, govConfig,
govAuthAddrStr,
) )
govKeeper.SetLegacyRouter(govRouter)
app.govKeeper = *govKeeper
// override x/gov tally handler with custom implementation // override x/gov tally handler with custom implementation
tallyHandler := NewTallyHandler( tallyHandler := NewTallyHandler(
app.govKeeper, app.stakingKeeper, app.savingsKeeper, app.earnKeeper, app.govKeeper, *app.stakingKeeper, app.savingsKeeper, app.earnKeeper,
app.liquidKeeper, app.bankKeeper, app.liquidKeeper, app.bankKeeper,
) )
app.govKeeper.SetTallyHandler(tallyHandler) app.govKeeper.SetTallyHandler(tallyHandler)
app.CouncilKeeper = councilkeeper.NewKeeper(
keys[counciltypes.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.)
app.mm = module.NewManager( app.mm = module.NewManager(
genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx, encodingConfig.TxConfig), genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx, encodingConfig.TxConfig),
auth.NewAppModule(appCodec, app.accountKeeper, nil), auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts, authSubspace),
bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper), bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper, bankSubspace),
capability.NewAppModule(appCodec, *app.capabilityKeeper), capability.NewAppModule(appCodec, *app.capabilityKeeper, false), // todo: confirm if this is okay to not be sealed
staking.NewAppModule(appCodec, app.stakingKeeper, app.accountKeeper, app.bankKeeper), staking.NewAppModule(appCodec, app.stakingKeeper, app.accountKeeper, app.bankKeeper, stakingSubspace),
distr.NewAppModule(appCodec, app.distrKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), distr.NewAppModule(appCodec, app.distrKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper, distrSubspace),
gov.NewAppModule(appCodec, app.govKeeper, app.accountKeeper, app.bankKeeper), gov.NewAppModule(appCodec, &app.govKeeper, app.accountKeeper, app.bankKeeper, govSubspace),
params.NewAppModule(app.paramsKeeper), params.NewAppModule(app.paramsKeeper),
crisis.NewAppModule(&app.crisisKeeper, options.SkipGenesisInvariants), crisis.NewAppModule(&app.crisisKeeper, options.SkipGenesisInvariants, crisisSubspace),
slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper, slashingSubspace),
consensus.NewAppModule(appCodec, app.consensusParamsKeeper),
ibc.NewAppModule(app.ibcKeeper), ibc.NewAppModule(app.ibcKeeper),
evm.NewAppModule(app.evmKeeper, app.accountKeeper), evm.NewAppModule(app.evmKeeper, app.accountKeeper),
feemarket.NewAppModule(app.feeMarketKeeper, feemarketSubspace), feemarket.NewAppModule(app.feeMarketKeeper, feemarketSubspace),
upgrade.NewAppModule(app.upgradeKeeper), upgrade.NewAppModule(&app.upgradeKeeper),
evidence.NewAppModule(app.evidenceKeeper), evidence.NewAppModule(app.evidenceKeeper),
transferModule, transferModule,
vesting.NewAppModule(app.accountKeeper, app.bankKeeper), vesting.NewAppModule(app.accountKeeper, app.vestingKeeper),
authzmodule.NewAppModule(appCodec, app.authzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry), authzmodule.NewAppModule(appCodec, app.authzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry),
kavadist.NewAppModule(app.kavadistKeeper, app.accountKeeper),
auction.NewAppModule(app.auctionKeeper, app.accountKeeper, app.bankKeeper),
issuance.NewAppModule(app.issuanceKeeper, app.accountKeeper, app.bankKeeper), issuance.NewAppModule(app.issuanceKeeper, app.accountKeeper, app.bankKeeper),
bep3.NewAppModule(app.bep3Keeper, app.accountKeeper, app.bankKeeper), bep3.NewAppModule(app.bep3Keeper, app.accountKeeper, app.bankKeeper),
pricefeed.NewAppModule(app.pricefeedKeeper, app.accountKeeper), pricefeed.NewAppModule(app.pricefeedKeeper, app.accountKeeper),
validatorvesting.NewAppModule(app.bankKeeper), validatorvesting.NewAppModule(app.bankKeeper),
swap.NewAppModule(app.swapKeeper, app.accountKeeper),
cdp.NewAppModule(app.cdpKeeper, app.accountKeeper, app.pricefeedKeeper, app.bankKeeper),
hard.NewAppModule(app.hardKeeper, app.accountKeeper, app.bankKeeper, app.pricefeedKeeper),
committee.NewAppModule(app.committeeKeeper, app.accountKeeper), committee.NewAppModule(app.committeeKeeper, app.accountKeeper),
incentive.NewAppModule(app.incentiveKeeper, app.accountKeeper, app.bankKeeper, app.cdpKeeper),
evmutil.NewAppModule(app.evmutilKeeper, app.bankKeeper, app.accountKeeper), evmutil.NewAppModule(app.evmutilKeeper, app.bankKeeper, app.accountKeeper),
savings.NewAppModule(app.savingsKeeper, app.accountKeeper, app.bankKeeper),
liquid.NewAppModule(app.liquidKeeper),
earn.NewAppModule(app.earnKeeper, app.accountKeeper, app.bankKeeper),
router.NewAppModule(app.routerKeeper),
// 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, mintSubspace),
community.NewAppModule(app.communityKeeper, app.accountKeeper), community.NewAppModule(app.communityKeeper, app.accountKeeper),
metrics.NewAppModule(options.TelemetryOptions), metrics.NewAppModule(options.TelemetryOptions),
) )
// Warning: Some begin blockers must run before others. Ensure the dependencies are understood before modifying this list. // Warning: Some begin blockers must run before others. Ensure the dependencies are understood before modifying this list.
app.mm.SetOrderBeginBlockers( app.mm.SetOrderBeginBlockers(
metricstypes.ModuleName,
// Upgrade begin blocker runs migrations on the first block after an upgrade. It should run before any other module. // Upgrade begin blocker runs migrations on the first block after an upgrade. It should run before any other module.
upgradetypes.ModuleName, upgradetypes.ModuleName,
// Capability begin blocker runs non state changing initialization. // Capability begin blocker runs non state changing initialization.
@ -818,7 +752,6 @@ func NewApp(
committeetypes.ModuleName, committeetypes.ModuleName,
// Community begin blocker should run before x/mint and x/kavadist since // Community begin blocker should run before x/mint and x/kavadist since
// the disable inflation upgrade will update those modules' params. // the disable inflation upgrade will update those modules' params.
communitytypes.ModuleName,
minttypes.ModuleName, minttypes.ModuleName,
distrtypes.ModuleName, distrtypes.ModuleName,
// During begin block slashing happens after distr.BeginBlocker so that // During begin block slashing happens after distr.BeginBlocker so that
@ -829,18 +762,13 @@ func NewApp(
stakingtypes.ModuleName, stakingtypes.ModuleName,
feemarkettypes.ModuleName, feemarkettypes.ModuleName,
evmtypes.ModuleName, evmtypes.ModuleName,
kavadisttypes.ModuleName,
// Auction begin blocker will close out expired auctions and pay debt back to cdp. // Auction begin blocker will close out expired auctions and pay debt back to cdp.
// It should be run before cdp begin blocker which cancels out debt with stable and starts more auctions. // It should be run before cdp begin blocker which cancels out debt with stable and starts more auctions.
auctiontypes.ModuleName,
cdptypes.ModuleName,
bep3types.ModuleName, bep3types.ModuleName,
hardtypes.ModuleName,
issuancetypes.ModuleName, issuancetypes.ModuleName,
incentivetypes.ModuleName, incentivetypes.ModuleName,
ibchost.ModuleName, ibcexported.ModuleName,
// Add all remaining modules with an empty begin blocker below since cosmos 0.45.0 requires it // Add all remaining modules with an empty begin blocker below since cosmos 0.45.0 requires it
swaptypes.ModuleName,
vestingtypes.ModuleName, vestingtypes.ModuleName,
pricefeedtypes.ModuleName, pricefeedtypes.ModuleName,
validatorvestingtypes.ModuleName, validatorvestingtypes.ModuleName,
@ -857,6 +785,7 @@ func NewApp(
liquidtypes.ModuleName, liquidtypes.ModuleName,
earntypes.ModuleName, earntypes.ModuleName,
routertypes.ModuleName, routertypes.ModuleName,
consensusparamtypes.ModuleName,
) )
// Warning: Some end blockers must run before others. Ensure the dependencies are understood before modifying this list. // Warning: Some end blockers must run before others. Ensure the dependencies are understood before modifying this list.
@ -870,21 +799,15 @@ func NewApp(
pricefeedtypes.ModuleName, pricefeedtypes.ModuleName,
// Add all remaining modules with an empty end blocker below since cosmos 0.45.0 requires it // Add all remaining modules with an empty end blocker below since cosmos 0.45.0 requires it
capabilitytypes.ModuleName, capabilitytypes.ModuleName,
incentivetypes.ModuleName,
issuancetypes.ModuleName, issuancetypes.ModuleName,
slashingtypes.ModuleName, slashingtypes.ModuleName,
distrtypes.ModuleName, distrtypes.ModuleName,
auctiontypes.ModuleName,
bep3types.ModuleName, bep3types.ModuleName,
cdptypes.ModuleName,
hardtypes.ModuleName,
committeetypes.ModuleName, committeetypes.ModuleName,
upgradetypes.ModuleName, upgradetypes.ModuleName,
evidencetypes.ModuleName, evidencetypes.ModuleName,
kavadisttypes.ModuleName,
swaptypes.ModuleName,
vestingtypes.ModuleName, vestingtypes.ModuleName,
ibchost.ModuleName, ibcexported.ModuleName,
validatorvestingtypes.ModuleName, validatorvestingtypes.ModuleName,
authtypes.ModuleName, authtypes.ModuleName,
banktypes.ModuleName, banktypes.ModuleName,
@ -893,13 +816,10 @@ func NewApp(
paramstypes.ModuleName, paramstypes.ModuleName,
authz.ModuleName, authz.ModuleName,
evmutiltypes.ModuleName, evmutiltypes.ModuleName,
savingstypes.ModuleName,
liquidtypes.ModuleName,
earntypes.ModuleName,
routertypes.ModuleName,
minttypes.ModuleName, minttypes.ModuleName,
communitytypes.ModuleName, communitytypes.ModuleName,
metricstypes.ModuleName, metricstypes.ModuleName,
consensusparamtypes.ModuleName,
) )
// Warning: Some init genesis methods must run before others. Ensure the dependencies are understood before modifying this list // Warning: Some init genesis methods must run before others. Ensure the dependencies are understood before modifying this list
@ -912,28 +832,18 @@ func NewApp(
slashingtypes.ModuleName, // iterates over validators, run after staking slashingtypes.ModuleName, // iterates over validators, run after staking
govtypes.ModuleName, govtypes.ModuleName,
minttypes.ModuleName, minttypes.ModuleName,
ibchost.ModuleName, ibcexported.ModuleName,
evidencetypes.ModuleName, evidencetypes.ModuleName,
authz.ModuleName, authz.ModuleName,
ibctransfertypes.ModuleName, ibctransfertypes.ModuleName,
evmtypes.ModuleName, evmtypes.ModuleName,
feemarkettypes.ModuleName, feemarkettypes.ModuleName,
kavadisttypes.ModuleName,
auctiontypes.ModuleName,
issuancetypes.ModuleName, issuancetypes.ModuleName,
savingstypes.ModuleName,
bep3types.ModuleName, bep3types.ModuleName,
pricefeedtypes.ModuleName, pricefeedtypes.ModuleName,
swaptypes.ModuleName,
cdptypes.ModuleName, // reads market prices, so must run after pricefeed genesis
hardtypes.ModuleName,
incentivetypes.ModuleName, // reads cdp params, so must run after cdp genesis
committeetypes.ModuleName, committeetypes.ModuleName,
evmutiltypes.ModuleName, evmutiltypes.ModuleName,
earntypes.ModuleName,
communitytypes.ModuleName,
genutiltypes.ModuleName, // runs arbitrary txs included in genisis state, so run after modules have been initialized genutiltypes.ModuleName, // runs arbitrary txs included in genisis state, so run after modules have been initialized
crisistypes.ModuleName, // runs the invariants at genesis, should run after other modules
// Add all remaining modules with an empty InitGenesis below since cosmos 0.45.0 requires it // Add all remaining modules with an empty InitGenesis below since cosmos 0.45.0 requires it
vestingtypes.ModuleName, vestingtypes.ModuleName,
paramstypes.ModuleName, paramstypes.ModuleName,
@ -942,10 +852,11 @@ func NewApp(
liquidtypes.ModuleName, liquidtypes.ModuleName,
routertypes.ModuleName, routertypes.ModuleName,
metricstypes.ModuleName, metricstypes.ModuleName,
consensusparamtypes.ModuleName,
crisistypes.ModuleName, // runs the invariants at genesis, should run after other modules
) )
app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterInvariants(&app.crisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
app.RegisterServices(app.configurator) app.RegisterServices(app.configurator)
@ -1044,7 +955,7 @@ func (app *App) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.Res
panic(err) panic(err)
} }
// Store current module versions in kava-10 to setup future in-place upgrades. // Store current module versions in 0gChain-10 to setup future in-place upgrades.
// During in-place migrations, the old module versions in the store will be referenced to determine which migrations to run. // During in-place migrations, the old module versions in the store will be referenced to determine which migrations to run.
app.upgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) app.upgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
@ -1106,7 +1017,7 @@ func RegisterAPIRouteRewrites(router *mux.Router) {
// Eg: querying /cosmos/distribution/v1beta1/community_pool will return // Eg: querying /cosmos/distribution/v1beta1/community_pool will return
// the same response as querying /kava/community/v1beta1/total_balance // the same response as querying /kava/community/v1beta1/total_balance
routeMap := map[string]string{ routeMap := map[string]string{
"/cosmos/distribution/v1beta1/community_pool": "/kava/community/v1beta1/total_balance", "/cosmos/distribution/v1beta1/community_pool": "/0g/community/v1beta1/total_balance",
} }
for clientPath, backendPath := range routeMap { for clientPath, backendPath := range routeMap {
@ -1147,16 +1058,6 @@ func (app *App) RegisterNodeService(clientCtx client.Context) {
func (app *App) loadBlockedMaccAddrs() map[string]bool { func (app *App) loadBlockedMaccAddrs() map[string]bool {
modAccAddrs := app.ModuleAccountAddrs() modAccAddrs := app.ModuleAccountAddrs()
allowedMaccs := map[string]bool{ allowedMaccs := map[string]bool{
// kavadist
app.accountKeeper.GetModuleAddress(kavadisttypes.ModuleName).String(): true,
// earn
app.accountKeeper.GetModuleAddress(earntypes.ModuleName).String(): true,
// liquid
app.accountKeeper.GetModuleAddress(liquidtypes.ModuleName).String(): true,
// kavadist fund
app.accountKeeper.GetModuleAddress(kavadisttypes.FundModuleAccount).String(): true,
// community
app.accountKeeper.GetModuleAddress(communitytypes.ModuleAccountName).String(): true,
// NOTE: if adding evmutil, adjust the cosmos-coins-fully-backed-invariant accordingly. // NOTE: if adding evmutil, adjust the cosmos-coins-fully-backed-invariant accordingly.
} }

View File

@ -8,25 +8,31 @@ import (
"testing" "testing"
"time" "time"
"github.com/0glabs/0g-chain/chaincfg"
db "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint"
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types" abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/types"
db "github.com/tendermint/tm-db" db "github.com/tendermint/tm-db"
) )
func TestNewApp(t *testing.T) { func TestNewApp(t *testing.T) {
SetSDKConfig() chaincfg.SetSDKConfig()
NewApp( NewApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)), log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db.NewMemDB(), db.NewMemDB(),
DefaultNodeHome, chaincfg.DefaultNodeHome,
nil, nil,
MakeEncodingConfig(), MakeEncodingConfig(),
DefaultOptions, DefaultOptions,
@ -34,9 +40,9 @@ func TestNewApp(t *testing.T) {
} }
func TestExport(t *testing.T) { func TestExport(t *testing.T) {
SetSDKConfig() chaincfg.SetSDKConfig()
db := db.NewMemDB() db := db.NewMemDB()
app := NewApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, DefaultNodeHome, nil, MakeEncodingConfig(), DefaultOptions) app := NewApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, chaincfg.DefaultNodeHome, nil, MakeEncodingConfig(), DefaultOptions, baseapp.SetChainID(TestChainId))
genesisState := GenesisStateWithSingleValidator(&TestApp{App: *app}, NewDefaultGenesisState()) genesisState := GenesisStateWithSingleValidator(&TestApp{App: *app}, NewDefaultGenesisState())
@ -45,21 +51,23 @@ func TestExport(t *testing.T) {
initRequest := abci.RequestInitChain{ initRequest := abci.RequestInitChain{
Time: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), Time: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC),
ChainId: "kavatest_1-1", ChainId: TestChainId,
InitialHeight: 1, InitialHeight: 1,
ConsensusParams: tmtypes.TM2PB.ConsensusParams(tmtypes.DefaultConsensusParams()), ConsensusParams: sims.DefaultConsensusParams,
Validators: nil, Validators: nil,
AppStateBytes: stateBytes, AppStateBytes: stateBytes,
} }
app.InitChain(initRequest) app.InitChain(initRequest)
app.Commit() app.Commit()
exportedApp, err := app.ExportAppStateAndValidators(false, []string{}) exportedApp, err := app.ExportAppStateAndValidators(false, []string{}, []string{})
require.NoError(t, err) require.NoError(t, err)
// Assume each module is exported correctly, so only check modules in genesis are present in export // Assume each module is exported correctly, so only check modules in genesis are present in export
initialModules, err := unmarshalJSONKeys(initRequest.AppStateBytes) initialModules, err := unmarshalJSONKeys(initRequest.AppStateBytes)
require.NoError(t, err) require.NoError(t, err)
// note ibctm is only registered in the BasicManager and not module manager so can be ignored
initialModules = removeIbcTmModule(initialModules)
exportedModules, err := unmarshalJSONKeys(exportedApp.AppState) exportedModules, err := unmarshalJSONKeys(exportedApp.AppState)
require.NoError(t, err) require.NoError(t, err)
assert.ElementsMatch(t, initialModules, exportedModules) assert.ElementsMatch(t, initialModules, exportedModules)
@ -143,3 +151,13 @@ func unmarshalJSONKeys(jsonBytes []byte) ([]string, error) {
return keys, nil return keys, nil
} }
func removeIbcTmModule(modules []string) []string {
var result []string
for _, str := range modules {
if str != ibctm.ModuleName {
result = append(result, str)
}
}
return result
}

View File

@ -1,41 +0,0 @@
package app
import sdk "github.com/cosmos/cosmos-sdk/types"
const (
// Bech32MainPrefix defines the Bech32 prefix for account addresses
Bech32MainPrefix = "kava"
// Bech32PrefixAccPub defines the Bech32 prefix of an account's public key
Bech32PrefixAccPub = Bech32MainPrefix + "pub"
// Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
Bech32PrefixValAddr = Bech32MainPrefix + "val" + "oper"
// Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
Bech32PrefixValPub = Bech32MainPrefix + "val" + "oper" + "pub"
// Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
Bech32PrefixConsAddr = Bech32MainPrefix + "val" + "cons"
// Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
Bech32PrefixConsPub = Bech32MainPrefix + "val" + "cons" + "pub"
Bip44CoinType = 459 // see https://github.com/satoshilabs/slips/blob/master/slip-0044.md
)
// SetSDKConfig configures the global config with kava app specific parameters.
// It does not seal the config to allow modification in tests.
func SetSDKConfig() *sdk.Config {
config := sdk.GetConfig()
SetBech32AddressPrefixes(config)
SetBip44CoinType(config)
return config
}
// SetBech32AddressPrefixes sets the global prefix to be used when serializing addresses to bech32 strings.
func SetBech32AddressPrefixes(config *sdk.Config) {
config.SetBech32PrefixForAccount(Bech32MainPrefix, Bech32PrefixAccPub)
config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub)
}
// SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets.
func SetBip44CoinType(config *sdk.Config) {
config.SetCoinType(Bip44CoinType)
}

View File

@ -3,7 +3,7 @@ package app
import ( import (
enccodec "github.com/evmos/ethermint/encoding/codec" enccodec "github.com/evmos/ethermint/encoding/codec"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
) )
// MakeEncodingConfig creates an EncodingConfig and registers the app's types on it. // MakeEncodingConfig creates an EncodingConfig and registers the app's types on it.

View File

@ -4,7 +4,7 @@ import (
"encoding/json" "encoding/json"
"log" "log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
servertypes "github.com/cosmos/cosmos-sdk/server/types" servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -14,7 +14,7 @@ import (
) )
// ExportAppStateAndValidators export the state of the app for a genesis file // ExportAppStateAndValidators export the state of the app for a genesis file
func (app *App) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteList []string, func (app *App) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteList []string, modulesToExport []string,
) (servertypes.ExportedApp, error) { ) (servertypes.ExportedApp, error) {
// as if they could withdraw from the start of the next block // as if they could withdraw from the start of the next block
// block time is not available and defaults to Jan 1st, 0001 // block time is not available and defaults to Jan 1st, 0001
@ -26,7 +26,7 @@ func (app *App) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteList []
app.prepForZeroHeightGenesis(ctx, jailWhiteList) app.prepForZeroHeightGenesis(ctx, jailWhiteList)
} }
genState := app.mm.ExportGenesis(ctx, app.appCodec) genState := app.mm.ExportGenesisForModules(ctx, app.appCodec, modulesToExport)
newAppState, err := json.MarshalIndent(genState, "", " ") newAppState, err := json.MarshalIndent(genState, "", " ")
if err != nil { if err != nil {
return servertypes.ExportedApp{}, err return servertypes.ExportedApp{}, err

View File

@ -1,5 +1,5 @@
/* /*
Package params defines the simulation parameters for the Kava app. Package params defines the simulation parameters for the 0gChain app.
It contains the default weights used for each transaction used on the module's It contains the default weights used for each transaction used on the module's
simulation. These weights define the chance for a transaction to be simulated at simulation. These weights define the chance for a transaction to be simulated at

View File

@ -8,10 +8,6 @@ import (
govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
earnkeeper "github.com/kava-labs/kava/x/earn/keeper"
liquidkeeper "github.com/kava-labs/kava/x/liquid/keeper"
liquidtypes "github.com/kava-labs/kava/x/liquid/types"
savingskeeper "github.com/kava-labs/kava/x/savings/keeper"
) )
var _ govv1.TallyHandler = TallyHandler{} var _ govv1.TallyHandler = TallyHandler{}
@ -20,23 +16,16 @@ var _ govv1.TallyHandler = TallyHandler{}
type TallyHandler struct { type TallyHandler struct {
gk govkeeper.Keeper gk govkeeper.Keeper
stk stakingkeeper.Keeper stk stakingkeeper.Keeper
svk savingskeeper.Keeper
ek earnkeeper.Keeper
lk liquidkeeper.Keeper
bk bankkeeper.Keeper bk bankkeeper.Keeper
} }
// NewTallyHandler creates a new tally handler. // NewTallyHandler creates a new tally handler.
func NewTallyHandler( func NewTallyHandler(
gk govkeeper.Keeper, stk stakingkeeper.Keeper, svk savingskeeper.Keeper, gk govkeeper.Keeper, stk stakingkeeper.Keeper, bk bankkeeper.Keeper,
ek earnkeeper.Keeper, lk liquidkeeper.Keeper, bk bankkeeper.Keeper,
) TallyHandler { ) TallyHandler {
return TallyHandler{ return TallyHandler{
gk: gk, gk: gk,
stk: stk, stk: stk,
svk: svk,
ek: ek,
lk: lk,
bk: bk, bk: bk,
} }
} }
@ -105,34 +94,34 @@ func (th TallyHandler) Tally(
}) })
// get voter bkava and update total voting power and results // get voter bkava and update total voting power and results
addrBkava := th.getAddrBkava(ctx, voter).toCoins() // addrBkava := th.getAddrBkava(ctx, voter).toCoins()
for _, coin := range addrBkava { // for _, coin := range addrBkava {
valAddr, err := liquidtypes.ParseLiquidStakingTokenDenom(coin.Denom) // valAddr, err := liquidtypes.ParseLiquidStakingTokenDenom(coin.Denom)
if err != nil { // if err != nil {
break // break
} // }
// reduce delegator shares by the amount of voter bkava for the validator // // reduce delegator shares by the amount of voter bkava for the validator
valAddrStr := valAddr.String() // valAddrStr := valAddr.String()
if val, ok := currValidators[valAddrStr]; ok { // if val, ok := currValidators[valAddrStr]; ok {
val.DelegatorDeductions = val.DelegatorDeductions.Add(sdk.NewDecFromInt(coin.Amount)) // val.DelegatorDeductions = val.DelegatorDeductions.Add(sdk.NewDecFromInt(coin.Amount))
currValidators[valAddrStr] = val // currValidators[valAddrStr] = val
} // }
// votingPower = amount of ukava coin // // votingPower = amount of ukava coin
stakedCoins, err := th.lk.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin)) // stakedCoins, err := th.lk.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin))
if err != nil { // if err != nil {
// error is returned only if the bkava denom is incorrect, which should never happen here. // // error is returned only if the bkava denom is incorrect, which should never happen here.
panic(err) // panic(err)
} // }
votingPower := sdk.NewDecFromInt(stakedCoins.Amount) // votingPower := sdk.NewDecFromInt(stakedCoins.Amount)
for _, option := range vote.Options { // for _, option := range vote.Options {
subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight)) // subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight))
results[option.Option] = results[option.Option].Add(subPower) // results[option.Option] = results[option.Option].Add(subPower)
} // }
totalVotingPower = totalVotingPower.Add(votingPower) // totalVotingPower = totalVotingPower.Add(votingPower)
} // }
th.gk.DeleteVote(ctx, vote.ProposalId, voter) th.gk.DeleteVote(ctx, vote.ProposalId, voter)
return false return false
@ -154,7 +143,7 @@ func (th TallyHandler) Tally(
totalVotingPower = totalVotingPower.Add(votingPower) totalVotingPower = totalVotingPower.Add(votingPower)
} }
tallyParams := th.gk.GetTallyParams(ctx) tallyParams := th.gk.GetParams(ctx)
tallyResults = govv1.NewTallyResultFromMap(results) tallyResults = govv1.NewTallyResultFromMap(results)
// TODO: Upgrade the spec to cover all of these cases & remove pseudocode. // TODO: Upgrade the spec to cover all of these cases & remove pseudocode.
@ -166,7 +155,7 @@ func (th TallyHandler) Tally(
// If there is not enough quorum of votes, the proposal fails // If there is not enough quorum of votes, the proposal fails
percentVoting := totalVotingPower.Quo(sdk.NewDecFromInt(th.stk.TotalBondedTokens(ctx))) percentVoting := totalVotingPower.Quo(sdk.NewDecFromInt(th.stk.TotalBondedTokens(ctx)))
if percentVoting.LT(sdk.MustNewDecFromStr(tallyParams.Quorum)) { if percentVoting.LT(sdk.MustNewDecFromStr(tallyParams.Quorum)) {
return false, true, tallyResults return false, tallyParams.BurnVoteQuorum, tallyResults
} }
// If no one votes (everyone abstains), proposal fails // If no one votes (everyone abstains), proposal fails
@ -176,7 +165,7 @@ func (th TallyHandler) Tally(
// If more than 1/3 of voters veto, proposal fails // If more than 1/3 of voters veto, proposal fails
if results[govv1.OptionNoWithVeto].Quo(totalVotingPower).GT(sdk.MustNewDecFromStr(tallyParams.VetoThreshold)) { if results[govv1.OptionNoWithVeto].Quo(totalVotingPower).GT(sdk.MustNewDecFromStr(tallyParams.VetoThreshold)) {
return false, true, tallyResults return false, tallyParams.BurnVoteVeto, tallyResults
} }
// If more than 1/2 of non-abstaining voters vote Yes, proposal passes // If more than 1/2 of non-abstaining voters vote Yes, proposal passes
@ -219,38 +208,38 @@ func (th TallyHandler) getAddrBkava(ctx sdk.Context, addr sdk.AccAddress) bkavaB
// addBkavaFromWallet adds all addr balances of bkava in x/bank. // addBkavaFromWallet adds all addr balances of bkava in x/bank.
func (th TallyHandler) addBkavaFromWallet(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { func (th TallyHandler) addBkavaFromWallet(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) {
coins := th.bk.GetAllBalances(ctx, addr) // coins := th.bk.GetAllBalances(ctx, addr)
for _, coin := range coins { // for _, coin := range coins {
if th.lk.IsDerivativeDenom(ctx, coin.Denom) { // if th.lk.IsDerivativeDenom(ctx, coin.Denom) {
bkava.add(coin) // bkava.add(coin)
} // }
} // }
} }
// addBkavaFromSavings adds all addr deposits of bkava in x/savings. // addBkavaFromSavings adds all addr deposits of bkava in x/savings.
func (th TallyHandler) addBkavaFromSavings(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { func (th TallyHandler) addBkavaFromSavings(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) {
deposit, found := th.svk.GetDeposit(ctx, addr) // deposit, found := th.svk.GetDeposit(ctx, addr)
if !found { // if !found {
return // return
} // }
for _, coin := range deposit.Amount { // for _, coin := range deposit.Amount {
if th.lk.IsDerivativeDenom(ctx, coin.Denom) { // if th.lk.IsDerivativeDenom(ctx, coin.Denom) {
bkava.add(coin) // bkava.add(coin)
} // }
} // }
} }
// addBkavaFromEarn adds all addr deposits of bkava in x/earn. // addBkavaFromEarn adds all addr deposits of bkava in x/earn.
func (th TallyHandler) addBkavaFromEarn(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { func (th TallyHandler) addBkavaFromEarn(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) {
shares, found := th.ek.GetVaultAccountShares(ctx, addr) // shares, found := th.ek.GetVaultAccountShares(ctx, addr)
if !found { // if !found {
return // return
} // }
for _, share := range shares { // for _, share := range shares {
if th.lk.IsDerivativeDenom(ctx, share.Denom) { // if th.lk.IsDerivativeDenom(ctx, share.Denom) {
if coin, err := th.ek.ConvertToAssets(ctx, share); err == nil { // if coin, err := th.ek.ConvertToAssets(ctx, share); err == nil {
bkava.add(coin) // bkava.add(coin)
} // }
} // }
} // }
} }

View File

@ -5,6 +5,7 @@ import (
"time" "time"
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
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"
@ -15,10 +16,8 @@ import (
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
earntypes "github.com/kava-labs/kava/x/earn/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
liquidtypes "github.com/kava-labs/kava/x/liquid/types"
) )
// d is an alias for sdk.MustNewDecFromStr // d is an alias for sdk.MustNewDecFromStr
@ -44,12 +43,13 @@ func (suite *tallyHandlerSuite) SetupTest() {
genesisTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) genesisTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC)
suite.ctx = suite.app.NewContext(false, tmproto.Header{Height: 1, Time: genesisTime}) suite.ctx = suite.app.NewContext(false, tmproto.Header{Height: 1, Time: genesisTime})
suite.staking = stakingHelper{suite.app.GetStakingKeeper()} stakingKeeper := *suite.app.GetStakingKeeper()
suite.staking = stakingHelper{stakingKeeper}
suite.staking.setBondDenom(suite.ctx, "ukava") suite.staking.setBondDenom(suite.ctx, "ukava")
suite.tallier = NewTallyHandler( suite.tallier = NewTallyHandler(
suite.app.GetGovKeeper(), suite.app.GetGovKeeper(),
suite.app.GetStakingKeeper(), stakingKeeper,
suite.app.GetSavingsKeeper(), suite.app.GetSavingsKeeper(),
suite.app.GetEarnKeeper(), suite.app.GetEarnKeeper(),
suite.app.GetLiquidKeeper(), suite.app.GetLiquidKeeper(),
@ -215,11 +215,12 @@ func (suite *tallyHandlerSuite) TestTallyOutcomes() {
} }
func (suite *tallyHandlerSuite) setTallyParams(quorum, threshold, veto sdk.Dec) { func (suite *tallyHandlerSuite) setTallyParams(quorum, threshold, veto sdk.Dec) {
suite.app.GetGovKeeper().SetTallyParams(suite.ctx, govv1.TallyParams{ params := suite.app.GetGovKeeper().GetParams(suite.ctx)
Quorum: quorum.String(), params.Quorum = quorum.String()
Threshold: threshold.String(), params.Threshold = threshold.String()
VetoThreshold: veto.String(), params.VetoThreshold = veto.String()
}) params.BurnVoteQuorum = true
suite.app.GetGovKeeper().SetParams(suite.ctx, params)
} }
func (suite *tallyHandlerSuite) voteOnProposal( func (suite *tallyHandlerSuite) voteOnProposal(
@ -240,7 +241,7 @@ func (suite *tallyHandlerSuite) voteOnProposal(
func (suite *tallyHandlerSuite) createProposal() govv1.Proposal { func (suite *tallyHandlerSuite) createProposal() govv1.Proposal {
gk := suite.app.GetGovKeeper() gk := suite.app.GetGovKeeper()
deposit := gk.GetDepositParams(suite.ctx).MinDeposit deposit := gk.GetParams(suite.ctx).MinDeposit
proposer := suite.createAccount(deposit...) proposer := suite.createAccount(deposit...)
msg, err := govv1beta1.NewMsgSubmitProposal( msg, err := govv1beta1.NewMsgSubmitProposal(
@ -250,7 +251,7 @@ func (suite *tallyHandlerSuite) createProposal() govv1.Proposal {
) )
suite.Require().NoError(err) suite.Require().NoError(err)
msgServerv1 := govkeeper.NewMsgServerImpl(gk) msgServerv1 := govkeeper.NewMsgServerImpl(&gk)
govAcct := gk.GetGovernanceAccount(suite.ctx).GetAddress() govAcct := gk.GetGovernanceAccount(suite.ctx).GetAddress()
msgServer := govkeeper.NewLegacyMsgServerImpl(govAcct.String(), msgServerv1) msgServer := govkeeper.NewLegacyMsgServerImpl(govAcct.String(), msgServerv1)
@ -269,39 +270,40 @@ func (suite *tallyHandlerSuite) newBondCoin(amount sdkmath.Int) sdk.Coin {
} }
func (suite *tallyHandlerSuite) allowBKavaEarnDeposits() { func (suite *tallyHandlerSuite) allowBKavaEarnDeposits() {
ek := suite.app.GetEarnKeeper() // ek := suite.app.GetEarnKeeper()
earnParams := ek.GetParams(suite.ctx) // earnParams := ek.GetParams(suite.ctx)
vault := earntypes.NewAllowedVault( // vault := earntypes.NewAllowedVault(
liquidtypes.DefaultDerivativeDenom, // liquidtypes.DefaultDerivativeDenom,
earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, // earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS},
false, // false,
nil, // nil,
) // )
earnParams.AllowedVaults = append(earnParams.AllowedVaults, vault) // earnParams.AllowedVaults = append(earnParams.AllowedVaults, vault)
ek.SetParams(suite.ctx, earnParams) // ek.SetParams(suite.ctx, earnParams)
sk := suite.app.GetSavingsKeeper() // sk := suite.app.GetSavingsKeeper()
savingsParams := sk.GetParams(suite.ctx) // savingsParams := sk.GetParams(suite.ctx)
savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, liquidtypes.DefaultDerivativeDenom) // savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, liquidtypes.DefaultDerivativeDenom)
sk.SetParams(suite.ctx, savingsParams) // sk.SetParams(suite.ctx, savingsParams)
} }
func (suite *tallyHandlerSuite) earnDeposit(owner sdk.AccAddress, derivative sdk.Coin) { func (suite *tallyHandlerSuite) earnDeposit(owner sdk.AccAddress, derivative sdk.Coin) {
ek := suite.app.GetEarnKeeper() // ek := suite.app.GetEarnKeeper()
err := ek.Deposit(suite.ctx, owner, derivative, earntypes.STRATEGY_TYPE_SAVINGS) // err := ek.Deposit(suite.ctx, owner, derivative, earntypes.STRATEGY_TYPE_SAVINGS)
suite.Require().NoError(err) // suite.Require().NoError(err)
} }
func (suite *tallyHandlerSuite) mintDerivative(owner sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) sdk.Coin { func (suite *tallyHandlerSuite) mintDerivative(owner sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) sdk.Coin {
lk := suite.app.GetLiquidKeeper() // lk := suite.app.GetLiquidKeeper()
minted, err := lk.MintDerivative(suite.ctx, owner, validator, suite.newBondCoin(amount)) // minted, err := lk.MintDerivative(suite.ctx, owner, validator, suite.newBondCoin(amount))
suite.Require().NoError(err) // suite.Require().NoError(err)
return minted // return minted
return sdk.NewCoin("ukava", amount)
} }
func (suite *tallyHandlerSuite) delegateToNewBondedValidator(delegator sdk.AccAddress, amount sdkmath.Int) stakingtypes.ValidatorI { func (suite *tallyHandlerSuite) delegateToNewBondedValidator(delegator sdk.AccAddress, amount sdkmath.Int) stakingtypes.ValidatorI {
@ -369,7 +371,7 @@ func (h stakingHelper) createUnbondedValidator(ctx sdk.Context, address sdk.ValA
return nil, err return nil, err
} }
msgServer := stakingkeeper.NewMsgServerImpl(h.keeper) msgServer := stakingkeeper.NewMsgServerImpl(&h.keeper)
_, err = msgServer.CreateValidator(sdk.WrapSDKContext(ctx), msg) _, err = msgServer.CreateValidator(sdk.WrapSDKContext(ctx), msg)
if err != nil { if err != nil {
return nil, err return nil, err
@ -389,7 +391,7 @@ func (h stakingHelper) delegate(ctx sdk.Context, delegator sdk.AccAddress, valid
h.newBondCoin(ctx, amount), h.newBondCoin(ctx, amount),
) )
msgServer := stakingkeeper.NewMsgServerImpl(h.keeper) msgServer := stakingkeeper.NewMsgServerImpl(&h.keeper)
_, err := msgServer.Delegate(sdk.WrapSDKContext(ctx), msg) _, err := msgServer.Delegate(sdk.WrapSDKContext(ctx), msg)
if err != nil { if err != nil {
return sdk.Dec{}, err return sdk.Dec{}, err

View File

@ -9,6 +9,11 @@ import (
"time" "time"
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
tmdb "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/log"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/baseapp"
"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"
@ -35,36 +40,22 @@ import (
evmkeeper "github.com/evmos/ethermint/x/evm/keeper" evmkeeper "github.com/evmos/ethermint/x/evm/keeper"
feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtypes "github.com/tendermint/tendermint/types"
tmdb "github.com/tendermint/tm-db"
auctionkeeper "github.com/kava-labs/kava/x/auction/keeper" "github.com/0glabs/0g-chain/chaincfg"
bep3keeper "github.com/kava-labs/kava/x/bep3/keeper" bep3keeper "github.com/0glabs/0g-chain/x/bep3/keeper"
cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper" committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper"
committeekeeper "github.com/kava-labs/kava/x/committee/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
communitykeeper "github.com/kava-labs/kava/x/community/keeper" issuancekeeper "github.com/0glabs/0g-chain/x/issuance/keeper"
earnkeeper "github.com/kava-labs/kava/x/earn/keeper" pricefeedkeeper "github.com/0glabs/0g-chain/x/pricefeed/keeper"
evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper"
hardkeeper "github.com/kava-labs/kava/x/hard/keeper"
incentivekeeper "github.com/kava-labs/kava/x/incentive/keeper"
issuancekeeper "github.com/kava-labs/kava/x/issuance/keeper"
kavadistkeeper "github.com/kava-labs/kava/x/kavadist/keeper"
liquidkeeper "github.com/kava-labs/kava/x/liquid/keeper"
pricefeedkeeper "github.com/kava-labs/kava/x/pricefeed/keeper"
routerkeeper "github.com/kava-labs/kava/x/router/keeper"
savingskeeper "github.com/kava-labs/kava/x/savings/keeper"
swapkeeper "github.com/kava-labs/kava/x/swap/keeper"
) )
var ( var (
emptyTime time.Time emptyTime time.Time
testChainID = "kavatest_1-1"
defaultInitialHeight int64 = 1 defaultInitialHeight int64 = 1
) )
const TestChainId = "kavatest_2221-1"
// TestApp is a simple wrapper around an App. It exposes internal keepers for use in integration tests. // TestApp is a simple wrapper around an App. It exposes internal keepers for use in integration tests.
// This file also contains test helpers. Ideally they would be in separate package. // This file also contains test helpers. Ideally they would be in separate package.
// Basic Usage: // Basic Usage:
@ -88,7 +79,7 @@ type TestApp struct {
// //
// Note, it also sets the sdk config with the app's address prefix, coin type, etc. // Note, it also sets the sdk config with the app's address prefix, coin type, etc.
func NewTestApp() TestApp { func NewTestApp() TestApp {
SetSDKConfig() chaincfg.SetSDKConfig()
return NewTestAppFromSealed() return NewTestAppFromSealed()
} }
@ -99,7 +90,10 @@ func NewTestAppFromSealed() TestApp {
encCfg := MakeEncodingConfig() encCfg := MakeEncodingConfig()
app := NewApp(log.NewNopLogger(), db, DefaultNodeHome, nil, encCfg, DefaultOptions) app := NewApp(
log.NewNopLogger(), db, chaincfg.DefaultNodeHome, nil,
encCfg, DefaultOptions, baseapp.SetChainID(TestChainId),
)
return TestApp{App: *app} return TestApp{App: *app}
} }
@ -107,30 +101,19 @@ func NewTestAppFromSealed() TestApp {
func (tApp TestApp) GetAccountKeeper() authkeeper.AccountKeeper { return tApp.accountKeeper } func (tApp TestApp) GetAccountKeeper() authkeeper.AccountKeeper { return tApp.accountKeeper }
func (tApp TestApp) GetBankKeeper() bankkeeper.Keeper { return tApp.bankKeeper } func (tApp TestApp) GetBankKeeper() bankkeeper.Keeper { return tApp.bankKeeper }
func (tApp TestApp) GetMintKeeper() mintkeeper.Keeper { return tApp.mintKeeper } func (tApp TestApp) GetMintKeeper() mintkeeper.Keeper { return tApp.mintKeeper }
func (tApp TestApp) GetStakingKeeper() stakingkeeper.Keeper { return tApp.stakingKeeper } func (tApp TestApp) GetStakingKeeper() *stakingkeeper.Keeper { return tApp.stakingKeeper }
func (tApp TestApp) GetSlashingKeeper() slashingkeeper.Keeper { return tApp.slashingKeeper } func (tApp TestApp) GetSlashingKeeper() slashingkeeper.Keeper { return tApp.slashingKeeper }
func (tApp TestApp) GetDistrKeeper() distkeeper.Keeper { return tApp.distrKeeper } func (tApp TestApp) GetDistrKeeper() distkeeper.Keeper { return tApp.distrKeeper }
func (tApp TestApp) GetGovKeeper() govkeeper.Keeper { return tApp.govKeeper } func (tApp TestApp) GetGovKeeper() govkeeper.Keeper { return tApp.govKeeper }
func (tApp TestApp) GetCrisisKeeper() crisiskeeper.Keeper { return tApp.crisisKeeper } func (tApp TestApp) GetCrisisKeeper() crisiskeeper.Keeper { return tApp.crisisKeeper }
func (tApp TestApp) GetParamsKeeper() paramskeeper.Keeper { return tApp.paramsKeeper } func (tApp TestApp) GetParamsKeeper() paramskeeper.Keeper { return tApp.paramsKeeper }
func (tApp TestApp) GetKavadistKeeper() kavadistkeeper.Keeper { return tApp.kavadistKeeper }
func (tApp TestApp) GetAuctionKeeper() auctionkeeper.Keeper { return tApp.auctionKeeper }
func (tApp TestApp) GetIssuanceKeeper() issuancekeeper.Keeper { return tApp.issuanceKeeper } func (tApp TestApp) GetIssuanceKeeper() issuancekeeper.Keeper { return tApp.issuanceKeeper }
func (tApp TestApp) GetBep3Keeper() bep3keeper.Keeper { return tApp.bep3Keeper } func (tApp TestApp) GetBep3Keeper() bep3keeper.Keeper { return tApp.bep3Keeper }
func (tApp TestApp) GetPriceFeedKeeper() pricefeedkeeper.Keeper { return tApp.pricefeedKeeper } func (tApp TestApp) GetPriceFeedKeeper() pricefeedkeeper.Keeper { return tApp.pricefeedKeeper }
func (tApp TestApp) GetSwapKeeper() swapkeeper.Keeper { return tApp.swapKeeper }
func (tApp TestApp) GetCDPKeeper() cdpkeeper.Keeper { return tApp.cdpKeeper }
func (tApp TestApp) GetHardKeeper() hardkeeper.Keeper { return tApp.hardKeeper }
func (tApp TestApp) GetCommitteeKeeper() committeekeeper.Keeper { return tApp.committeeKeeper } func (tApp TestApp) GetCommitteeKeeper() committeekeeper.Keeper { return tApp.committeeKeeper }
func (tApp TestApp) GetIncentiveKeeper() incentivekeeper.Keeper { return tApp.incentiveKeeper }
func (tApp TestApp) GetEvmutilKeeper() evmutilkeeper.Keeper { return tApp.evmutilKeeper } func (tApp TestApp) GetEvmutilKeeper() evmutilkeeper.Keeper { return tApp.evmutilKeeper }
func (tApp TestApp) GetEvmKeeper() *evmkeeper.Keeper { return tApp.evmKeeper } func (tApp TestApp) GetEvmKeeper() *evmkeeper.Keeper { return tApp.evmKeeper }
func (tApp TestApp) GetSavingsKeeper() savingskeeper.Keeper { return tApp.savingsKeeper }
func (tApp TestApp) GetFeeMarketKeeper() feemarketkeeper.Keeper { return tApp.feeMarketKeeper } func (tApp TestApp) GetFeeMarketKeeper() feemarketkeeper.Keeper { return tApp.feeMarketKeeper }
func (tApp TestApp) GetLiquidKeeper() liquidkeeper.Keeper { return tApp.liquidKeeper }
func (tApp TestApp) GetEarnKeeper() earnkeeper.Keeper { return tApp.earnKeeper }
func (tApp TestApp) GetRouterKeeper() routerkeeper.Keeper { return tApp.routerKeeper }
func (tApp TestApp) GetCommunityKeeper() communitykeeper.Keeper { return tApp.communityKeeper }
func (tApp TestApp) GetKVStoreKey(key string) *storetypes.KVStoreKey { func (tApp TestApp) GetKVStoreKey(key string) *storetypes.KVStoreKey {
return tApp.keys[key] return tApp.keys[key]
@ -170,7 +153,7 @@ func GenesisStateWithSingleValidator(
balances := []banktypes.Balance{ balances := []banktypes.Balance{
{ {
Address: acc.GetAddress().String(), Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100000000000000))), Coins: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100000000000000)),
}, },
} }
@ -233,7 +216,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 = "ukava" currentStakingGenesis.Params.BondDenom = chaincfg.GasDenom // TODO:
stakingGenesis := stakingtypes.NewGenesisState( stakingGenesis := stakingtypes.NewGenesisState(
currentStakingGenesis.Params, currentStakingGenesis.Params,
@ -253,13 +236,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("ukava", 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("ukava", bondAmt)}, Coins: sdk.Coins{chaincfg.MakeCoinForGasDenom(bondAmt)},
}) })
bankGenesis := banktypes.NewGenesisState( bankGenesis := banktypes.NewGenesisState(
@ -267,6 +250,7 @@ func genesisStateWithValSet(
balances, balances,
totalSupply, totalSupply,
currentBankGenesis.DenomMetadata, currentBankGenesis.DenomMetadata,
currentBankGenesis.SendEnabled,
) )
// set genesis state // set genesis state
@ -280,13 +264,13 @@ func genesisStateWithValSet(
// InitializeFromGenesisStates calls InitChain on the app using the provided genesis states. // InitializeFromGenesisStates calls InitChain on the app using the provided genesis states.
// If any module genesis states are missing, defaults are used. // If any module genesis states are missing, defaults are used.
func (tApp TestApp) InitializeFromGenesisStates(genesisStates ...GenesisState) TestApp { func (tApp TestApp) InitializeFromGenesisStates(genesisStates ...GenesisState) TestApp {
return tApp.InitializeFromGenesisStatesWithTimeAndChainIDAndHeight(emptyTime, testChainID, defaultInitialHeight, true, genesisStates...) return tApp.InitializeFromGenesisStatesWithTimeAndChainIDAndHeight(emptyTime, TestChainId, defaultInitialHeight, true, genesisStates...)
} }
// InitializeFromGenesisStatesWithTime calls InitChain on the app using the provided genesis states and time. // InitializeFromGenesisStatesWithTime calls InitChain on the app using the provided genesis states and time.
// If any module genesis states are missing, defaults are used. // If any module genesis states are missing, defaults are used.
func (tApp TestApp) InitializeFromGenesisStatesWithTime(genTime time.Time, genesisStates ...GenesisState) TestApp { func (tApp TestApp) InitializeFromGenesisStatesWithTime(genTime time.Time, genesisStates ...GenesisState) TestApp {
return tApp.InitializeFromGenesisStatesWithTimeAndChainIDAndHeight(genTime, testChainID, defaultInitialHeight, true, genesisStates...) return tApp.InitializeFromGenesisStatesWithTimeAndChainIDAndHeight(genTime, TestChainId, defaultInitialHeight, true, genesisStates...)
} }
// InitializeFromGenesisStatesWithTimeAndChainID calls InitChain on the app using the provided genesis states, time, and chain id. // InitializeFromGenesisStatesWithTimeAndChainID calls InitChain on the app using the provided genesis states, time, and chain id.
@ -343,8 +327,8 @@ func (tApp TestApp) InitializeFromGenesisStatesWithTimeAndChainIDAndHeight(
AppStateBytes: stateBytes, AppStateBytes: stateBytes,
ChainId: chainID, ChainId: chainID,
// Set consensus params, which is needed by x/feemarket // Set consensus params, which is needed by x/feemarket
ConsensusParams: &abci.ConsensusParams{ ConsensusParams: &tmproto.ConsensusParams{
Block: &abci.BlockParams{ Block: &tmproto.BlockParams{
MaxBytes: 200000, MaxBytes: 200000,
MaxGas: 20000000, MaxGas: 20000000,
}, },

View File

@ -1,3 +1,258 @@
package app package app
func (app App) RegisterUpgradeHandlers() {} import (
"fmt"
sdkmath "cosmossdk.io/math"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
)
const (
UpgradeName_Mainnet = "v0.25.0"
UpgradeName_Testnet = "v0.25.0-alpha.0"
UpgradeName_E2ETest = "v0.25.0-testing"
)
var (
// KAVA to ukava - 6 decimals
kavaConversionFactor = sdk.NewInt(1000_000)
secondsPerYear = sdk.NewInt(365 * 24 * 60 * 60)
// 10 Million KAVA per year in staking rewards, inflation disable time 2024-01-01T00:00:00 UTC
// CommunityParams_Mainnet = communitytypes.NewParams(
// time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
// // before switchover
// sdkmath.LegacyZeroDec(),
// // after switchover - 10M KAVA to ukava per year / seconds per year
// sdkmath.LegacyNewDec(10_000_000).
// MulInt(kavaConversionFactor).
// QuoInt(secondsPerYear),
// )
// Testnet -- 15 Trillion KAVA per year in staking rewards, inflation disable time 2023-11-16T00:00:00 UTC
// CommunityParams_Testnet = communitytypes.NewParams(
// time.Date(2023, 11, 16, 0, 0, 0, 0, time.UTC),
// // before switchover
// sdkmath.LegacyZeroDec(),
// // after switchover
// sdkmath.LegacyNewDec(15_000_000).
// MulInt64(1_000_000). // 15M * 1M = 15T
// MulInt(kavaConversionFactor).
// QuoInt(secondsPerYear),
// )
// CommunityParams_E2E = communitytypes.NewParams(
// time.Now().Add(10*time.Second).UTC(), // relative time for testing
// sdkmath.LegacyNewDec(0), // stakingRewardsPerSecond
// sdkmath.LegacyNewDec(1000), // upgradeTimeSetstakingRewardsPerSecond
// )
// ValidatorMinimumCommission is the new 5% minimum commission rate for validators
ValidatorMinimumCommission = sdk.NewDecWithPrec(5, 2)
)
// RegisterUpgradeHandlers registers the upgrade handlers for the app.
func (app App) RegisterUpgradeHandlers() {
// app.upgradeKeeper.SetUpgradeHandler(
// UpgradeName_Mainnet,
// upgradeHandler(app, UpgradeName_Mainnet, CommunityParams_Mainnet),
// )
// app.upgradeKeeper.SetUpgradeHandler(
// UpgradeName_Testnet,
// upgradeHandler(app, UpgradeName_Testnet, CommunityParams_Testnet),
// )
// app.upgradeKeeper.SetUpgradeHandler(
// UpgradeName_E2ETest,
// upgradeHandler(app, UpgradeName_Testnet, CommunityParams_E2E),
// )
upgradeInfo, err := app.upgradeKeeper.ReadUpgradeInfoFromDisk()
if err != nil {
panic(err)
}
doUpgrade := upgradeInfo.Name == UpgradeName_Mainnet ||
upgradeInfo.Name == UpgradeName_Testnet ||
upgradeInfo.Name == UpgradeName_E2ETest
if doUpgrade && !app.upgradeKeeper.IsSkipHeight(upgradeInfo.Height) {
storeUpgrades := storetypes.StoreUpgrades{
Added: []string{
// x/community added store
// communitytypes.ModuleName,
},
}
// configure store loader that checks if version == upgradeHeight and applies store upgrades
app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades))
}
}
// upgradeHandler returns an UpgradeHandler for the given upgrade parameters.
func upgradeHandler(
app App,
name string,
// communityParams communitytypes.Params,
) upgradetypes.UpgradeHandler {
return func(
ctx sdk.Context,
plan upgradetypes.Plan,
fromVM module.VersionMap,
) (module.VersionMap, error) {
app.Logger().Info(fmt.Sprintf("running %s upgrade handler", name))
toVM, err := app.mm.RunMigrations(ctx, app.configurator, fromVM)
if err != nil {
return toVM, err
}
//
// Staking validator minimum commission
//
UpdateValidatorMinimumCommission(ctx, app)
//
// Community Params
//
// app.communityKeeper.SetParams(ctx, communityParams)
// app.Logger().Info(
// "initialized x/community params",
// "UpgradeTimeDisableInflation", communityParams.UpgradeTimeDisableInflation,
// "StakingRewardsPerSecond", communityParams.StakingRewardsPerSecond,
// "UpgradeTimeSetStakingRewardsPerSecond", communityParams.UpgradeTimeSetStakingRewardsPerSecond,
// )
//
// Kavadist gov grant
//
// msgGrant, err := authz.NewMsgGrant(
// app.accountKeeper.GetModuleAddress(kavadisttypes.ModuleName), // granter
// app.accountKeeper.GetModuleAddress(govtypes.ModuleName), // grantee
// authz.NewGenericAuthorization(sdk.MsgTypeURL(&banktypes.MsgSend{})), // authorization
// nil, // expiration
// )
// if err != nil {
// return toVM, err
// }
// _, err = app.authzKeeper.Grant(ctx, msgGrant)
// if err != nil {
// return toVM, err
// }
// app.Logger().Info("created gov grant for kavadist funds")
//
// Gov Quorum
//
govTallyParams := app.govKeeper.GetTallyParams(ctx)
oldQuorum := govTallyParams.Quorum
govTallyParams.Quorum = sdkmath.LegacyMustNewDecFromStr("0.2").String()
app.govKeeper.SetTallyParams(ctx, govTallyParams)
app.Logger().Info(fmt.Sprintf("updated tally quorum from %s to %s", oldQuorum, govTallyParams.Quorum))
//
// Incentive Params
//
UpdateIncentiveParams(ctx, app)
return toVM, nil
}
}
// UpdateValidatorMinimumCommission updates the commission rate for all
// validators to be at least the new min commission rate, and sets the minimum
// commission rate in the staking params.
func UpdateValidatorMinimumCommission(
ctx sdk.Context,
app App,
) {
resultCount := make(map[stakingtypes.BondStatus]int)
// Iterate over *all* validators including inactive
app.stakingKeeper.IterateValidators(
ctx,
func(index int64, validator stakingtypes.ValidatorI) (stop bool) {
// Skip if validator commission is already >= 5%
if validator.GetCommission().GTE(ValidatorMinimumCommission) {
return false
}
val, ok := validator.(stakingtypes.Validator)
if !ok {
panic("expected stakingtypes.Validator")
}
// Set minimum commission rate to 5%, when commission is < 5%
val.Commission.Rate = ValidatorMinimumCommission
val.Commission.UpdateTime = ctx.BlockTime()
// Update MaxRate if necessary
if val.Commission.MaxRate.LT(ValidatorMinimumCommission) {
val.Commission.MaxRate = ValidatorMinimumCommission
}
if err := app.stakingKeeper.BeforeValidatorModified(ctx, val.GetOperator()); err != nil {
panic(fmt.Sprintf("failed to call BeforeValidatorModified: %s", err))
}
app.stakingKeeper.SetValidator(ctx, val)
// Keep track of counts just for logging purposes
switch val.GetStatus() {
case stakingtypes.Bonded:
resultCount[stakingtypes.Bonded]++
case stakingtypes.Unbonded:
resultCount[stakingtypes.Unbonded]++
case stakingtypes.Unbonding:
resultCount[stakingtypes.Unbonding]++
}
return false
},
)
app.Logger().Info(
"updated validator minimum commission rate for all existing validators",
stakingtypes.BondStatusBonded, resultCount[stakingtypes.Bonded],
stakingtypes.BondStatusUnbonded, resultCount[stakingtypes.Unbonded],
stakingtypes.BondStatusUnbonding, resultCount[stakingtypes.Unbonding],
)
stakingParams := app.stakingKeeper.GetParams(ctx)
stakingParams.MinCommissionRate = ValidatorMinimumCommission
app.stakingKeeper.SetParams(ctx, stakingParams)
app.Logger().Info(
"updated x/staking params minimum commission rate",
"MinCommissionRate", stakingParams.MinCommissionRate,
)
}
// UpdateIncentiveParams modifies the earn rewards period for bkava to be 600K KAVA per year.
func UpdateIncentiveParams(
ctx sdk.Context,
app App,
) {
// incentiveParams := app.incentiveKeeper.GetParams(ctx)
// bkava annualized rewards: 600K KAVA
// newAmount := sdkmath.LegacyNewDec(600_000).
// MulInt(kavaConversionFactor).
// QuoInt(secondsPerYear).
// TruncateInt()
// for i := range incentiveParams.EarnRewardPeriods {
// if incentiveParams.EarnRewardPeriods[i].CollateralType != "bkava" {
// continue
// }
// // Update rewards per second via index
// incentiveParams.EarnRewardPeriods[i].RewardsPerSecond = sdk.NewCoins(
// sdk.NewCoin("ukava", newAmount),
// )
// }
// app.incentiveKeeper.SetParams(ctx, incentiveParams)
}

239
app/upgrades_test.go Normal file
View File

@ -0,0 +1,239 @@
package app_test
import (
"testing"
"time"
"github.com/0glabs/0g-chain/app"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/evmos/ethermint/crypto/ethsecp256k1"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
)
// func TestUpgradeCommunityParams_Mainnet(t *testing.T) {
// require.Equal(
// t,
// sdkmath.LegacyZeroDec().String(),
// app.CommunityParams_Mainnet.StakingRewardsPerSecond.String(),
// )
// require.Equal(
// t,
// // Manually confirmed
// "317097.919837645865043125",
// app.CommunityParams_Mainnet.UpgradeTimeSetStakingRewardsPerSecond.String(),
// "mainnet kava per second should be correct",
// )
// }
// func TestUpgradeCommunityParams_Testnet(t *testing.T) {
// require.Equal(
// t,
// sdkmath.LegacyZeroDec().String(),
// app.CommunityParams_Testnet.StakingRewardsPerSecond.String(),
// )
// require.Equal(
// t,
// // Manually confirmed
// "475646879756.468797564687975646",
// app.CommunityParams_Testnet.UpgradeTimeSetStakingRewardsPerSecond.String(),
// "testnet kava per second should be correct",
// )
// }
func TestUpdateValidatorMinimumCommission(t *testing.T) {
tApp := app.NewTestApp()
tApp.InitializeFromGenesisStates()
ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()})
sk := tApp.GetStakingKeeper()
stakingParams := sk.GetParams(ctx)
stakingParams.MinCommissionRate = sdk.ZeroDec()
sk.SetParams(ctx, stakingParams)
// Set some validators with varying commission rates
vals := []struct {
name string
operatorAddr sdk.ValAddress
consPriv *ethsecp256k1.PrivKey
commissionRateMin sdk.Dec
commissionRateMax sdk.Dec
shouldBeUpdated bool
}{
{
name: "zero commission rate",
operatorAddr: sdk.ValAddress("val0"),
consPriv: generateConsKey(t),
commissionRateMin: sdk.ZeroDec(),
commissionRateMax: sdk.ZeroDec(),
shouldBeUpdated: true,
},
{
name: "0.01 commission rate",
operatorAddr: sdk.ValAddress("val1"),
consPriv: generateConsKey(t),
commissionRateMin: sdk.MustNewDecFromStr("0.01"),
commissionRateMax: sdk.MustNewDecFromStr("0.01"),
shouldBeUpdated: true,
},
{
name: "0.05 commission rate",
operatorAddr: sdk.ValAddress("val2"),
consPriv: generateConsKey(t),
commissionRateMin: sdk.MustNewDecFromStr("0.05"),
commissionRateMax: sdk.MustNewDecFromStr("0.05"),
shouldBeUpdated: false,
},
{
name: "0.06 commission rate",
operatorAddr: sdk.ValAddress("val3"),
consPriv: generateConsKey(t),
commissionRateMin: sdk.MustNewDecFromStr("0.06"),
commissionRateMax: sdk.MustNewDecFromStr("0.06"),
shouldBeUpdated: false,
},
{
name: "0.5 commission rate",
operatorAddr: sdk.ValAddress("val4"),
consPriv: generateConsKey(t),
commissionRateMin: sdk.MustNewDecFromStr("0.5"),
commissionRateMax: sdk.MustNewDecFromStr("0.5"),
shouldBeUpdated: false,
},
}
for _, v := range vals {
val, err := stakingtypes.NewValidator(
v.operatorAddr,
v.consPriv.PubKey(),
stakingtypes.Description{},
)
require.NoError(t, err)
val.Commission.Rate = v.commissionRateMin
val.Commission.MaxRate = v.commissionRateMax
err = sk.SetValidatorByConsAddr(ctx, val)
require.NoError(t, err)
sk.SetValidator(ctx, val)
}
require.NotPanics(
t, func() {
app.UpdateValidatorMinimumCommission(ctx, tApp.App)
},
)
stakingParamsAfter := sk.GetParams(ctx)
require.Equal(t, stakingParamsAfter.MinCommissionRate, app.ValidatorMinimumCommission)
// Check that all validators have a commission rate >= 5%
for _, val := range vals {
t.Run(val.name, func(t *testing.T) {
validator, found := sk.GetValidator(ctx, val.operatorAddr)
require.True(t, found, "validator should be found")
require.True(
t,
validator.GetCommission().GTE(app.ValidatorMinimumCommission),
"commission rate should be >= 5%",
)
require.True(
t,
validator.Commission.MaxRate.GTE(app.ValidatorMinimumCommission),
"commission rate max should be >= 5%, got %s",
validator.Commission.MaxRate,
)
if val.shouldBeUpdated {
require.Equal(
t,
ctx.BlockTime(),
validator.Commission.UpdateTime,
"commission update time should be set to block time",
)
} else {
require.Equal(
t,
time.Unix(0, 0).UTC(),
validator.Commission.UpdateTime,
"commission update time should not be changed -- default value is 0",
)
}
})
}
}
// func TestUpdateIncentiveParams(t *testing.T) {
// tApp := app.NewTestApp()
// tApp.InitializeFromGenesisStates()
// ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()})
// ik := tApp.GetIncentiveKeeper()
// params := ik.GetParams(ctx)
// startPeriod := time.Date(2021, 10, 26, 15, 0, 0, 0, time.UTC)
// endPeriod := time.Date(2022, 10, 26, 15, 0, 0, 0, time.UTC)
// params.EarnRewardPeriods = incentivetypes.MultiRewardPeriods{
// incentivetypes.NewMultiRewardPeriod(
// true,
// "bkava",
// startPeriod,
// endPeriod,
// sdk.NewCoins(
// sdk.NewCoin("ukava", sdk.NewInt(159459)),
// ),
// ),
// }
// ik.SetParams(ctx, params)
// beforeParams := ik.GetParams(ctx)
// require.Equal(t, params, beforeParams, "initial incentive params should be set")
// // -- UPGRADE
// app.UpdateIncentiveParams(ctx, tApp.App)
// // -- After
// afterParams := ik.GetParams(ctx)
// require.Len(
// t,
// afterParams.EarnRewardPeriods[0].RewardsPerSecond,
// 1,
// "bkava earn reward period should only contain 1 coin",
// )
// require.Equal(
// t,
// // Manual calculation of
// // 600,000 * 1000,000 / (365 * 24 * 60 * 60)
// sdk.NewCoin("ukava", sdkmath.NewInt(19025)),
// afterParams.EarnRewardPeriods[0].RewardsPerSecond[0],
// "bkava earn reward period should be updated",
// )
// // Check that other params are not changed
// afterParams.EarnRewardPeriods[0].RewardsPerSecond[0] = beforeParams.EarnRewardPeriods[0].RewardsPerSecond[0]
// require.Equal(
// t,
// beforeParams,
// afterParams,
// "other param values should not be changed",
// )
// }
func generateConsKey(
t *testing.T,
) *ethsecp256k1.PrivKey {
t.Helper()
key, err := ethsecp256k1.GenerateKey()
require.NoError(t, err)
return key
}

View File

@ -28,9 +28,9 @@ DIRS := $(BUILD_CACHE_DIR) $(BIN_DIR)
### Tool Versions ### ### Tool Versions ###
################################################################################ ################################################################################
GO_BIN ?= go GO_BIN ?= go
PROTOC_VERSION ?= v21.9 PROTOC_VERSION ?= v25.1
BUF_VERSION ?= v1.9.0 BUF_VERSION ?= v1.28.1
PROTOC_GEN_GOCOSMOS_VERSION ?= v0.3.1 PROTOC_GEN_GOCOSMOS_VERSION ?= $(shell $(GO_BIN) list -m -f '{{.Version}}' github.com/cosmos/gogoproto)
PROTOC_GEN_GRPC_GATEWAY_VERSION ?= $(shell $(GO_BIN) list -m github.com/grpc-ecosystem/grpc-gateway| sed 's:.* ::') PROTOC_GEN_GRPC_GATEWAY_VERSION ?= $(shell $(GO_BIN) list -m github.com/grpc-ecosystem/grpc-gateway| sed 's:.* ::')
PROTOC_GEN_DOC_VERSION ?= v1.5.1 PROTOC_GEN_DOC_VERSION ?= v1.5.1
SWAGGER_COMBINE_VERSION ?= v1.4.0 SWAGGER_COMBINE_VERSION ?= v1.4.0
@ -68,7 +68,7 @@ $(PROTOC_VERSION_FILE):
mkdir -p protoc && cd protoc; \ mkdir -p protoc && cd protoc; \
curl -sOL $(PROTOC_DOWNLOAD_URL); \ curl -sOL $(PROTOC_DOWNLOAD_URL); \
unzip -q $(PROTOC_ARCHIVE_NAME) bin/protoc unzip -q $(PROTOC_ARCHIVE_NAME) bin/protoc
@cp $(BUILD_CACHE_DIR)/protoc/bin/protoc $(BIN_DIR)/protoc @cp -f $(BUILD_CACHE_DIR)/protoc/bin/protoc $(BIN_DIR)/protoc
@rm -rf $(BUILD_CACHE_DIR)/protoc @rm -rf $(BUILD_CACHE_DIR)/protoc
PROTOC := $(BIN_DIR)/protoc PROTOC := $(BIN_DIR)/protoc
@ -93,7 +93,7 @@ $(BUF_VERSION_FILE):
mkdir -p buf && cd buf; \ mkdir -p buf && cd buf; \
curl -sOL $(BUF_DOWNLOAD_URL); \ curl -sOL $(BUF_DOWNLOAD_URL); \
tar -xzf $(BUF_ARCHIVE_NAME) buf/bin/buf tar -xzf $(BUF_ARCHIVE_NAME) buf/bin/buf
@cp $(BUILD_CACHE_DIR)/buf/buf/bin/buf $(BIN_DIR)/buf @cp -f $(BUILD_CACHE_DIR)/buf/buf/bin/buf $(BIN_DIR)/buf
@rm -rf $(BUILD_CACHE_DIR)/buf @rm -rf $(BUILD_CACHE_DIR)/buf
BUF := $(BIN_DIR)/buf BUF := $(BIN_DIR)/buf
@ -113,8 +113,8 @@ $(PROTOC_GEN_GOCOSMOS_VERSION_FILE):
@touch $(PROTOC_GEN_GOCOSMOS_VERSION_FILE) @touch $(PROTOC_GEN_GOCOSMOS_VERSION_FILE)
@cd $(BUILD_CACHE_DIR); \ @cd $(BUILD_CACHE_DIR); \
mkdir -p protoc-gen-gocosmos && cd protoc-gen-gocosmos; \ mkdir -p protoc-gen-gocosmos && cd protoc-gen-gocosmos; \
git clone -q https://github.com/regen-network/cosmos-proto.git; \ git clone -q https://github.com/cosmos/gogoproto.git; \
cd cosmos-proto; \ cd gogoproto; \
git checkout -q $(PROTOC_GEN_GOCOSMOS_VERSION); \ git checkout -q $(PROTOC_GEN_GOCOSMOS_VERSION); \
GOBIN=$(ROOT_DIR)/$(BIN_DIR) $(GO_BIN) install ./protoc-gen-gocosmos GOBIN=$(ROOT_DIR)/$(BIN_DIR) $(GO_BIN) install ./protoc-gen-gocosmos
@rm -rf $(BUILD_CACHE_DIR)/protoc-gen-gocosmos @rm -rf $(BUILD_CACHE_DIR)/protoc-gen-gocosmos
@ -185,7 +185,7 @@ $(PROTOC_GEN_DOC_VERSION_FILE):
mkdir -p protoc-gen-doc && cd protoc-gen-doc; \ mkdir -p protoc-gen-doc && cd protoc-gen-doc; \
curl -sOL $(PROTOC_GEN_DOC_DOWNLOAD_URL); \ curl -sOL $(PROTOC_GEN_DOC_DOWNLOAD_URL); \
tar -xzf $(PROTOC_GEN_DOC_ARCHIVE_NAME) protoc-gen-doc tar -xzf $(PROTOC_GEN_DOC_ARCHIVE_NAME) protoc-gen-doc
@cp $(BUILD_CACHE_DIR)/protoc-gen-doc/protoc-gen-doc $(BIN_DIR)/protoc-gen-doc @cp -f $(BUILD_CACHE_DIR)/protoc-gen-doc/protoc-gen-doc $(BIN_DIR)/protoc-gen-doc
@rm -rf $(BUILD_CACHE_DIR)/protoc-gen-doc @rm -rf $(BUILD_CACHE_DIR)/protoc-gen-doc
PROTOC_GEN_DOC := $(BIN_DIR)/protoc-gen-doc PROTOC_GEN_DOC := $(BIN_DIR)/protoc-gen-doc

View File

@ -14,13 +14,23 @@ PROTOBUF_ANY_DOWNLOAD_URL = https://raw.githubusercontent.com/protocolbuffers/pr
# #
# Proto dependencies under go.mod # Proto dependencies under go.mod
# #
GOGO_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/gogo/protobuf) GOGO_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cosmos/gogoproto)
TENDERMINT_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/tendermint/tendermint) TENDERMINT_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cometbft/cometbft)
COSMOS_PROTO_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cosmos/cosmos-proto) COSMOS_PROTO_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cosmos/cosmos-proto)
COSMOS_SDK_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cosmos/cosmos-sdk) COSMOS_SDK_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cosmos/cosmos-sdk)
IBC_GO_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cosmos/ibc-go/v6) IBC_GO_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/cosmos/ibc-go/v7)
ETHERMINT_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/evmos/ethermint) ETHERMINT_PATH := $(shell $(GO_BIN) list -m -f '{{.Dir}}' github.com/evmos/ethermint)
#
# ICS23 Proof Proto
#
ICS23_VERSION := $(shell $(GO_BIN) list -m -f '{{.Version}}' github.com/cosmos/ics23/go)
ICS23_PROOFS_PROTO_PATH := cosmos/ics23/v1/proofs.proto
ICS23_PROOFS_PROTO_LOCAL_PATH := third_party/proto/$(ICS23_PROOFS_PROTO_PATH)
ICS23_PROOFS_PROTO_DOWNLOAD_URL := https://raw.githubusercontent.com/cosmos/ics23/go/$(ICS23_VERSION)/proto/$(ICS23_PROOFS_PROTO_PATH)
# #
# Common target directories # Common target directories
# #
@ -44,18 +54,20 @@ proto-update-deps: check-rsync ## Update all third party proto files
@curl -sSL $(PROTOBUF_ANY_DOWNLOAD_URL)/any.proto > $(PROTOBUF_GOOGLE_TYPES)/any.proto @curl -sSL $(PROTOBUF_ANY_DOWNLOAD_URL)/any.proto > $(PROTOBUF_GOOGLE_TYPES)/any.proto
@mkdir -p client/docs @mkdir -p client/docs
@cp $(COSMOS_SDK_PATH)/client/docs/swagger-ui/swagger.yaml client/docs/cosmos-swagger.yml @cp -f $(COSMOS_SDK_PATH)/client/docs/swagger-ui/swagger.yaml client/docs/cosmos-swagger.yml
@cp $(IBC_GO_PATH)/docs/client/swagger-ui/swagger.yaml client/docs/ibc-go-swagger.yml @cp -f $(IBC_GO_PATH)/docs/client/swagger-ui/swagger.yaml client/docs/ibc-go-swagger.yml
@mkdir -p $(COSMOS_PROTO_TYPES) @mkdir -p $(COSMOS_PROTO_TYPES)
@cp $(COSMOS_PROTO_PATH)/proto/cosmos_proto/cosmos.proto $(COSMOS_PROTO_TYPES)/cosmos.proto @cp -f $(COSMOS_PROTO_PATH)/proto/cosmos_proto/cosmos.proto $(COSMOS_PROTO_TYPES)/cosmos.proto
@mkdir -p $(dir $(ICS23_PROOFS_PROTO_LOCAL_PATH))
@curl -sSL $(ICS23_PROOFS_PROTO_DOWNLOAD_URL) > $(ICS23_PROOFS_PROTO_LOCAL_PATH)
@$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(GOGO_PATH)/gogoproto third_party/proto @$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(GOGO_PATH)/gogoproto third_party/proto
@$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(TENDERMINT_PATH)/proto third_party @$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(TENDERMINT_PATH)/proto third_party
@$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(COSMOS_SDK_PATH)/proto third_party @$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(COSMOS_SDK_PATH)/proto third_party
@$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(IBC_GO_PATH)/proto third_party @$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(IBC_GO_PATH)/proto third_party
@$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(ETHERMINT_PATH)/proto third_party @$(RSYNC_BIN) -r --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --include "*.proto" --include='*/' --exclude='*' $(ETHERMINT_PATH)/proto third_party
@cp -f $(IBC_GO_PATH)/third_party/proto/proofs.proto third_party/proto/proofs.proto
.PHONY: check-proto-deps .PHONY: check-proto-deps
check-proto-deps: proto-update-deps ## Return error code 1 if proto dependencies are not changed check-proto-deps: proto-update-deps ## Return error code 1 if proto dependencies are not changed

View File

@ -1,13 +1,13 @@
.PHONY: proto-lint check-proto-lint .PHONY: proto-lint check-proto-lint
proto-lint check-proto-lint: install-build-deps proto-lint check-proto-lint: install-build-deps
@echo "Linting proto file" @echo "Linting proto file"
@$(BUF) lint @$(BUF) lint proto
.PHONY: proto-gen .PHONY: proto-gen
proto-gen: install-build-deps proto-gen: install-build-deps
@echo "Generating go proto files" @echo "Generating go proto files"
@$(BUF) generate --template proto/buf.gen.gogo.yaml proto @$(BUF) generate --template proto/buf.gen.gogo.yaml proto
@cp -r out/github.com/kava-labs/kava/* ./ @cp -r out/github.com/0glabs/0g-chain/* ./
@rm -rf out/github.com @rm -rf out/github.com
.PHONY: check-proto-gen .PHONY: check-proto-gen

22
chaincfg/coin.go Normal file
View File

@ -0,0 +1,22 @@
package chaincfg
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
var (
// Bip44CoinType satisfies EIP84. See https://github.com/ethereum/EIPs/issues/84 for more info.
Bip44CoinType uint32 = 459 // TODO: need new coin type for 0g-chain (a0gi)
// eth = 60
// kava = 459 // see https://github.com/satoshilabs/slips/blob/master/slip-0044.md
// BIP44HDPath is the default BIP44 HD path used on Ethereum.
//BIP44HDPath = ethaccounts.DefaultBaseDerivationPath.String()
)
// TODO: Implement BIP44CoinType and BIP44HDPath
// SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets.
func setBip44CoinType(config *sdk.Config) {
config.SetCoinType(Bip44CoinType)
//config.SetPurpose(sdk.Purpose) // Shared
//config.SetFullFundraiserPath(BIP44HDPath) //nolint: staticcheck
}

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))
}

15
chaincfg/config.go Normal file
View File

@ -0,0 +1,15 @@
package chaincfg
import sdk "github.com/cosmos/cosmos-sdk/types"
const (
AppName = "0gchaind"
EnvPrefix = "0GCHAIN"
)
func SetSDKConfig() *sdk.Config {
config := sdk.GetConfig()
setBech32Prefixes(config)
setBip44CoinType(config)
return config
}

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)
})
}
}

25
chaincfg/homedir.go Normal file
View File

@ -0,0 +1,25 @@
package chaincfg
import (
stdlog "log"
"os"
"path/filepath"
)
const (
HomeDirName = ".0gchain"
)
var (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome string
)
func init() {
userHomeDir, err := os.UserHomeDir()
if err != nil {
stdlog.Printf("Failed to get home dir %v", err)
}
DefaultNodeHome = filepath.Join(userHomeDir, HomeDirName)
}

76
chaincfg/mint.go Normal file
View File

@ -0,0 +1,76 @@
package chaincfg
import (
"github.com/shopspring/decimal"
sdk "github.com/cosmos/cosmos-sdk/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
)
var (
Xmax, _ = sdk.NewDecFromStr("1.0") // upper limit on staked supply (as % of circ supply)
Ymin, _ = sdk.NewDecFromStr("0.05") // target APY at upper limit
Xmin, _ = sdk.NewDecFromStr("0.2") // lower limit on staked supply (as % of circ supply)
Ymax, _ = sdk.NewDecFromStr("0.15") // target APY at lower limit
decayRate, _ = sdk.NewDecFromStr("10")
)
func decExp(x sdk.Dec) sdk.Dec {
xDec := decimal.NewFromBigInt(x.BigInt(), -18)
expDec, _ := xDec.ExpTaylor(18)
expInt := expDec.Shift(18).BigInt()
return sdk.NewDecFromBigIntWithPrec(expInt, 18)
}
func NextInflationRate(ctx sdk.Context, minter minttypes.Minter, params minttypes.Params, bondedRatio sdk.Dec, circulatingRatio sdk.Dec) sdk.Dec {
X := bondedRatio.Quo(circulatingRatio)
var apy sdk.Dec
if X.LT(Xmin) {
apy = Ymax
} else {
exp := decayRate.Neg().Mul(Xmax.Sub(Xmin))
c := decExp(exp)
d := Ymin.Sub(Ymax.Mul(c)).Quo(sdk.OneDec().Sub(c))
expBonded := decayRate.Neg().Mul(X.Sub(Xmin))
cBonded := decExp(expBonded)
e := Ymax.Sub(d).Mul(cBonded)
apy = d.Add(e)
}
inflation := apy.Mul(bondedRatio)
// // The target annual inflation rate is recalculated for each previsions cycle. The
// // inflation is also subject to a rate change (positive or negative) depending on
// // the distance from the desired ratio (67%). The maximum rate change possible is
// // defined to be 13% per year, however the annual inflation is capped as between
// // 7% and 20%.
// // (1 - bondedRatio/GoalBonded) * InflationRateChange
// inflationRateChangePerYear := sdk.OneDec().
// Sub(bondedRatio.Quo(params.GoalBonded)).
// Mul(params.InflationRateChange)
// inflationRateChange := inflationRateChangePerYear.Quo(sdk.NewDec(int64(params.BlocksPerYear)))
// // adjust the new annual inflation for this next cycle
// inflation := minter.Inflation.Add(inflationRateChange) // note inflationRateChange may be negative
// if inflation.GT(params.InflationMax) {
// inflation = params.InflationMax
// }
// if inflation.LT(params.InflationMin) {
// inflation = params.InflationMin
// }
ctx.Logger().Info(
"nextInflationRate",
"bondedRatio", bondedRatio,
"circulatingRatio", circulatingRatio,
"apy", apy,
"inflation", inflation,
"params", params,
"minter", minter,
)
return inflation
}

44
chaincfg/prefix.go Normal file
View File

@ -0,0 +1,44 @@
package chaincfg
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// Bech32Prefix defines the Bech32 prefix used for EthAccounts
Bech32Prefix = "0g"
// PrefixAccount is the prefix for account keys
PrefixAccount = "acc"
// PrefixValidator is the prefix for validator keys
PrefixValidator = "val"
// PrefixConsensus is the prefix for consensus keys
PrefixConsensus = "cons"
// PrefixPublic is the prefix for public keys
PrefixPublic = "pub"
// PrefixOperator is the prefix for operator keys
PrefixOperator = "oper"
// PrefixAddress is the prefix for addresses
PrefixAddress = "addr"
// Bech32PrefixAccAddr defines the Bech32 prefix of an account's address
Bech32PrefixAccAddr = Bech32Prefix
// Bech32PrefixAccPub defines the Bech32 prefix of an account's public key
Bech32PrefixAccPub = Bech32Prefix + PrefixPublic
// Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
Bech32PrefixValAddr = Bech32Prefix + PrefixValidator + PrefixOperator
// Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
Bech32PrefixValPub = Bech32Prefix + PrefixValidator + PrefixOperator + PrefixPublic
// Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
Bech32PrefixConsAddr = Bech32Prefix + PrefixValidator + PrefixConsensus
// Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
Bech32PrefixConsPub = Bech32Prefix + PrefixValidator + PrefixConsensus + PrefixPublic
)
// setBech32Prefixes sets the global prefixes to be used when serializing addresses and public keys to Bech32 strings.
func setBech32Prefixes(config *sdk.Config) {
config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub)
config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub)
}

View File

@ -837,6 +837,7 @@
"gov_denom": "ukava", "gov_denom": "ukava",
"params": { "params": {
"circuit_breaker": false, "circuit_breaker": false,
"liquidation_block_interval": 500,
"collateral_params": [ "collateral_params": [
{ {
"auction_size": "50000000000", "auction_size": "50000000000",
@ -2177,6 +2178,23 @@
"quorum": "0.334000000000000000", "quorum": "0.334000000000000000",
"threshold": "0.500000000000000000", "threshold": "0.500000000000000000",
"veto_threshold": "0.334000000000000000" "veto_threshold": "0.334000000000000000"
},
"params": {
"min_deposit": [
{
"denom": "ukava",
"amount": "10000000"
}
],
"max_deposit_period": "172800s",
"voting_period": "600s",
"quorum": "0.334000000000000000",
"threshold": "0.500000000000000000",
"veto_threshold": "0.334000000000000000",
"min_initial_deposit_ratio": "0.000000000000000000",
"burn_vote_quorum": false,
"burn_proposal_deposit_prevote": false,
"burn_vote_veto": true
} }
}, },
"hard": { "hard": {

View File

@ -14,9 +14,9 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/cometbft/cometbft/crypto/ed25519"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/ed25519"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests"
@ -62,36 +62,36 @@ func TestKvCLIKeysAddRecover(t *testing.T) {
exitSuccess, _, _ = f.KeysAddRecover("test-recover", "dentist task convince chimney quality leave banana trade firm crawl eternal easily") exitSuccess, _, _ = f.KeysAddRecover("test-recover", "dentist task convince chimney quality leave banana trade firm crawl eternal easily")
require.True(t, exitSuccess) require.True(t, exitSuccess)
require.Equal(t, "kava1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recover").String()) require.Equal(t, "0g1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recover").String())
// test old bip44 coin type // test old bip44 coin type
exitSuccess, _, _ = f.KeysAddRecover("test-recover-legacy", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--legacy-hd-path") exitSuccess, _, _ = f.KeysAddRecover("test-recover-legacy", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--legacy-hd-path")
require.True(t, exitSuccess) require.True(t, exitSuccess)
require.Equal(t, "kava1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj", f.KeyAddress("test-recover-legacy").String()) require.Equal(t, "0g1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj", f.KeyAddress("test-recover-legacy").String())
// Cleanup testing directories // Cleanup testing directories
f.Cleanup() f.Cleanup()
} }
func TestKavaCLIKeysAddRecoverHDPath(t *testing.T) { func TestZgChainCLIKeysAddRecoverHDPath(t *testing.T) {
t.Parallel() t.Parallel()
f := InitFixtures(t) f := InitFixtures(t)
f.KeysAddRecoverHDPath("test-recoverHD1", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 0, 0) f.KeysAddRecoverHDPath("test-recoverHD1", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 0, 0)
require.Equal(t, "kava1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverHD1").String()) require.Equal(t, "0g1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverHD1").String())
f.KeysAddRecoverHDPath("test-recoverH2", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 5) f.KeysAddRecoverHDPath("test-recoverH2", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 5)
require.Equal(t, "kava1qpj6nstqn0n5gzcsaezspuhulje6msjq5t8cq5", f.KeyAddress("test-recoverH2").String()) require.Equal(t, "0g1qpj6nstqn0n5gzcsaezspuhulje6msjq5t8cq5", f.KeyAddress("test-recoverH2").String())
f.KeysAddRecoverHDPath("test-recoverH3", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 17) f.KeysAddRecoverHDPath("test-recoverH3", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 17)
require.Equal(t, "kava1vayfpstgapt7dmv7074kc3ll8xpf0rlzvh4k08", f.KeyAddress("test-recoverH3").String()) require.Equal(t, "0g1vayfpstgapt7dmv7074kc3ll8xpf0rlzvh4k08", f.KeyAddress("test-recoverH3").String())
f.KeysAddRecoverHDPath("test-recoverH4", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17) f.KeysAddRecoverHDPath("test-recoverH4", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17)
require.Equal(t, "kava1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH4").String()) require.Equal(t, "0g1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH4").String())
// test old bip44 coin type // test old bip44 coin type
f.KeysAddRecoverHDPath("test-recoverH5", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17, "--legacy-hd-path") f.KeysAddRecoverHDPath("test-recoverH5", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17, "--legacy-hd-path")
require.Equal(t, "kava1v9plmhvyhgxk3th9ydacm7j4z357s3nhhmy0tv", f.KeyAddress("test-recoverH5").String()) require.Equal(t, "0g1v9plmhvyhgxk3th9ydacm7j4z357s3nhhmy0tv", f.KeyAddress("test-recoverH5").String())
exitSuccess, _, _ := f.KeysAddRecover("test-recover-fail", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--legacy-hd-path --hd-path 44'/459'/0'/0/0") exitSuccess, _, _ := f.KeysAddRecover("test-recover-fail", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--legacy-hd-path --hd-path 44'/459'/0'/0/0")
require.False(t, exitSuccess) require.False(t, exitSuccess)
@ -99,11 +99,11 @@ func TestKavaCLIKeysAddRecoverHDPath(t *testing.T) {
// test -hd-path flag // test -hd-path flag
exitSuccess, _, _ = f.KeysAddRecover("test-recoverH6", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--hd-path 44'/459'/0'/0/0") exitSuccess, _, _ = f.KeysAddRecover("test-recoverH6", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--hd-path 44'/459'/0'/0/0")
require.True(t, exitSuccess) require.True(t, exitSuccess)
require.Equal(t, "kava1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverH6").String()) require.Equal(t, "0g1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverH6").String())
exitSuccess, _, _ = f.KeysAddRecover("test-recoverH7", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--hd-path 44'/459'/2'/0/17") exitSuccess, _, _ = f.KeysAddRecover("test-recoverH7", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--hd-path 44'/459'/2'/0/17")
require.True(t, exitSuccess) require.True(t, exitSuccess)
require.Equal(t, "kava1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH7").String()) require.Equal(t, "0g1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH7").String())
// Cleanup testing directories // Cleanup testing directories
f.Cleanup() f.Cleanup()
@ -813,7 +813,7 @@ func TestKvCLISubmitCommunityPoolSpendProposal(t *testing.T) {
} }
func TestKvCLIQueryTxPagination(t *testing.T) { func TestKvCLIQueryTxPagination(t *testing.T) {
// Skip until https://github.com/tendermint/tendermint/issues/4432 has been // Skip until https://github.com/cometbft/cometbft/issues/4432 has been
// resolved and included in a release. // resolved and included in a release.
t.SkipNow() t.SkipNow()

View File

@ -13,13 +13,13 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
tmtypes "github.com/tendermint/tendermint/types" tmtypes "github.com/cometbft/cometbft/types"
"cosmossdk.io/simapp"
clientkeys "github.com/cosmos/cosmos-sdk/client/keys" clientkeys "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
@ -28,7 +28,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/slashing"
"github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
) )
const ( const (
@ -65,8 +65,7 @@ var (
func init() { func init() {
// set the address prefixes // set the address prefixes
config := sdk.GetConfig() chaincfg.SetSDKConfig()
app.SetBech32AddressPrefixes(config)
// config.Seal() // config.Seal()
} }
@ -92,7 +91,7 @@ type Fixtures struct {
// NewFixtures creates a new instance of Fixtures with many vars set // NewFixtures creates a new instance of Fixtures with many vars set
func NewFixtures(t *testing.T) *Fixtures { func NewFixtures(t *testing.T) *Fixtures {
tmpDir, err := ioutil.TempDir("", "kava_integration_"+t.Name()+"_") tmpDir, err := ioutil.TempDir("", "0gchain_integration_"+t.Name()+"_")
require.NoError(t, err) require.NoError(t, err)
servAddr, port, err := server.FreeTCPAddr() servAddr, port, err := server.FreeTCPAddr()
@ -201,9 +200,9 @@ func (f *Fixtures) Flags() string {
} }
//___________________________________________________________________________________ //___________________________________________________________________________________
// kavad // 0gchaind
// UnsafeResetAll is kavad unsafe-reset-all // UnsafeResetAll is 0gchaind unsafe-reset-all
func (f *Fixtures) UnsafeResetAll(flags ...string) { func (f *Fixtures) UnsafeResetAll(flags ...string) {
cmd := fmt.Sprintf("%s --home=%s unsafe-reset-all", f.KvdBinary, f.KvdHome) cmd := fmt.Sprintf("%s --home=%s unsafe-reset-all", f.KvdBinary, f.KvdHome)
executeWrite(f.T, addFlags(cmd, flags)) executeWrite(f.T, addFlags(cmd, flags))
@ -211,7 +210,7 @@ func (f *Fixtures) UnsafeResetAll(flags ...string) {
require.NoError(f.T, err) require.NoError(f.T, err)
} }
// KvInit is kavad init // KvInit is 0gchaind init
// NOTE: KvInit sets the ChainID for the Fixtures instance // NOTE: KvInit sets the ChainID for the Fixtures instance
func (f *Fixtures) KvInit(moniker string, flags ...string) { func (f *Fixtures) KvInit(moniker string, flags ...string) {
cmd := fmt.Sprintf("%s init -o --home=%s %s", f.KvdBinary, f.KvdHome, moniker) cmd := fmt.Sprintf("%s init -o --home=%s %s", f.KvdBinary, f.KvdHome, moniker)
@ -229,25 +228,25 @@ func (f *Fixtures) KvInit(moniker string, flags ...string) {
f.ChainID = chainID f.ChainID = chainID
} }
// AddGenesisAccount is kavad add-genesis-account // AddGenesisAccount is 0gchaind add-genesis-account
func (f *Fixtures) AddGenesisAccount(address sdk.AccAddress, coins sdk.Coins, flags ...string) { func (f *Fixtures) AddGenesisAccount(address sdk.AccAddress, coins sdk.Coins, flags ...string) {
cmd := fmt.Sprintf("%s add-genesis-account %s %s --home=%s --keyring-backend=test", f.KvdBinary, address, coins, f.KvdHome) cmd := fmt.Sprintf("%s add-genesis-account %s %s --home=%s --keyring-backend=test", f.KvdBinary, address, coins, f.KvdHome)
executeWriteCheckErr(f.T, addFlags(cmd, flags)) executeWriteCheckErr(f.T, addFlags(cmd, flags))
} }
// GenTx is kavad gentx // GenTx is 0gchaind gentx
func (f *Fixtures) GenTx(name string, flags ...string) { func (f *Fixtures) GenTx(name string, flags ...string) {
cmd := fmt.Sprintf("%s gentx --name=%s --home=%s --home-client=%s --keyring-backend=test", f.KvdBinary, name, f.KvdHome, f.KvcliHome) cmd := fmt.Sprintf("%s gentx --name=%s --home=%s --home-client=%s --keyring-backend=test", f.KvdBinary, name, f.KvdHome, f.KvcliHome)
executeWriteCheckErr(f.T, addFlags(cmd, flags)) executeWriteCheckErr(f.T, addFlags(cmd, flags))
} }
// CollectGenTxs is kavad collect-gentxs // CollectGenTxs is 0gchaind collect-gentxs
func (f *Fixtures) CollectGenTxs(flags ...string) { func (f *Fixtures) CollectGenTxs(flags ...string) {
cmd := fmt.Sprintf("%s collect-gentxs --home=%s", f.KvdBinary, f.KvdHome) cmd := fmt.Sprintf("%s collect-gentxs --home=%s", f.KvdBinary, f.KvdHome)
executeWriteCheckErr(f.T, addFlags(cmd, flags)) executeWriteCheckErr(f.T, addFlags(cmd, flags))
} }
// GDStart runs kavad start with the appropriate flags and returns a process // GDStart runs 0gchaind start with the appropriate flags and returns a process
func (f *Fixtures) GDStart(flags ...string) *tests.Process { func (f *Fixtures) GDStart(flags ...string) *tests.Process {
cmd := fmt.Sprintf("%s start --home=%s --rpc.laddr=%v --p2p.laddr=%v --pruning=everything", f.KvdBinary, f.KvdHome, f.RPCAddr, f.P2PAddr) cmd := fmt.Sprintf("%s start --home=%s --rpc.laddr=%v --p2p.laddr=%v --pruning=everything", f.KvdBinary, f.KvdHome, f.RPCAddr, f.P2PAddr)
proc := tests.GoExecuteTWithStdout(f.T, addFlags(cmd, flags)) proc := tests.GoExecuteTWithStdout(f.T, addFlags(cmd, flags))
@ -256,7 +255,7 @@ func (f *Fixtures) GDStart(flags ...string) *tests.Process {
return proc return proc
} }
// GDTendermint returns the results of kavad tendermint [query] // GDTendermint returns the results of 0gchaind tendermint [query]
func (f *Fixtures) GDTendermint(query string) string { func (f *Fixtures) GDTendermint(query string) string {
cmd := fmt.Sprintf("%s tendermint %s --home=%s", f.KvdBinary, query, f.KvdHome) cmd := fmt.Sprintf("%s tendermint %s --home=%s", f.KvdBinary, query, f.KvdHome)
success, stdout, stderr := executeWriteRetStdStreams(f.T, cmd) success, stdout, stderr := executeWriteRetStdStreams(f.T, cmd)
@ -265,7 +264,7 @@ func (f *Fixtures) GDTendermint(query string) string {
return strings.TrimSpace(stdout) return strings.TrimSpace(stdout)
} }
// ValidateGenesis runs kavad validate-genesis // ValidateGenesis runs 0gchaind validate-genesis
func (f *Fixtures) ValidateGenesis() { func (f *Fixtures) ValidateGenesis() {
cmd := fmt.Sprintf("%s validate-genesis --home=%s", f.KvdBinary, f.KvdHome) cmd := fmt.Sprintf("%s validate-genesis --home=%s", f.KvdBinary, f.KvdHome)
executeWriteCheckErr(f.T, cmd) executeWriteCheckErr(f.T, cmd)

View File

@ -7,7 +7,7 @@
}, },
"externalDocs": { "externalDocs": {
"description": "GitHub", "description": "GitHub",
"url": "https://github.com/Kava-Labs/kava" "url": "https://github.com/0glabs/0g-chain"
}, },
"host": "api.data.kava.io", "host": "api.data.kava.io",
"schemes": ["https"], "schemes": ["https"],

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

74
client/grpc/README.md Normal file
View File

@ -0,0 +1,74 @@
# Kava gRPC Client
The Kava gRPC client is a tool for making gRPC queries on a Kava chain.
## Features
- Easy-to-use gRPC client for the Kava chain.
- Access all query clients for Cosmos and Kava modules using `client.Query` (e.g., `client.Query.Bank.Balance`).
- Utilize utility functions for common queries (e.g., `client.BaseAccount(str)`).
## Usage
### Creating a new client
```go
package main
import (
kavaGrpc "github.com/kava-labs/kava/client/grpc"
)
grpcUrl := "https://grpc.kava.io:443"
client, err := kavaGrpc.NewClient(grpcUrl)
if err != nil {
panic(err)
}
```
### Making grpc queries
Query clients for both Cosmos and Kava modules are available via `client.Query`.
Example: Query Cosmos module `x/bank` for address balance
```go
import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
)
rsp, err := client.Query.Bank.Balance(context.Background(), &banktypes.QueryBalanceRequest{
Address: "kava19rjk5qmmwywnzfccwzyn02jywgpwjqf60afj92",
Denom: "ukava",
})
```
Example: Query Kava module `x/evmutil` for params
```go
import (
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types"
)
rsp, err := client.Query.Evmutil.Params(
context.Background(), &evmutiltypes.QueryParamsRequest{},
)
```
#### Query Utilities
Utility functions for common queries are available directly on the client.
Example: Util query to get a base account
```go
kavaAcc := "kava19rjk5qmmwywnzfccwzyn02jywgpwjqf60afj92"
rsp, err := client.BaseAccount(kavaAcc)
if err != nil {
panic(err)
}
fmt.Printf("account sequence for %s: %d\n", kavaAcc, rsp.Sequence)
```
## Query Tests
To test queries, a Kava node is required. Therefore, the e2e tests for the gRPC client queries can be found in the `tests/e2e` directory. Tests for new utility queries should be added as e2e tests under the `test/e2e` directory.

50
client/grpc/client.go Normal file
View File

@ -0,0 +1,50 @@
package grpc
import (
"errors"
"github.com/kava-labs/kava/client/grpc/query"
"github.com/kava-labs/kava/client/grpc/util"
)
// KavaGrpcClient enables the usage of kava grpc query clients and query utils
type KavaGrpcClient struct {
config KavaGrpcClientConfig
// Query clients for cosmos and kava modules
Query *query.QueryClient
// Utils for common queries (ie fetch an unpacked BaseAccount)
*util.Util
}
// KavaGrpcClientConfig is a configuration struct for a KavaGrpcClient
type KavaGrpcClientConfig struct {
// note: add future config options here
}
// NewClient creates a new KavaGrpcClient via a grpc url
func NewClient(grpcUrl string) (*KavaGrpcClient, error) {
return NewClientWithConfig(grpcUrl, NewDefaultConfig())
}
// NewClientWithConfig creates a new KavaGrpcClient via a grpc url and config
func NewClientWithConfig(grpcUrl string, config KavaGrpcClientConfig) (*KavaGrpcClient, error) {
if grpcUrl == "" {
return nil, errors.New("grpc url cannot be empty")
}
query, error := query.NewQueryClient(grpcUrl)
if error != nil {
return nil, error
}
client := &KavaGrpcClient{
Query: query,
Util: util.NewUtil(query),
config: config,
}
return client, nil
}
func NewDefaultConfig() KavaGrpcClientConfig {
return KavaGrpcClientConfig{}
}

View File

@ -0,0 +1,15 @@
package grpc_test
import (
"testing"
"github.com/kava-labs/kava/client/grpc"
"github.com/stretchr/testify/require"
)
func TestNewClient_InvalidEndpoint(t *testing.T) {
_, err := grpc.NewClient("invalid-url")
require.ErrorContains(t, err, "unknown grpc url scheme")
_, err = grpc.NewClient("")
require.ErrorContains(t, err, "grpc url cannot be empty")
}

View File

@ -1,25 +1,21 @@
package util package query
import ( import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"net/url" "net/url"
"strconv"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
) )
// NewGrpcConnection parses a GRPC endpoint and creates a connection to it // newGrpcConnection parses a GRPC endpoint and creates a connection to it
func NewGrpcConnection(endpoint string) (*grpc.ClientConn, error) { func newGrpcConnection(ctx context.Context, endpoint string) (*grpc.ClientConn, error) {
grpcUrl, err := url.Parse(endpoint) grpcUrl, err := url.Parse(endpoint)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("failed to parse grpc connection \"%s\": %v", endpoint, err)
} }
var creds credentials.TransportCredentials var creds credentials.TransportCredentials
@ -33,15 +29,10 @@ func NewGrpcConnection(endpoint string) (*grpc.ClientConn, error) {
} }
secureOpt := grpc.WithTransportCredentials(creds) secureOpt := grpc.WithTransportCredentials(creds)
grpcConn, err := grpc.Dial(grpcUrl.Host, secureOpt) grpcConn, err := grpc.DialContext(ctx, grpcUrl.Host, secureOpt)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return grpcConn, nil return grpcConn, nil
} }
func CtxAtHeight(height int64) context.Context {
heightStr := strconv.FormatInt(height, 10)
return metadata.AppendToOutgoingContext(context.Background(), grpctypes.GRPCBlockHeightHeader, heightStr)
}

7
client/grpc/query/doc.go Normal file
View File

@ -0,0 +1,7 @@
/*
The query package includes Cosmos and Kava gRPC query clients.
To ensure that the `QueryClient` stays updated, add new module query clients
to the `QueryClient` whenever new modules with grpc queries are added to the Kava app.
*/
package query

132
client/grpc/query/query.go Normal file
View File

@ -0,0 +1,132 @@
package query
import (
"context"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authz "github.com/cosmos/cosmos-sdk/x/authz"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
govv1types "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
govv1beta1types "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"
ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types"
evmtypes "github.com/evmos/ethermint/x/evm/types"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
auctiontypes "github.com/kava-labs/kava/x/auction/types"
bep3types "github.com/kava-labs/kava/x/bep3/types"
cdptypes "github.com/kava-labs/kava/x/cdp/types"
committeetypes "github.com/kava-labs/kava/x/committee/types"
communitytypes "github.com/kava-labs/kava/x/community/types"
earntypes "github.com/kava-labs/kava/x/earn/types"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types"
hardtypes "github.com/kava-labs/kava/x/hard/types"
incentivetypes "github.com/kava-labs/kava/x/incentive/types"
issuancetypes "github.com/kava-labs/kava/x/issuance/types"
kavadisttypes "github.com/kava-labs/kava/x/kavadist/types"
liquidtypes "github.com/kava-labs/kava/x/liquid/types"
pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types"
savingstypes "github.com/kava-labs/kava/x/savings/types"
swaptypes "github.com/kava-labs/kava/x/swap/types"
)
// QueryClient is a wrapper with all Cosmos and Kava grpc query clients
type QueryClient struct {
// cosmos-sdk query clients
Tm tmservice.ServiceClient
Tx txtypes.ServiceClient
Auth authtypes.QueryClient
Authz authz.QueryClient
Bank banktypes.QueryClient
Distribution disttypes.QueryClient
Evidence evidencetypes.QueryClient
Gov govv1types.QueryClient
GovBeta govv1beta1types.QueryClient
Mint minttypes.QueryClient
Params paramstypes.QueryClient
Slashing slashingtypes.QueryClient
Staking stakingtypes.QueryClient
Upgrade upgradetypes.QueryClient
// 3rd party query clients
Evm evmtypes.QueryClient
Feemarket feemarkettypes.QueryClient
IbcClient ibcclienttypes.QueryClient
IbcTransfer ibctransfertypes.QueryClient
// kava module query clients
Auction auctiontypes.QueryClient
Bep3 bep3types.QueryClient
Cdp cdptypes.QueryClient
Committee committeetypes.QueryClient
Community communitytypes.QueryClient
Earn earntypes.QueryClient
Evmutil evmutiltypes.QueryClient
Hard hardtypes.QueryClient
Incentive incentivetypes.QueryClient
Issuance issuancetypes.QueryClient
Kavadist kavadisttypes.QueryClient
Liquid liquidtypes.QueryClient
Pricefeed pricefeedtypes.QueryClient
Savings savingstypes.QueryClient
Swap swaptypes.QueryClient
}
// NewQueryClient creates a new QueryClient and initializes all the module query clients
func NewQueryClient(grpcEndpoint string) (*QueryClient, error) {
conn, err := newGrpcConnection(context.Background(), grpcEndpoint)
if err != nil {
return &QueryClient{}, err
}
client := &QueryClient{
Tm: tmservice.NewServiceClient(conn),
Tx: txtypes.NewServiceClient(conn),
Auth: authtypes.NewQueryClient(conn),
Authz: authz.NewQueryClient(conn),
Bank: banktypes.NewQueryClient(conn),
Distribution: disttypes.NewQueryClient(conn),
Evidence: evidencetypes.NewQueryClient(conn),
Gov: govv1types.NewQueryClient(conn),
GovBeta: govv1beta1types.NewQueryClient(conn),
Mint: minttypes.NewQueryClient(conn),
Params: paramstypes.NewQueryClient(conn),
Slashing: slashingtypes.NewQueryClient(conn),
Staking: stakingtypes.NewQueryClient(conn),
Upgrade: upgradetypes.NewQueryClient(conn),
Evm: evmtypes.NewQueryClient(conn),
Feemarket: feemarkettypes.NewQueryClient(conn),
IbcClient: ibcclienttypes.NewQueryClient(conn),
IbcTransfer: ibctransfertypes.NewQueryClient(conn),
Auction: auctiontypes.NewQueryClient(conn),
Bep3: bep3types.NewQueryClient(conn),
Cdp: cdptypes.NewQueryClient(conn),
Committee: committeetypes.NewQueryClient(conn),
Community: communitytypes.NewQueryClient(conn),
Earn: earntypes.NewQueryClient(conn),
Evmutil: evmutiltypes.NewQueryClient(conn),
Hard: hardtypes.NewQueryClient(conn),
Incentive: incentivetypes.NewQueryClient(conn),
Issuance: issuancetypes.NewQueryClient(conn),
Kavadist: kavadisttypes.NewQueryClient(conn),
Liquid: liquidtypes.NewQueryClient(conn),
Pricefeed: pricefeedtypes.NewQueryClient(conn),
Savings: savingstypes.NewQueryClient(conn),
Swap: swaptypes.NewQueryClient(conn),
}
return client, nil
}

View File

@ -0,0 +1,73 @@
package query_test
import (
"testing"
"github.com/kava-labs/kava/client/grpc/query"
"github.com/stretchr/testify/require"
)
func TestNewQueryClient_InvalidGprc(t *testing.T) {
t.Run("valid connection", func(t *testing.T) {
conn, err := query.NewQueryClient("http://localhost:1234")
require.NoError(t, err)
require.NotNil(t, conn)
})
t.Run("non-empty url", func(t *testing.T) {
_, err := query.NewQueryClient("")
require.ErrorContains(t, err, "unknown grpc url scheme")
})
t.Run("invalid url scheme", func(t *testing.T) {
_, err := query.NewQueryClient("ftp://localhost:1234")
require.ErrorContains(t, err, "unknown grpc url scheme")
})
}
func TestNewQueryClient_ValidClient(t *testing.T) {
t.Run("all clients are created", func(t *testing.T) {
client, err := query.NewQueryClient("http://localhost:1234")
require.NoError(t, err)
require.NotNil(t, client)
// validate cosmos clients
require.NotNil(t, client.Tm)
require.NotNil(t, client.Tx)
require.NotNil(t, client.Auth)
require.NotNil(t, client.Authz)
require.NotNil(t, client.Bank)
require.NotNil(t, client.Distribution)
require.NotNil(t, client.Evidence)
require.NotNil(t, client.Gov)
require.NotNil(t, client.GovBeta)
require.NotNil(t, client.Mint)
require.NotNil(t, client.Params)
require.NotNil(t, client.Slashing)
require.NotNil(t, client.Staking)
require.NotNil(t, client.Upgrade)
// validate 3rd party clients
require.NotNil(t, client.Evm)
require.NotNil(t, client.Feemarket)
require.NotNil(t, client.IbcClient)
require.NotNil(t, client.IbcTransfer)
// validate kava clients
require.NotNil(t, client.Auction)
require.NotNil(t, client.Bep3)
require.NotNil(t, client.Cdp)
require.NotNil(t, client.Committee)
require.NotNil(t, client.Community)
require.NotNil(t, client.Earn)
require.NotNil(t, client.Evmutil)
require.NotNil(t, client.Hard)
require.NotNil(t, client.Incentive)
require.NotNil(t, client.Issuance)
require.NotNil(t, client.Kavadist)
require.NotNil(t, client.Liquid)
require.NotNil(t, client.Pricefeed)
require.NotNil(t, client.Savings)
require.NotNil(t, client.Swap)
})
}

View File

@ -0,0 +1,41 @@
package util
import (
"context"
"fmt"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
// Account fetches an account via an address and returns the unpacked account
func (u *Util) Account(addr string) (authtypes.AccountI, error) {
res, err := u.query.Auth.Account(context.Background(), &authtypes.QueryAccountRequest{
Address: addr,
})
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
var acc authtypes.AccountI
err = u.encodingConfig.Marshaler.UnpackAny(res.Account, &acc)
if err != nil {
return nil, fmt.Errorf("failed to unpack account: %w", err)
}
return acc, nil
}
// BaseAccount fetches a base account via an address or returns an error if
// the account is not a base account
func (u *Util) BaseAccount(addr string) (authtypes.BaseAccount, error) {
acc, err := u.Account(addr)
if err != nil {
return authtypes.BaseAccount{}, err
}
bAcc, ok := acc.(*authtypes.BaseAccount)
if !ok {
return authtypes.BaseAccount{}, fmt.Errorf("%s is not a base account", addr)
}
return *bAcc, nil
}

8
client/grpc/util/doc.go Normal file
View File

@ -0,0 +1,8 @@
/*
The util package contains utility functions for the Kava gRPC client.
For example, `account.go` includes account-related query helpers.
In this file, utilities such as `client.Util.BaseAccount(addr)` is exposed to
query an account and return an unpacked `BaseAccount` instance.
*/
package util

32
client/grpc/util/util.go Normal file
View File

@ -0,0 +1,32 @@
package util
import (
"context"
"strconv"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"google.golang.org/grpc/metadata"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/params"
query "github.com/kava-labs/kava/client/grpc/query"
)
// Util contains utility functions for the Kava gRPC client
type Util struct {
query *query.QueryClient
encodingConfig params.EncodingConfig
}
// NewUtil creates a new Util instance
func NewUtil(query *query.QueryClient) *Util {
return &Util{
query: query,
encodingConfig: app.MakeEncodingConfig(),
}
}
func (u *Util) CtxAtHeight(height int64) context.Context {
heightStr := strconv.FormatInt(height, 10)
return metadata.AppendToOutgoingContext(context.Background(), grpctypes.GRPCBlockHeightHeader, heightStr)
}

View File

@ -13,7 +13,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/tendermint/tendermint/types" "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"

View File

@ -12,15 +12,14 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/0glabs/0g-chain/client/rest"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/client/rest"
) )
func TestBaseReq_Sanitize(t *testing.T) { func TestBaseReq_Sanitize(t *testing.T) {

View File

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"errors" "errors"
@ -7,6 +7,9 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
cometbftdb "github.com/cometbft/cometbft-db"
"github.com/cometbft/cometbft/libs/log"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
@ -19,12 +22,9 @@ import (
ethermintflags "github.com/evmos/ethermint/server/flags" ethermintflags "github.com/evmos/ethermint/server/flags"
"github.com/spf13/cast" "github.com/spf13/cast"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tendermint/tendermint/libs/log"
db "github.com/tendermint/tm-db"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
metricstypes "github.com/kava-labs/kava/x/metrics/types"
) )
const ( const (
@ -32,7 +32,7 @@ const (
flagMempoolAuthAddresses = "mempool.authorized-addresses" flagMempoolAuthAddresses = "mempool.authorized-addresses"
) )
// appCreator holds functions used by the sdk server to control the kava app. // appCreator holds functions used by the sdk server to control the 0g-chain app.
// The methods implement types in cosmos-sdk/server/types // The methods implement types in cosmos-sdk/server/types
type appCreator struct { type appCreator struct {
encodingConfig params.EncodingConfig encodingConfig params.EncodingConfig
@ -41,7 +41,7 @@ type appCreator struct {
// newApp loads config from AppOptions and returns a new app. // newApp loads config from AppOptions and returns a new app.
func (ac appCreator) newApp( func (ac appCreator) newApp(
logger log.Logger, logger log.Logger,
db db.DB, db cometbftdb.DB,
traceStore io.Writer, traceStore io.Writer,
appOpts servertypes.AppOptions, appOpts servertypes.AppOptions,
) servertypes.Application { ) servertypes.Application {
@ -62,7 +62,7 @@ func (ac appCreator) newApp(
homeDir := cast.ToString(appOpts.Get(flags.FlagHome)) homeDir := cast.ToString(appOpts.Get(flags.FlagHome))
snapshotDir := filepath.Join(homeDir, "data", "snapshots") // TODO can these directory names be imported from somewhere? snapshotDir := filepath.Join(homeDir, "data", "snapshots") // TODO can these directory names be imported from somewhere?
snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir) snapshotDB, err := cometbftdb.NewDB("metadata", server.GetAppDBBackend(appOpts), snapshotDir)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -89,6 +89,17 @@ func (ac appCreator) newApp(
cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent)), cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent)),
) )
// Setup chainId
chainID := cast.ToString(appOpts.Get(flags.FlagChainID))
if len(chainID) == 0 {
// fallback to genesis chain-id
appGenesis, err := tmtypes.GenesisDocFromFile(filepath.Join(homeDir, "config", "genesis.json"))
if err != nil {
panic(err)
}
chainID = appGenesis.ChainID
}
return app.NewApp( return app.NewApp(
logger, db, homeDir, traceStore, ac.encodingConfig, logger, db, homeDir, traceStore, ac.encodingConfig,
app.Options{ app.Options{
@ -100,7 +111,6 @@ func (ac appCreator) newApp(
MempoolAuthAddresses: mempoolAuthAddresses, MempoolAuthAddresses: mempoolAuthAddresses,
EVMTrace: cast.ToString(appOpts.Get(ethermintflags.EVMTracer)), EVMTrace: cast.ToString(appOpts.Get(ethermintflags.EVMTracer)),
EVMMaxGasWanted: cast.ToUint64(appOpts.Get(ethermintflags.EVMMaxTxGasWanted)), EVMMaxGasWanted: cast.ToUint64(appOpts.Get(ethermintflags.EVMMaxTxGasWanted)),
TelemetryOptions: metricstypes.TelemetryOptionsFromAppOpts(appOpts),
}, },
baseapp.SetPruning(pruningOpts), baseapp.SetPruning(pruningOpts),
baseapp.SetMinGasPrices(strings.Replace(cast.ToString(appOpts.Get(server.FlagMinGasPrices)), ";", ",", -1)), baseapp.SetMinGasPrices(strings.Replace(cast.ToString(appOpts.Get(server.FlagMinGasPrices)), ";", ",", -1)),
@ -114,18 +124,20 @@ func (ac appCreator) newApp(
baseapp.SetIAVLCacheSize(cast.ToInt(appOpts.Get(server.FlagIAVLCacheSize))), baseapp.SetIAVLCacheSize(cast.ToInt(appOpts.Get(server.FlagIAVLCacheSize))),
baseapp.SetIAVLDisableFastNode(cast.ToBool(iavlDisableFastNode)), baseapp.SetIAVLDisableFastNode(cast.ToBool(iavlDisableFastNode)),
baseapp.SetIAVLLazyLoading(cast.ToBool(appOpts.Get(server.FlagIAVLLazyLoading))), baseapp.SetIAVLLazyLoading(cast.ToBool(appOpts.Get(server.FlagIAVLLazyLoading))),
baseapp.SetChainID(chainID),
) )
} }
// appExport writes out an app's state to json. // appExport writes out an app's state to json.
func (ac appCreator) appExport( func (ac appCreator) appExport(
logger log.Logger, logger log.Logger,
db db.DB, db cometbftdb.DB,
traceStore io.Writer, traceStore io.Writer,
height int64, height int64,
forZeroHeight bool, forZeroHeight bool,
jailAllowedAddrs []string, jailAllowedAddrs []string,
appOpts servertypes.AppOptions, appOpts servertypes.AppOptions,
modulesToExport []string,
) (servertypes.ExportedApp, error) { ) (servertypes.ExportedApp, error) {
homePath, ok := appOpts.Get(flags.FlagHome).(string) homePath, ok := appOpts.Get(flags.FlagHome).(string)
if !ok || homePath == "" { if !ok || homePath == "" {
@ -146,7 +158,7 @@ func (ac appCreator) appExport(
} else { } else {
tempApp = app.NewApp(logger, db, homePath, traceStore, ac.encodingConfig, options) tempApp = app.NewApp(logger, db, homePath, traceStore, ac.encodingConfig, options)
} }
return tempApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) return tempApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport)
} }
// addStartCmdFlags adds flags to the server start command. // addStartCmdFlags adds flags to the server start command.

View File

@ -1,16 +1,16 @@
package cmd package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/version"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/spf13/cobra" "github.com/spf13/cobra"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
) )
func AssertInvariantsCmd(config params.EncodingConfig) *cobra.Command { func AssertInvariantsCmd(config params.EncodingConfig) *cobra.Command {

View File

@ -1,5 +1,5 @@
// Sourced from https://github.com/evmos/ethermint/blob/main/cmd/ethermintd/genaccounts.go // Sourced from https://github.com/evmos/ethermint/blob/main/cmd/ethermintd/genaccounts.go
package cmd package main
import ( import (
"bufio" "bufio"

View File

@ -1,14 +1,14 @@
package client package cmd
import ( import (
"bufio" "bufio"
"github.com/cometbft/cometbft/libs/cli"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/keys"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keyring"
ethclient "github.com/evmos/ethermint/client" ethclient "github.com/evmos/ethermint/client"
@ -18,9 +18,9 @@ import (
var ethFlag = "eth" var ethFlag = "eth"
// KeyCommands registers a sub-tree of commands to interact with // keyCommands registers a sub-tree of commands to interact with
// local private key storage. // local private key storage.
func KeyCommands(defaultNodeHome string) *cobra.Command { func keyCommands(defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "keys", Use: "keys",
Short: "Manage your application's keys", Short: "Manage your application's keys",
@ -52,6 +52,13 @@ The pass backend requires GnuPG: https://gnupg.org/
addCmd := keys.AddKeyCommand() addCmd := keys.AddKeyCommand()
addCmd.Flags().Bool(ethFlag, false, "use default evm coin-type (60) and key signing algorithm (\"eth_secp256k1\")") addCmd.Flags().Bool(ethFlag, false, "use default evm coin-type (60) and key signing algorithm (\"eth_secp256k1\")")
algoFlag := addCmd.Flag(flags.FlagKeyAlgorithm)
algoFlag.DefValue = string(hd.EthSecp256k1Type)
err := algoFlag.Value.Set(string(hd.EthSecp256k1Type))
if err != nil {
panic(err)
}
addCmd.RunE = runAddCmd addCmd.RunE = runAddCmd
cmd.AddCommand( cmd.AddCommand(
@ -100,7 +107,7 @@ func runAddCmd(cmd *cobra.Command, args []string) error {
eth, _ := cmd.Flags().GetBool(ethFlag) eth, _ := cmd.Flags().GetBool(ethFlag)
if eth { if eth {
cmd.Print("eth flag specified: using coin-type 60 and signing algorithm eth_secp256k1\n") cmd.Print("eth flag specified: using coin-type 60 and signing algorithm eth_secp256k1\n")
cmd.Flags().Set(flags.FlagKeyAlgorithm, string(hd.EthSecp256k1Type)) cmd.Flags().Set(flags.FlagKeyType, string(hd.EthSecp256k1Type))
cmd.Flags().Set("coin-type", "60") cmd.Flags().Set("coin-type", "60")
} }

View File

@ -6,14 +6,15 @@ import (
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/chaincfg"
"github.com/kava-labs/kava/cmd/kava/cmd"
) )
func main() { func main() {
rootCmd := cmd.NewRootCmd() chaincfg.SetSDKConfig().Seal()
if err := svrcmd.Execute(rootCmd, cmd.EnvPrefix, app.DefaultNodeHome); err != nil { rootCmd := NewRootCmd()
if err := svrcmd.Execute(rootCmd, chaincfg.EnvPrefix, chaincfg.DefaultNodeHome); err != nil {
switch e := err.(type) { switch e := err.(type) {
case server.ErrorCode: case server.ErrorCode:
os.Exit(e.Code) os.Exit(e.Code)

View File

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
@ -7,7 +7,7 @@ import (
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
) )
// newQueryCmd creates all the commands for querying blockchain state. // newQueryCmd creates all the commands for querying blockchain state.

View File

@ -1,40 +1,46 @@
package cmd package main
import ( import (
"fmt"
"os" "os"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/config"
"github.com/cosmos/cosmos-sdk/client/debug" "github.com/cosmos/cosmos-sdk/client/debug"
"github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
tmcfg "github.com/cometbft/cometbft/config"
tmcli "github.com/cometbft/cometbft/libs/cli"
"github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
ethermintclient "github.com/evmos/ethermint/client" ethermintclient "github.com/evmos/ethermint/client"
"github.com/evmos/ethermint/crypto/hd" "github.com/evmos/ethermint/crypto/hd"
ethermintserver "github.com/evmos/ethermint/server" ethermintserver "github.com/evmos/ethermint/server"
servercfg "github.com/evmos/ethermint/server/config" servercfg "github.com/evmos/ethermint/server/config"
"github.com/spf13/cobra" "github.com/spf13/cobra"
tmcfg "github.com/tendermint/tendermint/config"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
kavaclient "github.com/kava-labs/kava/client" "github.com/0glabs/0g-chain/chaincfg"
"github.com/kava-labs/kava/cmd/kava/opendb" "github.com/0glabs/0g-chain/cmd/opendb"
"github.com/0glabs/0g-chain/crypto/vrf"
) )
// EnvPrefix is the prefix environment variables must have to configure the app. func customKeyringOptions() keyring.Option {
const EnvPrefix = "KAVA" return func(options *keyring.Options) {
options.SupportedAlgos = append(hd.SupportedAlgorithms, vrf.VrfAlgo)
options.SupportedAlgosLedger = append(hd.SupportedAlgorithmsLedger, vrf.VrfAlgo)
}
}
// NewRootCmd creates a new root command for the kava blockchain. // NewRootCmd creates a new root command for the 0g-chain blockchain.
func NewRootCmd() *cobra.Command { func NewRootCmd() *cobra.Command {
app.SetSDKConfig().Seal()
encodingConfig := app.MakeEncodingConfig() encodingConfig := app.MakeEncodingConfig()
initClientCtx := client.Context{}. initClientCtx := client.Context{}.
WithCodec(encodingConfig.Marshaler). WithCodec(encodingConfig.Marshaler).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry). WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
@ -42,14 +48,21 @@ func NewRootCmd() *cobra.Command {
WithLegacyAmino(encodingConfig.Amino). WithLegacyAmino(encodingConfig.Amino).
WithInput(os.Stdin). WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}). WithAccountRetriever(types.AccountRetriever{}).
WithBroadcastMode(flags.BroadcastBlock). <<<<<<< HEAD
WithBroadcastMode(flags.FlagBroadcastMode).
WithHomeDir(app.DefaultNodeHome). WithHomeDir(app.DefaultNodeHome).
WithKeyringOptions(hd.EthSecp256k1Option()). WithKeyringOptions(hd.EthSecp256k1Option()).
WithViper(EnvPrefix) WithViper(EnvPrefix)
=======
WithBroadcastMode(flags.BroadcastBlock).
WithHomeDir(chaincfg.DefaultNodeHome).
WithKeyringOptions(customKeyringOptions()).
WithViper(chaincfg.EnvPrefix)
>>>>>>> be1cd76f (add vrf)
rootCmd := &cobra.Command{ rootCmd := &cobra.Command{
Use: "kava", Use: chaincfg.AppName,
Short: "Daemon and CLI for the Kava blockchain.", Short: "Daemon and CLI for the 0g-chain blockchain.",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
cmd.SetOut(cmd.OutOrStdout()) cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr()) cmd.SetErr(cmd.ErrOrStderr())
@ -68,7 +81,7 @@ func NewRootCmd() *cobra.Command {
return err return err
} }
customAppTemplate, customAppConfig := servercfg.AppConfig("ukava") customAppTemplate, customAppConfig := servercfg.AppConfig(chaincfg.GasDenom)
return server.InterceptConfigsPreRunHandler( return server.InterceptConfigsPreRunHandler(
cmd, cmd,
@ -79,19 +92,24 @@ func NewRootCmd() *cobra.Command {
}, },
} }
addSubCmds(rootCmd, encodingConfig, app.DefaultNodeHome) addSubCmds(rootCmd, encodingConfig, chaincfg.DefaultNodeHome)
return rootCmd return rootCmd
} }
// addSubCmds registers all the sub commands used by kava. // addSubCmds registers all the sub commands used by 0g-chain.
func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, defaultNodeHome string) { func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, defaultNodeHome string) {
gentxModule, ok := app.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic)
if !ok {
panic(fmt.Errorf("expected %s module to be an instance of type %T", genutiltypes.ModuleName, genutil.AppModuleBasic{}))
}
rootCmd.AddCommand( rootCmd.AddCommand(
StatusCommand(), StatusCommand(),
ethermintclient.ValidateChainID( ethermintclient.ValidateChainID(
genutilcli.InitCmd(app.ModuleBasics, defaultNodeHome), genutilcli.InitCmd(app.ModuleBasics, defaultNodeHome),
), ),
genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome), genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome, gentxModule.GenTxValidator),
AssertInvariantsCmd(encodingConfig), AssertInvariantsCmd(encodingConfig),
genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, defaultNodeHome), genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, defaultNodeHome),
genutilcli.ValidateGenesisCmd(app.ModuleBasics), genutilcli.ValidateGenesisCmd(app.ModuleBasics),
@ -108,7 +126,7 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de
opts := ethermintserver.StartOptions{ opts := ethermintserver.StartOptions{
AppCreator: ac.newApp, AppCreator: ac.newApp,
DefaultNodeHome: app.DefaultNodeHome, DefaultNodeHome: chaincfg.DefaultNodeHome,
DBOpener: opendb.OpenDB, DBOpener: opendb.OpenDB,
} }
// ethermintserver adds additional flags to start the JSON-RPC server for evm support // ethermintserver adds additional flags to start the JSON-RPC server for evm support
@ -119,10 +137,12 @@ 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(),
kavaclient.KeyCommands(app.DefaultNodeHome), keyCommands(app.DefaultNodeHome),
rocksdb.RocksDBCmd,
newShardCmd(opts),
) )
} }

232
cmd/0gchaind/shard.go Normal file
View File

@ -0,0 +1,232 @@
package cmd
import (
"fmt"
"strings"
"github.com/spf13/cobra"
dbm "github.com/cometbft/cometbft-db"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types"
"github.com/cosmos/cosmos-sdk/store/rootmulti"
tmconfig "github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/node"
tmstate "github.com/cometbft/cometbft/state"
"github.com/cometbft/cometbft/store"
ethermintserver "github.com/evmos/ethermint/server"
)
const (
flagShardStartBlock = "start"
flagShardEndBlock = "end"
flagShardOnlyAppState = "only-app-state"
// TODO: --preserve flag for creating & operating on a copy?
// allow using -1 to mean "latest" (perform no rollbacks)
shardEndBlockLatest = -1
)
func newShardCmd(opts ethermintserver.StartOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "shard --home <path-to-home-dir> --start <start-block> --end <end-block> [--only-app-state]",
Short: "Strip all blocks from the database outside of a given range",
Long: `shard opens a local kava home directory's databases and removes all blocks outside a range defined by --start and --end. The range is inclusive of the end block.
It works by first rolling back the latest state to the block before the end block, and then by pruning all state before the start block.
Setting the end block to -1 signals to keep the latest block (no rollbacks).
The --only-app-state flag can be used to skip the pruning of the blockstore and cometbft state. This matches the functionality of the cosmos-sdk's "prune" command. Note that rolled back blocks will still affect all stores.
WARNING: this is a destructive action.`,
Example: `Create a 1M block data shard (keeps blocks kava 1,000,000 to 2,000,000)
$ kava shard --home path/to/.kava --start 1000000 --end 2000000
Prune all blocks up to 5,000,000:
$ kava shard --home path/to/.kava --start 5000000 --end -1
Prune first 1M blocks _without_ affecting blockstore or cometBFT state:
$ kava shard --home path/to/.kava --start 1000000 --end -1 --only-app-state`,
RunE: func(cmd *cobra.Command, args []string) error {
// read & validate flags
startBlock, err := cmd.Flags().GetInt64(flagShardStartBlock)
if err != nil {
return err
}
endBlock, err := cmd.Flags().GetInt64(flagShardEndBlock)
if err != nil {
return err
}
if (endBlock == 0 || endBlock < startBlock) && endBlock != shardEndBlockLatest {
return fmt.Errorf("end block (%d) must be greater than start block (%d)", endBlock, startBlock)
}
onlyAppState, err := cmd.Flags().GetBool(flagShardOnlyAppState)
if err != nil {
return err
}
clientCtx := client.GetClientContextFromCmd(cmd)
ctx := server.GetServerContextFromCmd(cmd)
ctx.Config.SetRoot(clientCtx.HomeDir)
//////////////////////////////
// Rollback state to endBlock
//////////////////////////////
// connect to database
db, err := opts.DBOpener(ctx.Viper, clientCtx.HomeDir, server.GetAppDBBackend(ctx.Viper))
if err != nil {
return err
}
// close db connection when done
defer func() {
if err := db.Close(); err != nil {
ctx.Logger.Error("error closing db", "error", err.Error())
}
}()
// get the multistore
app := opts.AppCreator(ctx.Logger, db, nil, ctx.Viper)
cms := app.CommitMultiStore()
multistore, ok := cms.(*rootmulti.Store)
if !ok {
return fmt.Errorf("only sharding of rootmulti.Store type is supported")
}
// handle desired endblock being latest
latest := multistore.LatestVersion()
fmt.Printf("latest height: %d\n", latest)
if endBlock == shardEndBlockLatest {
endBlock = latest
}
shardSize := endBlock - startBlock + 1
// error if requesting block range the database does not have
if endBlock > latest {
return fmt.Errorf("data does not contain end block (%d): latest version is %d", endBlock, latest)
}
fmt.Printf("pruning data in %s down to heights %d - %d (%d blocks)\n", clientCtx.HomeDir, startBlock, endBlock, shardSize)
// set pruning options to prevent no-ops from `PruneStores`
multistore.SetPruning(pruningtypes.PruningOptions{KeepRecent: uint64(shardSize), Interval: 0})
// rollback application state
if err = multistore.RollbackToVersion(endBlock); err != nil {
return fmt.Errorf("failed to rollback application state: %s", err)
}
// open block store & cometbft state
blockStore, stateStore, err := openCometBftDbs(ctx.Config)
if err != nil {
return fmt.Errorf("failed to open cometbft dbs: %s", err)
}
// prep for outputting progress repeatedly to same line
needsRollback := endBlock < latest
progress := "rolling back blockstore & cometbft state to height %d"
numChars := len(fmt.Sprintf(progress, latest))
clearLine := fmt.Sprintf("\r%s\r", strings.Repeat(" ", numChars))
printRollbackProgress := func(h int64) {
fmt.Print(clearLine)
fmt.Printf(progress, h)
}
// rollback tendermint db
height := latest
for height > endBlock {
printRollbackProgress(height - 1)
height, _, err = tmstate.Rollback(blockStore, stateStore, true)
if err != nil {
return fmt.Errorf("failed to rollback tendermint state: %w", err)
}
}
if needsRollback {
fmt.Println()
} else {
fmt.Printf("latest store height is already %d\n", latest)
}
//////////////////////////////
// Prune blocks to startBlock
//////////////////////////////
// enumerate all heights to prune
pruneHeights := make([]int64, 0, latest-shardSize)
for i := int64(1); i < startBlock; i++ {
pruneHeights = append(pruneHeights, i)
}
if len(pruneHeights) > 0 {
// prune application state
fmt.Printf("pruning application state to height %d\n", startBlock)
if err := multistore.PruneStores(true, pruneHeights); err != nil {
return fmt.Errorf("failed to prune application state: %s", err)
}
}
// get starting block of block store
baseBlock := blockStore.Base()
// only prune if data exists, otherwise blockStore.PruneBlocks will panic
if !onlyAppState && baseBlock < startBlock {
// prune block store
fmt.Printf("pruning block store from %d - %d\n", baseBlock, startBlock)
if _, err := blockStore.PruneBlocks(startBlock); err != nil {
return fmt.Errorf("failed to prune block store (retainHeight=%d): %s", startBlock, err)
}
// prune cometbft state
fmt.Printf("pruning cometbft state from %d - %d\n", baseBlock, startBlock)
if err := stateStore.PruneStates(baseBlock, startBlock); err != nil {
return fmt.Errorf("failed to prune cometbft state store (%d - %d): %s", baseBlock, startBlock, err)
}
} else {
fmt.Printf("blockstore and cometbft state begins at block %d\n", baseBlock)
}
// TODO: db compaction
return nil
},
}
cmd.Flags().String(flags.FlagHome, opts.DefaultNodeHome, "The application home directory")
cmd.Flags().Int64(flagShardStartBlock, 1, "Start block of data shard (inclusive)")
cmd.Flags().Int64(flagShardEndBlock, 0, "End block of data shard (inclusive)")
cmd.Flags().Bool(flagShardOnlyAppState, false, "Skip pruning of blockstore & cometbft state")
return cmd
}
// inspired by https://github.com/Kava-Labs/cometbft/blob/277b0853db3f67865a55aa1c54f59790b5f591be/node/node.go#L234
func openCometBftDbs(config *tmconfig.Config) (blockStore *store.BlockStore, stateStore tmstate.Store, err error) {
dbProvider := node.DefaultDBProvider
var blockStoreDB dbm.DB
blockStoreDB, err = dbProvider(&node.DBContext{ID: "blockstore", Config: config})
if err != nil {
return
}
blockStore = store.NewBlockStore(blockStoreDB)
stateDB, err := dbProvider(&node.DBContext{ID: "state", Config: config})
if err != nil {
return
}
stateStore = tmstate.NewStore(stateDB, tmstate.StoreOptions{
DiscardABCIResponses: config.Storage.DiscardABCIResponses,
})
return
}

View File

@ -1,13 +1,13 @@
package cmd package main
import ( import (
"context" "context"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tendermint/tendermint/libs/bytes" "github.com/cometbft/cometbft/libs/bytes"
"github.com/tendermint/tendermint/p2p" "github.com/cometbft/cometbft/p2p"
coretypes "github.com/tendermint/tendermint/rpc/core/types" coretypes "github.com/cometbft/cometbft/rpc/core/types"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/flags"

View File

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
@ -6,7 +6,7 @@ import (
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
) )
// newTxCmd creates all commands for submitting blockchain transactions. // newTxCmd creates all commands for submitting blockchain transactions.

View File

@ -0,0 +1,216 @@
//go:build rocksdb
// +build rocksdb
package rocksdb
import (
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/server"
"github.com/kava-labs/kava/cmd/kava/opendb"
"github.com/linxGnu/grocksdb"
"github.com/spf13/cobra"
"golang.org/x/exp/slices"
"github.com/cometbft/cometbft/libs/log"
)
const (
flagPrintStatsInterval = "print-stats-interval"
)
var allowedDBs = []string{"application", "blockstore", "state"}
func CompactRocksDBCmd() *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf(
"compact <%s>",
strings.Join(allowedDBs, "|"),
),
Short: "force compacts RocksDB",
Long: `This is a utility command that performs a force compaction on the state or
blockstore. This should only be run once the node has stopped.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
statsIntervalStr, err := cmd.Flags().GetString(flagPrintStatsInterval)
if err != nil {
return err
}
statsInterval, err := time.ParseDuration(statsIntervalStr)
if err != nil {
return fmt.Errorf("failed to parse duration for --%s: %w", flagPrintStatsInterval, err)
}
clientCtx := client.GetClientContextFromCmd(cmd)
ctx := server.GetServerContextFromCmd(cmd)
if server.GetAppDBBackend(ctx.Viper) != "rocksdb" {
return errors.New("compaction is currently only supported with rocksdb")
}
if !slices.Contains(allowedDBs, args[0]) {
return fmt.Errorf(
"invalid db name, must be one of the following: %s",
strings.Join(allowedDBs, ", "),
)
}
return compactRocksDBs(clientCtx.HomeDir, logger, args[0], statsInterval)
},
}
cmd.Flags().String(flagPrintStatsInterval, "1m", "duration string for how often to print compaction stats")
return cmd
}
// compactRocksDBs performs a manual compaction on the given db.
func compactRocksDBs(
rootDir string,
logger log.Logger,
dbName string,
statsInterval time.Duration,
) error {
dbPath := filepath.Join(rootDir, "data", dbName+".db")
dbOpts, cfOpts, err := opendb.LoadLatestOptions(dbPath)
if err != nil {
return err
}
logger.Info("opening db", "path", dbPath)
db, _, err := grocksdb.OpenDbColumnFamilies(
dbOpts,
dbPath,
[]string{opendb.DefaultColumnFamilyName},
[]*grocksdb.Options{cfOpts},
)
if err != nil {
return err
}
if err != nil {
logger.Error("failed to initialize cometbft db", "path", dbPath, "err", err)
return fmt.Errorf("failed to open db %s %w", dbPath, err)
}
defer db.Close()
logColumnFamilyMetadata(db, logger)
logger.Info("starting compaction...", "db", dbPath)
done := make(chan bool)
registerSignalHandler(db, logger, done)
startCompactionStatsOutput(db, logger, done, statsInterval)
// Actually run the compaction
db.CompactRange(grocksdb.Range{Start: nil, Limit: nil})
logger.Info("done compaction", "db", dbPath)
done <- true
return nil
}
// bytesToMB converts bytes to megabytes.
func bytesToMB(bytes uint64) float64 {
return float64(bytes) / 1024 / 1024
}
// logColumnFamilyMetadata outputs the column family and level metadata.
func logColumnFamilyMetadata(
db *grocksdb.DB,
logger log.Logger,
) {
metadata := db.GetColumnFamilyMetadata()
logger.Info(
"column family metadata",
"name", metadata.Name(),
"sizeMB", bytesToMB(metadata.Size()),
"fileCount", metadata.FileCount(),
"levels", len(metadata.LevelMetas()),
)
for _, level := range metadata.LevelMetas() {
logger.Info(
fmt.Sprintf("level %d metadata", level.Level()),
"sstMetas", strconv.Itoa(len(level.SstMetas())),
"sizeMB", strconv.FormatFloat(bytesToMB(level.Size()), 'f', 2, 64),
)
}
}
// startCompactionStatsOutput starts a goroutine that outputs compaction stats
// every minute.
func startCompactionStatsOutput(
db *grocksdb.DB,
logger log.Logger,
done chan bool,
statsInterval time.Duration,
) {
go func() {
ticker := time.NewTicker(statsInterval)
isClosed := false
for {
select {
// Make sure we don't try reading from the closed db.
// We continue the loop so that we can make sure the done channel
// does not stall indefinitely from repeated writes and no reader.
case <-done:
logger.Debug("stopping compaction stats output")
isClosed = true
case <-ticker.C:
if !isClosed {
compactionStats := db.GetProperty("rocksdb.stats")
fmt.Printf("%s\n", compactionStats)
}
}
}
}()
}
// registerSignalHandler registers a signal handler that will cancel any running
// compaction when the user presses Ctrl+C.
func registerSignalHandler(
db *grocksdb.DB,
logger log.Logger,
done chan bool,
) {
// https://github.com/facebook/rocksdb/wiki/RocksDB-FAQ
// Q: Can I close the DB when a manual compaction is in progress?
//
// A: No, it's not safe to do that. However, you call
// CancelAllBackgroundWork(db, true) in another thread to abort the
// running compactions, so that you can close the DB sooner. Since
// 6.5, you can also speed it up using
// DB::DisableManualCompaction().
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
for sig := range c {
logger.Info(fmt.Sprintf(
"received %s signal, aborting running compaction... Do NOT kill me before compaction is cancelled. I will exit when compaction is cancelled.",
sig,
))
db.DisableManualCompaction()
logger.Info("manual compaction disabled")
// Stop the logging
done <- true
}
}()
}

View File

@ -0,0 +1,19 @@
//go:build rocksdb
// +build rocksdb
package rocksdb
import (
"github.com/spf13/cobra"
)
// RocksDBCmd defines the root command containing subcommands that assist in
// rocksdb related tasks such as manual compaction.
var RocksDBCmd = &cobra.Command{
Use: "rocksdb",
Short: "RocksDB util commands",
}
func init() {
RocksDBCmd.AddCommand(CompactRocksDBCmd())
}

View File

@ -0,0 +1,14 @@
//go:build !rocksdb
// +build !rocksdb
package rocksdb
import (
"github.com/spf13/cobra"
)
// RocksDBCmd defines the root command when the rocksdb build tag is not set.
var RocksDBCmd = &cobra.Command{
Use: "rocksdb",
Short: "RocksDB util commands, disabled because rocksdb build tag not set",
}

View File

@ -6,8 +6,8 @@ package opendb
import ( import (
"path/filepath" "path/filepath"
dbm "github.com/cometbft/cometbft-db"
"github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/server/types"
dbm "github.com/tendermint/tm-db"
) )
// OpenDB is a copy of default DBOpener function used by ethermint, see for details: // OpenDB is a copy of default DBOpener function used by ethermint, see for details:

View File

@ -29,10 +29,10 @@ import (
"strings" "strings"
"time" "time"
dbm "github.com/cometbft/cometbft-db"
"github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/server/types"
"github.com/linxGnu/grocksdb" "github.com/linxGnu/grocksdb"
"github.com/spf13/cast" "github.com/spf13/cast"
dbm "github.com/tendermint/tm-db"
) )
var ErrUnexpectedConfiguration = errors.New("unexpected rocksdb configuration, rocksdb should have only one column family named default") var ErrUnexpectedConfiguration = errors.New("unexpected rocksdb configuration, rocksdb should have only one column family named default")
@ -41,7 +41,7 @@ const (
// default tm-db block cache size for RocksDB // default tm-db block cache size for RocksDB
defaultBlockCacheSize = 1 << 30 defaultBlockCacheSize = 1 << 30
defaultColumnFamilyName = "default" DefaultColumnFamilyName = "default"
enableMetricsOptName = "rocksdb.enable-metrics" enableMetricsOptName = "rocksdb.enable-metrics"
reportMetricsIntervalSecsOptName = "rocksdb.report-metrics-interval-secs" reportMetricsIntervalSecsOptName = "rocksdb.report-metrics-interval-secs"
@ -91,7 +91,7 @@ func OpenDB(appOpts types.AppOptions, home string, backendType dbm.BackendType)
// option will be overridden only in case if it explicitly specified in appOpts // option will be overridden only in case if it explicitly specified in appOpts
func openRocksdb(dir string, appOpts types.AppOptions) (dbm.DB, error) { func openRocksdb(dir string, appOpts types.AppOptions) (dbm.DB, error) {
optionsPath := filepath.Join(dir, "application.db") optionsPath := filepath.Join(dir, "application.db")
dbOpts, cfOpts, err := loadLatestOptions(optionsPath) dbOpts, cfOpts, err := LoadLatestOptions(optionsPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -112,10 +112,10 @@ func openRocksdb(dir string, appOpts types.AppOptions) (dbm.DB, error) {
return newRocksDBWithOptions("application", dir, dbOpts, cfOpts, readOpts, enableMetrics, reportMetricsIntervalSecs) return newRocksDBWithOptions("application", dir, dbOpts, cfOpts, readOpts, enableMetrics, reportMetricsIntervalSecs)
} }
// loadLatestOptions loads and returns database and column family options // LoadLatestOptions loads and returns database and column family options
// if options file not found, it means database isn't created yet, in such case default tm-db options will be returned // if options file not found, it means database isn't created yet, in such case default tm-db options will be returned
// if database exists it should have only one column family named default // if database exists it should have only one column family named default
func loadLatestOptions(dir string) (*grocksdb.Options, *grocksdb.Options, error) { func LoadLatestOptions(dir string) (*grocksdb.Options, *grocksdb.Options, error) {
latestOpts, err := grocksdb.LoadLatestOptions(dir, grocksdb.NewDefaultEnv(), true, grocksdb.NewLRUCache(defaultBlockCacheSize)) latestOpts, err := grocksdb.LoadLatestOptions(dir, grocksdb.NewDefaultEnv(), true, grocksdb.NewLRUCache(defaultBlockCacheSize))
if err != nil && strings.HasPrefix(err.Error(), "NotFound: ") { if err != nil && strings.HasPrefix(err.Error(), "NotFound: ") {
return newDefaultOptions(), newDefaultOptions(), nil return newDefaultOptions(), newDefaultOptions(), nil
@ -127,7 +127,7 @@ func loadLatestOptions(dir string) (*grocksdb.Options, *grocksdb.Options, error)
cfNames := latestOpts.ColumnFamilyNames() cfNames := latestOpts.ColumnFamilyNames()
cfOpts := latestOpts.ColumnFamilyOpts() cfOpts := latestOpts.ColumnFamilyOpts()
// db should have only one column family named default // db should have only one column family named default
ok := len(cfNames) == 1 && cfNames[0] == defaultColumnFamilyName ok := len(cfNames) == 1 && cfNames[0] == DefaultColumnFamilyName
if !ok { if !ok {
return nil, nil, ErrUnexpectedConfiguration return nil, nil, ErrUnexpectedConfiguration
} }
@ -312,7 +312,7 @@ func newRocksDBWithOptions(
dbOpts.EnableStatistics() dbOpts.EnableStatistics()
} }
db, _, err := grocksdb.OpenDbColumnFamilies(dbOpts, dbPath, []string{defaultColumnFamilyName}, []*grocksdb.Options{cfOpts}) db, _, err := grocksdb.OpenDbColumnFamilies(dbOpts, dbPath, []string{DefaultColumnFamilyName}, []*grocksdb.Options{cfOpts})
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -83,7 +83,7 @@ func TestOpenRocksdb(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, db.Close()) require.NoError(t, db.Close())
dbOpts, cfOpts, err := loadLatestOptions(filepath.Join(dir, "application.db")) dbOpts, cfOpts, err := LoadLatestOptions(filepath.Join(dir, "application.db"))
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, tc.maxOpenFiles, dbOpts.GetMaxOpenFiles()) require.Equal(t, tc.maxOpenFiles, dbOpts.GetMaxOpenFiles())
require.Equal(t, tc.maxFileOpeningThreads, dbOpts.GetMaxFileOpeningThreads()) require.Equal(t, tc.maxFileOpeningThreads, dbOpts.GetMaxFileOpeningThreads())
@ -108,7 +108,7 @@ func TestOpenRocksdb(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, db.Close()) require.NoError(t, db.Close())
dbOpts, cfOpts, err := loadLatestOptions(filepath.Join(dir, "application.db")) dbOpts, cfOpts, err := LoadLatestOptions(filepath.Join(dir, "application.db"))
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, defaultOpts.GetMaxOpenFiles(), dbOpts.GetMaxOpenFiles()) require.Equal(t, defaultOpts.GetMaxOpenFiles(), dbOpts.GetMaxOpenFiles())
require.Equal(t, defaultOpts.GetMaxFileOpeningThreads(), dbOpts.GetMaxFileOpeningThreads()) require.Equal(t, defaultOpts.GetMaxFileOpeningThreads(), dbOpts.GetMaxFileOpeningThreads())
@ -190,7 +190,7 @@ func TestLoadLatestOptions(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, db.Close()) require.NoError(t, db.Close())
dbOpts, cfOpts, err := loadLatestOptions(filepath.Join(dir, "application.db")) dbOpts, cfOpts, err := LoadLatestOptions(filepath.Join(dir, "application.db"))
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, tc.maxOpenFiles, dbOpts.GetMaxOpenFiles()) require.Equal(t, tc.maxOpenFiles, dbOpts.GetMaxOpenFiles())
require.Equal(t, tc.maxFileOpeningThreads, dbOpts.GetMaxFileOpeningThreads()) require.Equal(t, tc.maxFileOpeningThreads, dbOpts.GetMaxFileOpeningThreads())
@ -210,7 +210,7 @@ func TestLoadLatestOptions(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
}() }()
dbOpts, cfOpts, err := loadLatestOptions(filepath.Join(dir, "application.db")) dbOpts, cfOpts, err := LoadLatestOptions(filepath.Join(dir, "application.db"))
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, defaultOpts.GetMaxOpenFiles(), dbOpts.GetMaxOpenFiles()) require.Equal(t, defaultOpts.GetMaxOpenFiles(), dbOpts.GetMaxOpenFiles())
require.Equal(t, defaultOpts.GetMaxFileOpeningThreads(), dbOpts.GetMaxFileOpeningThreads()) require.Equal(t, defaultOpts.GetMaxFileOpeningThreads(), dbOpts.GetMaxFileOpeningThreads())
@ -368,7 +368,7 @@ func TestNewRocksDBWithOptions(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, db.Close()) require.NoError(t, db.Close())
dbOpts, cfOpts, err = loadLatestOptions(filepath.Join(dir, "application.db")) dbOpts, cfOpts, err = LoadLatestOptions(filepath.Join(dir, "application.db"))
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, 999, dbOpts.GetMaxOpenFiles()) require.Equal(t, 999, dbOpts.GetMaxOpenFiles())
require.Equal(t, defaultOpts.GetMaxFileOpeningThreads(), dbOpts.GetMaxFileOpeningThreads()) require.Equal(t, defaultOpts.GetMaxFileOpeningThreads(), dbOpts.GetMaxFileOpeningThreads())

View File

@ -4,11 +4,11 @@ pragma solidity ^0.8.18;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/Ownable.sol";
/// @title An ERC20 token contract owned and deployed by the evmutil module of Kava. /// @title An ERC20 token contract owned and deployed by the evmutil module of 0g-chain.
/// Tokens are backed one-for-one by cosmos-sdk coins held in the module account. /// Tokens are backed one-for-one by cosmos-sdk coins held in the module account.
/// @author Kava Labs, LLC /// @author 0g Labs, LLC
/// @custom:security-contact security@kava.io /// @custom:security-contact security@0g.ai
contract ERC20KavaWrappedCosmosCoin is ERC20, Ownable { contract ERC20ZgChainWrappedCosmosCoin is ERC20, Ownable {
/// @notice The decimals places of the token. For display purposes only. /// @notice The decimals places of the token. For display purposes only.
uint8 private immutable _decimals; uint8 private immutable _decimals;

View File

@ -5,7 +5,7 @@ const config: HardhatUserConfig = {
solidity: { solidity: {
version: "0.8.18", version: "0.8.18",
settings: { settings: {
// istanbul upgrade occurred before the london hardfork, so is compatible with kava's evm // istanbul upgrade occurred before the london hardfork, so is compatible with 0g-chain's evm
evmVersion: "istanbul", evmVersion: "istanbul",
// optimize build for deployment to mainnet! // optimize build for deployment to mainnet!
optimizer: { optimizer: {
@ -16,21 +16,21 @@ const config: HardhatUserConfig = {
}, },
networks: { networks: {
// kvtool's local network // kvtool's local network
kava: { chain: {
url: "http://127.0.0.1:8545", url: "http://127.0.0.1:8545",
accounts: [ accounts: [
// kava keys unsafe-export-eth-key whale2 // 0g-chain keys unsafe-export-eth-key whale2
"AA50F4C6C15190D9E18BF8B14FC09BFBA0E7306331A4F232D10A77C2879E7966", "AA50F4C6C15190D9E18BF8B14FC09BFBA0E7306331A4F232D10A77C2879E7966",
], ],
}, },
protonet: { protonet: {
url: "https://evm.app.protonet.us-east.production.kava.io:443", url: "https://evm.app.protonet.us-east.production.0g-chain.io:443",
accounts: [ accounts: [
"247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9", "247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9",
], ],
}, },
internal_testnet: { internal_testnet: {
url: "https://evm.data.internal.testnet.us-east.production.kava.io:443", url: "https://evm.data.internal.testnet.us-east.production.0g-chain.io:443",
accounts: [ accounts: [
"247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9", "247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9",
], ],

View File

@ -1,11 +1,11 @@
{ {
"name": "kava-contracts", "name": "0g-chain-contracts",
"version": "0.0.1", "version": "0.0.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "kava-contracts", "name": "0g-chain-contracts",
"version": "0.0.1", "version": "0.0.1",
"devDependencies": { "devDependencies": {
"@nomicfoundation/hardhat-toolbox": "^2.0.2", "@nomicfoundation/hardhat-toolbox": "^2.0.2",

View File

@ -1,9 +1,9 @@
{ {
"name": "kava-contracts", "name": "0g-chain-contracts",
"version": "0.0.1", "version": "0.0.1",
"author": "Kava Labs", "author": "0g Labs",
"private": true, "private": true,
"description": "Solidity contracts for Kava Blockchain", "description": "Solidity contracts for 0g Blockchain",
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=18.0.0"
}, },
@ -12,7 +12,7 @@
"clean": "hardhat clean", "clean": "hardhat clean",
"compile": "hardhat compile", "compile": "hardhat compile",
"coverage": "hardhat coverage", "coverage": "hardhat coverage",
"ethermint-json": "jq '{ abi: .abi | tostring, bin: .bytecode | ltrimstr(\"0x\")}' artifacts/contracts/ERC20KavaWrappedCosmosCoin.sol/ERC20KavaWrappedCosmosCoin.json > ../x/evmutil/types/ethermint_json/ERC20KavaWrappedCosmosCoin.json", "ethermint-json": "jq '{ abi: .abi | tostring, bin: .bytecode | ltrimstr(\"0x\")}' artifacts/contracts/ERC20ZgChainWrappedCosmosCoin.sol/ERC20ZgChainWrappedCosmosCoin.json > ../x/evmutil/types/ethermint_json/ERC20ZgChainWrappedCosmosCoin.json",
"gen-ts-types": "hardhat typechain", "gen-ts-types": "hardhat typechain",
"lint": "eslint '**/*.{js,ts}'", "lint": "eslint '**/*.{js,ts}'",
"lint-fix": "eslint '**/*.{js,ts}' --fix", "lint-fix": "eslint '**/*.{js,ts}' --fix",

View File

@ -1,14 +1,14 @@
import { ethers } from "hardhat"; import { ethers } from "hardhat";
async function main() { async function main() {
const tokenName = "Kava-wrapped ATOM"; const tokenName = "0g-chain-wrapped ATOM";
const tokenSymbol = "kATOM"; const tokenSymbol = "kATOM";
const tokenDecimals = 6; const tokenDecimals = 6;
const ERC20KavaWrappedCosmosCoin = await ethers.getContractFactory( const ERC20ZgChainWrappedCosmosCoin = await ethers.getContractFactory(
"ERC20KavaWrappedCosmosCoin" "ERC20ZgChainWrappedCosmosCoin"
); );
const token = await ERC20KavaWrappedCosmosCoin.deploy( const token = await ERC20ZgChainWrappedCosmosCoin.deploy(
tokenName, tokenName,
tokenSymbol, tokenSymbol,
tokenDecimals tokenDecimals

View File

@ -2,21 +2,21 @@ import { expect } from "chai";
import { Signer } from "ethers"; import { Signer } from "ethers";
import { ethers } from "hardhat"; import { ethers } from "hardhat";
import { import {
ERC20KavaWrappedCosmosCoin, ERC20ZgChainWrappedCosmosCoin,
ERC20KavaWrappedCosmosCoin__factory as ERC20KavaWrappedCosmosCoinFactory, ERC20ZgChainWrappedCosmosCoin__factory as ERC20ZgChainWrappedCosmosCoinFactory,
} from "../typechain-types"; } from "../typechain-types";
const decimals = 6n; const decimals = 6n;
describe("ERC20KavaWrappedCosmosCoin", function () { describe("ERC20ZgChainWrappedCosmosCoin", function () {
let erc20: ERC20KavaWrappedCosmosCoin; let erc20: ERC20ZgChainWrappedCosmosCoin;
let erc20Factory: ERC20KavaWrappedCosmosCoinFactory; let erc20Factory: ERC20ZgChainWrappedCosmosCoinFactory;
let owner: Signer; let owner: Signer;
let sender: Signer; let sender: Signer;
beforeEach(async function () { beforeEach(async function () {
erc20Factory = await ethers.getContractFactory( erc20Factory = await ethers.getContractFactory(
"ERC20KavaWrappedCosmosCoin" "ERC20ZgChainWrappedCosmosCoin"
); );
erc20 = await erc20Factory.deploy("Wrapped ATOM", "ATOM", decimals); erc20 = await erc20Factory.deploy("Wrapped ATOM", "ATOM", decimals);
[owner, sender] = await ethers.getSigners(); [owner, sender] = await ethers.getSigners();

View File

@ -0,0 +1,166 @@
package bn254util
import (
"math/big"
"github.com/consensys/gnark-crypto/ecc/bn254"
"github.com/consensys/gnark-crypto/ecc/bn254/fp"
"github.com/consensys/gnark-crypto/ecc/bn254/fr"
"github.com/ethereum/go-ethereum/crypto"
)
const (
G1PointSize = 32 * 2
G2PointSize = 32 * 2 * 2
)
var (
FR_MODULUS, _ = new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
)
func VerifySig(sig *bn254.G1Affine, pubkey *bn254.G2Affine, msgBytes [32]byte) (bool, error) {
g2Gen := GetG2Generator()
msgPoint := MapToCurve(msgBytes)
var negSig bn254.G1Affine
negSig.Neg((*bn254.G1Affine)(sig))
P := [2]bn254.G1Affine{*msgPoint, negSig}
Q := [2]bn254.G2Affine{*pubkey, *g2Gen}
ok, err := bn254.PairingCheck(P[:], Q[:])
if err != nil {
return false, nil
}
return ok, nil
}
func MapToCurve(digest [32]byte) *bn254.G1Affine {
one := new(big.Int).SetUint64(1)
three := new(big.Int).SetUint64(3)
x := new(big.Int)
x.SetBytes(digest[:])
for {
// y = x^3 + 3
xP3 := new(big.Int).Exp(x, big.NewInt(3), fp.Modulus())
y := new(big.Int).Add(xP3, three)
y.Mod(y, fp.Modulus())
if y.ModSqrt(y, fp.Modulus()) == nil {
x.Add(x, one).Mod(x, fp.Modulus())
} else {
var fpX, fpY fp.Element
fpX.SetBigInt(x)
fpY.SetBigInt(y)
return &bn254.G1Affine{
X: fpX,
Y: fpY,
}
}
}
}
func CheckG1AndG2DiscreteLogEquality(pointG1 *bn254.G1Affine, pointG2 *bn254.G2Affine) (bool, error) {
negGenG1 := new(bn254.G1Affine).Neg(GetG1Generator())
return bn254.PairingCheck([]bn254.G1Affine{*pointG1, *negGenG1}, []bn254.G2Affine{*GetG2Generator(), *pointG2})
}
func GetG1Generator() *bn254.G1Affine {
g1Gen := new(bn254.G1Affine)
_, err := g1Gen.X.SetString("1")
if err != nil {
return nil
}
_, err = g1Gen.Y.SetString("2")
if err != nil {
return nil
}
return g1Gen
}
func GetG2Generator() *bn254.G2Affine {
g2Gen := new(bn254.G2Affine)
g2Gen.X.SetString("10857046999023057135944570762232829481370756359578518086990519993285655852781",
"11559732032986387107991004021392285783925812861821192530917403151452391805634")
g2Gen.Y.SetString("8495653923123431417604973247489272438418190587263600148770280649306958101930",
"4082367875863433681332203403145435568316851327593401208105741076214120093531")
return g2Gen
}
func MulByGeneratorG1(a *fr.Element) *bn254.G1Affine {
g1Gen := GetG1Generator()
return new(bn254.G1Affine).ScalarMultiplication(g1Gen, a.BigInt(new(big.Int)))
}
func MulByGeneratorG2(a *fr.Element) *bn254.G2Affine {
g2Gen := GetG2Generator()
return new(bn254.G2Affine).ScalarMultiplication(g2Gen, a.BigInt(new(big.Int)))
}
func SerializeG1(p *bn254.G1Affine) []byte {
b := make([]byte, 0)
tmp := p.X.Bytes()
for i := 0; i < 32; i++ {
b = append(b, tmp[i])
}
tmp = p.Y.Bytes()
for i := 0; i < 32; i++ {
b = append(b, tmp[i])
}
return b
}
func DeserializeG1(b []byte) *bn254.G1Affine {
p := new(bn254.G1Affine)
p.X.SetBytes(b[0:32])
p.Y.SetBytes(b[32:64])
return p
}
func SerializeG2(p *bn254.G2Affine) []byte {
b := make([]byte, 0)
tmp := p.X.A0.Bytes()
for i := 0; i < 32; i++ {
b = append(b, tmp[i])
}
tmp = p.X.A1.Bytes()
for i := 0; i < 32; i++ {
b = append(b, tmp[i])
}
tmp = p.Y.A0.Bytes()
for i := 0; i < 32; i++ {
b = append(b, tmp[i])
}
tmp = p.Y.A1.Bytes()
for i := 0; i < 32; i++ {
b = append(b, tmp[i])
}
return b
}
func DeserializeG2(b []byte) *bn254.G2Affine {
p := new(bn254.G2Affine)
p.X.A0.SetBytes(b[0:32])
p.X.A1.SetBytes(b[32:64])
p.Y.A0.SetBytes(b[64:96])
p.Y.A1.SetBytes(b[96:128])
return p
}
func Gamma(hash *bn254.G1Affine, signature *bn254.G1Affine, pkG1 *bn254.G1Affine, pkG2 *bn254.G2Affine) *big.Int {
toHash := make([]byte, 0)
toHash = append(toHash, SerializeG1(hash)...)
toHash = append(toHash, SerializeG1(signature)...)
toHash = append(toHash, SerializeG1(pkG1)...)
toHash = append(toHash, SerializeG2(pkG2)...)
msgHash := crypto.Keccak256(toHash)
gamma := new(big.Int)
gamma.SetBytes(msgHash)
gamma.Mod(gamma, FR_MODULUS)
return gamma
}

58
crypto/vrf/algorithm.go Normal file
View File

@ -0,0 +1,58 @@
package vrf
import (
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
)
var (
// SupportedAlgorithms defines the list of signing algorithms used on Evmos:
// - eth_secp256k1 (Ethereum)
// - secp256k1 (Tendermint)
SupportedAlgorithms = keyring.SigningAlgoList{VrfAlgo}
// SupportedAlgorithmsLedger defines the list of signing algorithms used on Evmos for the Ledger device:
// - eth_secp256k1 (Ethereum)
// - secp256k1 (Tendermint)
SupportedAlgorithmsLedger = keyring.SigningAlgoList{VrfAlgo}
)
func VrfOption() keyring.Option {
return func(options *keyring.Options) {
options.SupportedAlgos = SupportedAlgorithms
options.SupportedAlgosLedger = SupportedAlgorithmsLedger
}
}
const (
VrfType = hd.PubKeyType(KeyType)
)
var (
_ keyring.SignatureAlgo = VrfAlgo
VrfAlgo = vrfAlgo{}
)
type vrfAlgo struct{}
func (s vrfAlgo) Name() hd.PubKeyType {
return VrfType
}
func (s vrfAlgo) Derive() hd.DeriveFn {
return func(mnemonic, bip39Passphrase, path string) ([]byte, error) {
key, err := GenerateKey()
if err != nil {
return nil, err
}
return key.Bytes(), nil
}
}
func (s vrfAlgo) Generate() hd.GenerateFn {
return func(bz []byte) cryptotypes.PrivKey {
key, _ := GenerateKey()
return key
}
}

496
crypto/vrf/keys.pb.go Normal file
View File

@ -0,0 +1,496 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: crypto/vrf/keys.proto
package vrf
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// PubKey defines a type alias for an vrf.PublicKey that implements
// Vrf's PubKey interface. It represents the 32-byte compressed public
// key format.
type PubKey struct {
// key is the public key in byte form
Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *PubKey) Reset() { *m = PubKey{} }
func (*PubKey) ProtoMessage() {}
func (*PubKey) Descriptor() ([]byte, []int) {
return fileDescriptor_eae59d1af27f5957, []int{0}
}
func (m *PubKey) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PubKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PubKey.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 *PubKey) XXX_Merge(src proto.Message) {
xxx_messageInfo_PubKey.Merge(m, src)
}
func (m *PubKey) XXX_Size() int {
return m.Size()
}
func (m *PubKey) XXX_DiscardUnknown() {
xxx_messageInfo_PubKey.DiscardUnknown(m)
}
var xxx_messageInfo_PubKey proto.InternalMessageInfo
func (m *PubKey) GetKey() []byte {
if m != nil {
return m.Key
}
return nil
}
// PrivKey defines a type alias for an vrf.PrivateKey that implements
// Vrf's PrivateKey interface.
type PrivKey struct {
// key is the private key in byte form
Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *PrivKey) Reset() { *m = PrivKey{} }
func (m *PrivKey) String() string { return proto.CompactTextString(m) }
func (*PrivKey) ProtoMessage() {}
func (*PrivKey) Descriptor() ([]byte, []int) {
return fileDescriptor_eae59d1af27f5957, []int{1}
}
func (m *PrivKey) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PrivKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PrivKey.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 *PrivKey) XXX_Merge(src proto.Message) {
xxx_messageInfo_PrivKey.Merge(m, src)
}
func (m *PrivKey) XXX_Size() int {
return m.Size()
}
func (m *PrivKey) XXX_DiscardUnknown() {
xxx_messageInfo_PrivKey.DiscardUnknown(m)
}
var xxx_messageInfo_PrivKey proto.InternalMessageInfo
func (m *PrivKey) GetKey() []byte {
if m != nil {
return m.Key
}
return nil
}
func init() {
proto.RegisterType((*PubKey)(nil), "crypto.vrf.PubKey")
proto.RegisterType((*PrivKey)(nil), "crypto.vrf.PrivKey")
}
func init() { proto.RegisterFile("crypto/vrf/keys.proto", fileDescriptor_eae59d1af27f5957) }
var fileDescriptor_eae59d1af27f5957 = []byte{
// 174 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x2e, 0xaa, 0x2c,
0x28, 0xc9, 0xd7, 0x2f, 0x2b, 0x4a, 0xd3, 0xcf, 0x4e, 0xad, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f,
0xc9, 0x17, 0xe2, 0x82, 0x08, 0xeb, 0x95, 0x15, 0xa5, 0x49, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83,
0x85, 0xf5, 0x41, 0x2c, 0x88, 0x0a, 0x25, 0x05, 0x2e, 0xb6, 0x80, 0xd2, 0x24, 0xef, 0xd4, 0x4a,
0x21, 0x01, 0x2e, 0xe6, 0xec, 0xd4, 0x4a, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x9e, 0x20, 0x10, 0xd3,
0x8a, 0x65, 0xc6, 0x02, 0x79, 0x06, 0x25, 0x69, 0x2e, 0xf6, 0x80, 0xa2, 0xcc, 0x32, 0xac, 0x4a,
0x9c, 0xec, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09,
0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x35, 0x3d, 0xb3,
0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0x20, 0x3d, 0x27, 0x31, 0xa9, 0x58, 0xdf,
0x20, 0x5d, 0x37, 0x39, 0x23, 0x31, 0x33, 0x4f, 0x1f, 0xe1, 0xd8, 0x24, 0x36, 0xb0, 0x33, 0x8c,
0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xdb, 0xb8, 0x32, 0x07, 0xc1, 0x00, 0x00, 0x00,
}
func (m *PubKey) 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 *PubKey) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PubKey) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintKeys(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *PrivKey) 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 *PrivKey) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PrivKey) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintKeys(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintKeys(dAtA []byte, offset int, v uint64) int {
offset -= sovKeys(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *PubKey) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
if l > 0 {
n += 1 + l + sovKeys(uint64(l))
}
return n
}
func (m *PrivKey) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
if l > 0 {
n += 1 + l + sovKeys(uint64(l))
}
return n
}
func sovKeys(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozKeys(x uint64) (n int) {
return sovKeys(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *PubKey) 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 ErrIntOverflowKeys
}
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: PubKey: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PubKey: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowKeys
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthKeys
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthKeys
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
if m.Key == nil {
m.Key = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipKeys(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthKeys
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *PrivKey) 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 ErrIntOverflowKeys
}
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: PrivKey: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PrivKey: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowKeys
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthKeys
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthKeys
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
if m.Key == nil {
m.Key = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipKeys(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthKeys
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipKeys(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, ErrIntOverflowKeys
}
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, ErrIntOverflowKeys
}
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, ErrIntOverflowKeys
}
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, ErrInvalidLengthKeys
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupKeys
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthKeys
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthKeys = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowKeys = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupKeys = fmt.Errorf("proto: unexpected end of group")
)

194
crypto/vrf/vrf.go Normal file
View File

@ -0,0 +1,194 @@
package vrf
import (
"bytes"
"crypto/subtle"
"fmt"
errorsmod "cosmossdk.io/errors"
vrfalgo "github.com/coniks-sys/coniks-go/crypto/vrf"
"github.com/cosmos/cosmos-sdk/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
errortypes "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/ethereum/go-ethereum/common"
tmcrypto "github.com/tendermint/tendermint/crypto"
)
const (
// PrivKeySize defines the size of the PrivKey bytes
PrivKeySize = 64
// PubKeySize defines the size of the PubKey bytes
PubKeySize = 32
// KeyType is the string constant for the vrf algorithm
KeyType = "vrf"
)
// Amino encoding names
const (
// PrivKeyName defines the amino encoding name for the vrf private key
PrivKeyName = "vrf/PrivKey"
// PubKeyName defines the amino encoding name for the vrf public key
PubKeyName = "vrf/PubKey"
)
// ----------------------------------------------------------------------------
// vrf Private Key
var (
_ cryptotypes.PrivKey = &PrivKey{}
_ codec.AminoMarshaler = &PrivKey{}
)
// GenerateKey generates a new random private key. It returns an error upon
// failure.
func GenerateKey() (*PrivKey, error) {
priv, err := vrfalgo.GenerateKey(nil)
if err != nil {
return nil, err
}
return &PrivKey{
Key: priv,
}, nil
}
func (privKey PrivKey) getVrfPrivateKey() vrfalgo.PrivateKey {
return vrfalgo.PrivateKey(privKey.Key)
}
// Bytes returns the byte representation of the Private Key.
func (privKey PrivKey) Bytes() []byte {
bz := make([]byte, len(privKey.Key))
copy(bz, privKey.Key)
return bz
}
// PubKey returns the private key's public key. If the privkey is not valid
// it returns a nil value.
func (privKey PrivKey) PubKey() cryptotypes.PubKey {
pk, _ := vrfalgo.PrivateKey(privKey.Key).Public()
return &PubKey{
Key: pk,
}
}
// Equals returns true if two private keys are equal and false otherwise.
func (privKey PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool {
return privKey.Type() == other.Type() && subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1
}
// Type returns vrf
func (privKey PrivKey) Type() string {
return KeyType
}
// Compute generates the vrf value for the byte slice m using the
// underlying private key sk.
func (privKey PrivKey) Sign(digestBz []byte) ([]byte, error) {
sk := privKey.getVrfPrivateKey()
return sk.Compute(digestBz), nil
}
// MarshalAmino overrides Amino binary marshaling.
func (privKey PrivKey) MarshalAmino() ([]byte, error) {
return privKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshaling.
func (privKey *PrivKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PrivKeySize {
return fmt.Errorf("invalid privkey size, expected %d got %d", PrivKeySize, len(bz))
}
privKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshaling.
func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return privKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshaling.
func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error {
return privKey.UnmarshalAmino(bz)
}
// ----------------------------------------------------------------------------
// vrf Public Key
var (
_ cryptotypes.PubKey = &PubKey{}
_ codec.AminoMarshaler = &PubKey{}
)
// func (pubKey PubKey) getVrfPublicKey() vrfalgo.PublicKey {
// return vrfalgo.PublicKey(pubKey.Key)
// }
// Address returns the address of the ECDSA public key.
// The function will return an empty address if the public key is invalid.
func (pubKey PubKey) Address() tmcrypto.Address {
return tmcrypto.Address(common.BytesToAddress(pubKey.Key).Bytes())
}
// Bytes returns the raw bytes of the ECDSA public key.
func (pubKey PubKey) Bytes() []byte {
bz := make([]byte, len(pubKey.Key))
copy(bz, pubKey.Key)
return bz
}
// String implements the fmt.Stringer interface.
func (pubKey PubKey) String() string {
return fmt.Sprintf("vrf{%X}", pubKey.Key)
}
// Type returns vrf
func (pubKey PubKey) Type() string {
return KeyType
}
// Equals returns true if the pubkey type is the same and their bytes are deeply equal.
func (pubKey PubKey) Equals(other cryptotypes.PubKey) bool {
return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes())
}
// Verify returns true iff vrf=Compute(m) for the sk that
// corresponds to pk.
func (pubKey PubKey) VerifySignature(msg, sig []byte) bool {
panic("not implement")
}
// MarshalAmino overrides Amino binary marshaling.
func (pubKey PubKey) MarshalAmino() ([]byte, error) {
return pubKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshaling.
func (pubKey *PubKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PubKeySize {
return errorsmod.Wrapf(errortypes.ErrInvalidPubKey, "invalid pubkey size, expected %d, got %d", PubKeySize, len(bz))
}
pubKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshaling.
func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return pubKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshaling.
func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error {
return pubKey.UnmarshalAmino(bz)
}

96
crypto/vrf/vrf_test.go Normal file
View File

@ -0,0 +1,96 @@
package vrf
import (
"testing"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"encoding/base64"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
)
func TestPrivKey(t *testing.T) {
// validate type and equality
privKey, err := GenerateKey()
require.NoError(t, err)
require.Implements(t, (*cryptotypes.PrivKey)(nil), privKey)
// validate inequality
privKey2, err := GenerateKey()
require.NoError(t, err)
require.False(t, privKey.Equals(privKey2))
}
func TestPrivKey_PubKey(t *testing.T) {
privKey, err := GenerateKey()
require.NoError(t, err)
// validate type and equality
pubKey := &PubKey{
Key: privKey.PubKey().Bytes(),
}
require.Implements(t, (*cryptotypes.PubKey)(nil), pubKey)
// validate inequality
privKey2, err := GenerateKey()
require.NoError(t, err)
require.False(t, pubKey.Equals(privKey2.PubKey()))
}
func TestMarshalAmino(t *testing.T) {
aminoCdc := codec.NewLegacyAmino()
privKey, err := GenerateKey()
require.NoError(t, err)
pubKey := privKey.PubKey().(*PubKey)
testCases := []struct {
desc string
msg codec.AminoMarshaler
typ interface{}
expBinary []byte
expJSON string
}{
{
"vrf private key",
privKey,
&PrivKey{},
append([]byte{64}, privKey.Bytes()...), // Length-prefixed.
"\"" + base64.StdEncoding.EncodeToString(privKey.Bytes()) + "\"",
},
{
"vrf public key",
pubKey,
&PubKey{},
append([]byte{32}, pubKey.Bytes()...), // Length-prefixed.
"\"" + base64.StdEncoding.EncodeToString(pubKey.Bytes()) + "\"",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Do a round trip of encoding/decoding binary.
bz, err := aminoCdc.Marshal(tc.msg)
require.NoError(t, err)
require.Equal(t, tc.expBinary, bz)
err = aminoCdc.Unmarshal(bz, tc.typ)
require.NoError(t, err)
require.Equal(t, tc.msg, tc.typ)
// Do a round trip of encoding/decoding JSON.
bz, err = aminoCdc.MarshalJSON(tc.msg)
require.NoError(t, err)
require.Equal(t, tc.expJSON, string(bz))
err = aminoCdc.UnmarshalJSON(bz, tc.typ)
require.NoError(t, err)
require.Equal(t, tc.msg, tc.typ)
})
}
}

View File

@ -3,7 +3,7 @@ version: '3'
services: services:
kvdnode0: kvdnode0:
container_name: kvdnode0 container_name: kvdnode0
image: "kava/kavanode" image: "0glabs/0g-chain-node"
ports: ports:
- "26656-26657:26656-26657" - "26656-26657:26656-26657"
environment: environment:
@ -17,7 +17,7 @@ services:
kvdnode1: kvdnode1:
container_name: kvdnode1 container_name: kvdnode1
image: "kava/kavanode" image: "0glabs/0g-chain-node"
ports: ports:
- "26659-26660:26656-26657" - "26659-26660:26656-26657"
environment: environment:
@ -31,7 +31,7 @@ services:
kvdnode2: kvdnode2:
container_name: kvdnode2 container_name: kvdnode2
image: "kava/kavanode" image: "0glabs/0g-chain-node"
environment: environment:
- ID=2 - ID=2
- LOG=${LOG:-kvd.log} - LOG=${LOG:-kvd.log}
@ -45,7 +45,7 @@ services:
kvdnode3: kvdnode3:
container_name: kvdnode3 container_name: kvdnode3
image: "kava/kavanode" image: "0glabs/0g-chain-node"
environment: environment:
- ID=3 - ID=3
- LOG=${LOG:-kvd.log} - LOG=${LOG:-kvd.log}

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