Compare commits

...

103 Commits

Author SHA1 Message Date
0g-wh
a58ed51deb clean code
Some checks are pending
Continuous Integration (Commit) / lint (push) Waiting to run
2024-08-02 19:32:45 +08:00
0g-wh
966420cc90 tidy 2024-08-02 19:26:51 +08:00
0g-wh
4121f95973 rename 2024-08-02 19:26:51 +08:00
0g-wh
f6028bff0d rename 2024-08-02 19:26:51 +08:00
0g-wh
a45aa46dbc rebase to kava cosmos 0.47 upgrade 2024-08-02 19:26:51 +08:00
0g-wh
1342ff0f9a add Upload Release Assets workflow (#49)
* Create upload-release-assets.yml
2024-08-02 19:26:51 +08:00
Solovyov1796
fbbbde9c49 update gitignore 2024-08-02 19:26:51 +08:00
Solovyov1796
d0af500cf1 merge testnet script 2024-08-02 19:26:51 +08:00
0g-wh
db09ebf9dc add cosmovisor init script 2024-08-02 19:26:51 +08:00
Solovyov1796
733b716885 use 0glabs' cometbft 2024-08-02 19:26:51 +08:00
0xsatoshi
9ef6e85f10 enable vesting msgs 2024-08-02 19:26:51 +08:00
0xsatoshi
5a9f50dda5 fix 2024-08-02 19:26:51 +08:00
0xsatoshi
11893c9200 fix 2024-08-02 19:26:51 +08:00
MiniFrenchBread
6005142a4d refactor: epoch quorum storage 2024-08-02 19:26:51 +08:00
MiniFrenchBread
fe08e9f941 feat: getQuorumRow 2024-08-02 19:26:51 +08:00
Solovyov1796
cc8a3f864f keep the EthSecp256k1 from cosmos for compatible 2024-08-02 19:26:51 +08:00
Solovyov1796
da1d8433fb recover "rename denoms" in 3 files 2024-08-02 19:26:51 +08:00
Solovyov1796
9f39e3a91e use chaincfg.MakeCoinForGasDenom 2024-08-02 19:26:51 +08:00
Solovyov1796
19c0a9b852 custom inflation calculation function 2024-08-02 19:26:51 +08:00
MiniFrenchBread
ad586c949e chore: remove tmp output 2024-08-02 19:26:51 +08:00
MiniFrenchBread
d4b3d064db fix: decimals 2024-08-02 19:26:51 +08:00
MiniFrenchBread
22077a98ca refactor: delegator 2024-08-02 19:26:51 +08:00
MiniFrenchBread
b62eea0798 fix: localtestnet.sh 2024-08-02 19:26:51 +08:00
MiniFrenchBread
d99f176518 tidy 2024-08-02 19:26:51 +08:00
MiniFrenchBread
f96fee6c2e merge testnet/v0.1.x 2024-08-02 19:26:50 +08:00
Solovyov1796
6de8deb115 remove the EthSecp256k1 from cosmos 2024-08-02 19:26:50 +08:00
Solovyov1796
1f905244da rename denoms 2024-08-02 19:26:50 +08:00
Solovyov1796
35de15eef8 fix unit test 2024-08-02 19:26:50 +08:00
Solovyov1796
a67af32108 remove module's legacy code 2024-08-02 19:26:50 +08:00
Solovyov1796
6552ee28bc recover go mod file 2024-08-02 19:26:50 +08:00
Solovyov1796
4648f7643e remove das module 2024-08-02 19:26:50 +08:00
MiniFrenchBread
883d401ee3 feat: add get functions 2024-08-02 19:26:50 +08:00
MiniFrenchBread
50aacfa0c9 fix: da signers begin block 2024-08-02 19:26:50 +08:00
MiniFrenchBread
b3e526871e feat: max quorum num 2024-08-02 19:26:50 +08:00
MiniFrenchBread
9d15e399d8 fix: quorum 2024-08-02 19:26:50 +08:00
MiniFrenchBread
2b323eb655 feat: quorum 2024-08-02 19:26:50 +08:00
MiniFrenchBread
b6563958c1 fix: defaultGenesis 2024-08-02 19:26:50 +08:00
MiniFrenchBread
9c4006c626 feat: update dasigners proto api 2024-08-02 19:26:50 +08:00
MiniFrenchBread
dbf68f2471 fix: dasigners module 2024-08-02 19:26:50 +08:00
MiniFrenchBread
43b9916283 chore: dependency 2024-08-02 19:26:50 +08:00
MiniFrenchBread
4f6e7c9b98 feat: precompile 2024-08-02 19:26:50 +08:00
Solovyov1796
0392451819 rename the app name showed in usage (#10) 2024-08-02 19:26:50 +08:00
Peter Zhang
58832ff48e update max validator count 2024-08-02 19:26:50 +08:00
Peter Zhang
25f3181b5c update checkout branch 2024-08-02 19:26:50 +08:00
Solovyov1796
d07673616f update init-genesis.sh for devnet and testnet 2024-08-02 19:26:50 +08:00
Solovyov1796
3e0349a952 fix unit test 2024-08-02 19:26:50 +08:00
Solovyov1796
cb18ee26ce recv both cosmos denom and evm denom from bank keeper 2024-08-02 19:26:50 +08:00
0xsatoshi
90a9a98bc1 fix 2024-08-02 19:26:50 +08:00
0xsatoshi
8ca8453fb0 fix 2024-08-02 19:26:50 +08:00
Solovyov1796
d55494e697 update scripts 2024-08-02 19:26:50 +08:00
Solovyov1796
d0331307dc update env vars 2024-08-02 19:26:50 +08:00
Peter Zhang
f66cc46e47 modify deploy script 2024-08-02 19:26:50 +08:00
Solovyov1796
985f887968 update 2024-08-02 19:26:50 +08:00
Solovyov1796
ba5ce40fa9 fix unit test for x 2024-08-02 19:26:50 +08:00
Solovyov1796
3c839c0c95 add scripts for devnet 2024-08-02 19:26:50 +08:00
Solovyov1796
df55eae7aa fix panic 2024-08-02 19:26:50 +08:00
Solovyov1796
85b3ea129b merge script from branch v0.1.0 2024-08-02 19:26:50 +08:00
Solovyov1796
35da899616 fix test 2024-08-02 19:26:50 +08:00
Solovyov1796
cf502b61e7 add 0g code 2024-08-02 19:26:50 +08:00
Solovyov1796
14a0b2c99f rename kava 2024-08-02 19:26:50 +08:00
Solovyov1796
dd0743d1f5 add vrf 2024-08-02 19:26:50 +08:00
Solovyov1796
c04b6d1c7e revise file structure in cmd 2024-08-02 19:26:50 +08:00
Solovyov1796
1f989563f4 add chaincfg to save all configration of chain 2024-08-02 19:26:50 +08:00
Solovyov1796
ae3240e703 update build file 2024-08-02 19:26:50 +08:00
Solovyov1796
c7bb0576d3 revise proto files 2024-08-02 19:26:50 +08:00
Solovyov1796
47d31239d2 remove useless modules 2024-08-02 19:26:49 +08:00
Solovyov1796
3b75c9a3db rename go mod path 2024-08-02 19:26:37 +08:00
Peter Zhang
e976f28232 add deploy scripts 2024-08-02 19:26:37 +08:00
Peter Zhang
31d565f5a7 add deploy scripts 2024-08-02 19:26:37 +08:00
drklee3
897846b46f 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 19:26:37 +08:00
drklee3
577f39b998 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 19:26:37 +08:00
mergify[bot]
667e532aaa
chore: remove repetitive words (#1869) (#1873)
Signed-off-by: frameflare <yangzenghua@outlook.com>
(cherry picked from commit 41b79e44af)

Co-authored-by: frameflare <166090836+frameflare@users.noreply.github.com>
2024-04-05 07:27:10 -07:00
Nick DeLuca
32a0193c45
bump release/v0.26.x deps (#1871) 2024-04-05 07:15:29 -07:00
mergify[bot]
be5bf62ab8
fix:paramaters->paramaters (#1796) (#1872)
Fix misspellings across docs & comments

(cherry picked from commit 0ea92335de)

Co-authored-by: alex <152680487+bodhi-crypo@users.noreply.github.com>
2024-04-05 07:14:49 -07:00
Draco
7ca43024e4
Add v26 migrate docs (#1863)
* add migrate docs

* change date to TDB
2024-03-29 11:05:52 -07:00
Nick DeLuca
c9d900be2c
Set the CDP Block Interval to 100 during v0.26.x upgrade (#1865)
* set CDP block interval to 100 to only run interest synchronization
for risky cdps every 100 blocks instead of every block

* refactor and use constant for setting to improve clarity; update
block interval to 50 instead of 100.  This will decrease risk by
running around every 6 minutes instead of 12 mintues for current
mainnet block times.
2024-03-29 11:05:26 -07:00
Nick DeLuca
8f93ca2048
Use IAVL 0.20.x for v0.26.x release, update deps (#1862)
* revert back to iavl v1 to avoid hash changes on new modules like
we are seeing on the v0.24.x to v0.25.x upgrade block.  Also, add
replace statements for exp and rapid to match upstream cosmos-sdk

* fix sharding prune store logging and error return.

* add comment to clarify WithKeyTable usage
2024-03-28 14:38:07 -07:00
mergify[bot]
e34c94aa62
bep3 conversion msg server tests (#1859) (#1861)
(cherry picked from commit d3233d65d5)

Co-authored-by: Draco <draco@dracoli.com>
2024-03-28 07:16:15 -07:00
mergify[bot]
a548de05c2
Implement bep3 evm native conversion logic (#1848) (#1858)
* Implement bep3 evm native conversion logic

* Update changelog

* Fix indentation

* Add bep3 conversion keeper tests

* make DefaultBEP3ConversionDenoms private

* refactor bep3 conversion

* update bep3 tests to cover all bep3 assets

* minor refactor

(cherry picked from commit 3afb656d1f)

Co-authored-by: Draco <draco@dracoli.com>
2024-03-25 14:46:52 -04:00
Draco
7f73061c13
Add packet-forwarding store to upgrade (#1856) 2024-03-23 10:01:39 -04:00
mergify[bot]
da8a4f8787
Bump cosmos-sdk to v0.47.10-kava.2 with iavl v1 support (#1846) (#1855)
* Bump to cosmos-sdk to v0.47.10-kava.2

* Update go version in dockerfile to 1.21

* Fix shard logic for iavl v1

* Update changelog

(cherry picked from commit 969614d555)

Co-authored-by: Draco <draco@dracoli.com>
2024-03-22 18:27:21 -07:00
mergify[bot]
e96fd1735d
update deps and add mergify config for v0.26.x release branch (backport #1853) (#1854)
* update deps and add mergify config for v0.26.x release branch (#1853)

(cherry picked from commit 7866ee2f74)

# Conflicts:
#	go.sum

* fix go.sum conflicts

---------

Co-authored-by: Nick DeLuca <nickdeluca08@gmail.com>
2024-03-22 15:47:47 -07:00
Kevin Davis
eb9d3a3ed8
add legacy rest removal notice (#1857) 2024-03-22 14:36:24 -07:00
Levi Schoen
a681a5e631
upgrade to iavl v1 (#1845) 2024-03-12 15:04:10 -04:00
Draco
6b41ed84b8
Add packet forward store to upgrade (#1843) 2024-03-08 16:34:31 -05:00
Draco
17691e95a8
Merge branch 'master' into release/v0.26.x 2024-03-08 09:10:32 -05:00
Levi Schoen
cf2d83b020
consolidate conditional for internal testnet cd 2024-03-07 13:56:34 -08:00
Draco
5c0f27b952
Add ibc packet forward middleware for ibc transfer (#1839)
* Add ibc packet forward middleware for ibc transfer

* Update changelog for ibc packet forwarding
2024-03-07 16:47:46 -05:00
Levi Schoen
322f2ac056
only deploy internal testnet if deploy version or genesis state changes (#1842) 2024-03-07 15:44:42 -05:00
Adam Robert Turman
9bfd1ffd7d
fund internal testnet e2e account with USDt (#1841) 2024-03-06 14:07:26 -06:00
Robert Pirtle
f5384a1f11
cli: refactor shard command & add recovery options (#1837)
* expose SkipLoadLatest override via AppOpts

* add --force-app-version option to shard command

* refactor sharding of application.db

* refactor sharding of blockstore & state.db

* add --only-cometbft-state flag

* add comment divisions

* update usage doc

* prevent infinite loop during cometbft rollback
2024-02-29 16:22:09 -08:00
Draco
2a1e9a6631
Update x/incentive cli to use grpc (#1836)
* Update x/incentive cli to use grpc

* Update changelog
2024-02-29 15:09:52 -05:00
Robert Pirtle
069be95dde
fix: update vesting tests to use fixed block time (#1838)
* fix: update SWP circulating supply test constant

* use fixed blocktime for vesting tests
2024-02-29 12:09:07 -08:00
Draco
1d944d5219
Validator Vesting gRPC Endpoints (#1832)
* Add validator-vesting grpc

* Update validator REST API endpoints to use grpc

* Update validator-vesting cli to use grpc

* Update changelog for added grpc changes

* Add grpc query tests
2024-02-27 14:40:52 -05:00
Draco
11d3ba3466
Remove used legacy querier types (#1835)
These were left out by accident when the legacy queriers are removed from the modules in this commit 3ba4078ec1
2024-02-27 14:25:56 -05:00
Levi Schoen
2bc0c62570
register solomachine module for v6 to v7 ibc-go migration (#1831) 2024-02-16 12:49:58 -05:00
Levi Schoen
58d04e2996 register solomachine module for v6 to v7 ibc-go migration (#1830) 2024-02-15 15:24:55 -08:00
Draco
ad387e6a42
Add upgrade handler for Kava v0.26.0 (#1827)
* Add upgrade handler for Kava v0.26.0

* Update tests e2e to run upgrade tests
2024-02-13 13:27:27 -05:00
Draco
550ecc8027
Change e2e kvtool config template back to master (#1829) 2024-02-12 15:02:31 -05:00
Draco
5914f1db85
Update Kava grpc client with consensus client (#1828)
* Add consensus client to kava grpc client

* Update kvtool to latest version
This version includes the v25 kava template
2024-02-12 12:49:49 -05:00
Levi Schoen
ad03a75679
emulate block broadcast mode in seed scripts (#1824) 2024-02-08 18:32:44 -05:00
Levi Schoen
c0df29333b
use broadcast mode sync vs block in cli scripts (#1823) 2024-02-08 14:52:36 -05:00
Levi Schoen
45aa631f18
allow for running manual cd for protonet ad hoc (#1821) 2024-02-07 14:18:53 -05:00
1076 changed files with 28477 additions and 179374 deletions

10
.github/mergify.yml vendored
View File

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

View File

@ -33,7 +33,7 @@ kava config chain-id "${CHAIN_ID}"
kava config keyring-backend test
# wait for transactions to be committed per CLI command
kava config broadcast-mode block
kava config broadcast-mode sync
# setup god's wallet
echo "${KAVA_TESTNET_GOD_MNEMONIC}" | kava keys add --recover god
@ -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 🖖🏽
# make sure to update god committee member permissions for the module
# 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
# fetch current module params

View File

@ -1,6 +1,14 @@
#!/bin/bash
set -ex
# by sleeping 1 block in between tx's
# we can emulate the behavior of the
# the deprecated and now removed (as of Kava 16)
# broadcast mode of `block` in order to
# minimize the chance tx's fail due to an
# account sequence number mismatch
AVG_SECONDS_BETWEEN_BLOCKS=6.5
# configure kava binary to talk to the desired chain endpoint
kava config node "${CHAIN_API_URL}"
kava config chain-id "${CHAIN_ID}"
@ -9,7 +17,7 @@ kava config chain-id "${CHAIN_ID}"
kava config keyring-backend test
# wait for transactions to be committed per CLI command
kava config broadcast-mode block
kava config broadcast-mode sync
# setup dev wallet
echo "${DEV_WALLET_MNEMONIC}" | kava keys add --recover dev-wallet
@ -23,6 +31,8 @@ echo "sweet ocean blush coil mobile ten floor sample nuclear power legend where
# fund evm-contract-deployer account (using issuance)
kava tx issuance issue 200000000ukava kava1van3znl6597xgwwh46jgquutnqkwvwszjg04fz --from dev-wallet --gas-prices 0.5ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# deploy and fund USDC ERC20 contract
MULTICHAIN_USDC_CONTRACT_DEPLOY=$(npx hardhat --network "${ERC20_DEPLOYER_NETWORK_NAME}" deploy-erc20 "USD Coin" USDC 6)
MULTICHAIN_USDC_CONTRACT_ADDRESS=${MULTICHAIN_USDC_CONTRACT_DEPLOY: -42}
@ -96,6 +106,8 @@ npx hardhat --network "${ERC20_DEPLOYER_NETWORK_NAME}" mint-erc20 "$TETHER_USDT_
kava tx issuance issue 6000000000ukava kava1vlpsrmdyuywvaqrv7rx6xga224sqfwz3fyfhwq \
--from dev-wallet --gas-prices 0.5ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# parse space seperated list of validators
# into bash array
read -r -a GENESIS_VALIDATOR_ADDRESS_ARRAY <<<"$GENESIS_VALIDATOR_ADDRESSES"
@ -103,11 +115,14 @@ read -r -a GENESIS_VALIDATOR_ADDRESS_ARRAY <<<"$GENESIS_VALIDATOR_ADDRESSES"
# delegate 300KAVA to each validator
for validator in "${GENESIS_VALIDATOR_ADDRESS_ARRAY[@]}"; do
kava tx staking delegate "${validator}" 300000000ukava --from dev-wallet --gas-prices 0.5ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
done
# create a text proposal
kava tx gov submit-legacy-proposal --deposit 1000000000ukava --type "Text" --title "Example Proposal" --description "This is an example proposal" --gas auto --gas-adjustment 1.2 --from dev-wallet --gas-prices 0.01ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# setup god's wallet
echo "${KAVA_TESTNET_GOD_MNEMONIC}" | kava keys add --recover god
@ -155,13 +170,17 @@ printf "original evm util module params\n %s" , "$originalEvmUtilParams"
# change the params of the chain like a god - make it so 🖖🏽
# make sure to update god committee member permissions for the module
# 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.
kava tx committee submit-proposal 1 "$proposalFileName" --gas 2000000 --gas-prices 0.01ukava --from god -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# vote on the proposal. this assumes no other committee proposal has ever been submitted (id=1)
kava tx committee vote 1 yes --gas 2000000 --gas-prices 0.01ukava --from god -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# fetch current module params
updatedEvmUtilParams=$(curl https://api.app.internal.testnet.us-east.production.kava.io/kava/evmutil/v1beta1/params)
printf "updated evm util module params\n %s" , "$updatedEvmUtilParams"
@ -172,3 +191,5 @@ kava tx evmutil convert-cosmos-coin-to-erc20 \
"$DEV_TEST_WALLET_ADDRESS" \
1000000hard \
--from dev-wallet --gas 2000000 --gas-prices 0.001ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS

View File

@ -1,6 +1,14 @@
#!/bin/bash
set -ex
# by sleeping 1 block in between tx's
# we can emulate the behavior of the
# the deprecated and now removed (as of Kava 16)
# broadcast mode of `block` in order to
# minimize the chance tx's fail due to an
# account sequence number mismatch
AVG_SECONDS_BETWEEN_BLOCKS=6.5
# configure kava binary to talk to the desired chain endpoint
kava config node "${CHAIN_API_URL}"
kava config chain-id "${CHAIN_ID}"
@ -9,7 +17,7 @@ kava config chain-id "${CHAIN_ID}"
kava config keyring-backend test
# wait for transactions to be committed per CLI command
kava config broadcast-mode block
kava config broadcast-mode sync
# setup dev wallet
echo "${DEV_WALLET_MNEMONIC}" | kava keys add --recover dev-wallet
@ -23,9 +31,13 @@ echo "sweet ocean blush coil mobile ten floor sample nuclear power legend where
# fund evm-contract-deployer account (using issuance)
kava tx issuance issue 200000000ukava kava1van3znl6597xgwwh46jgquutnqkwvwszjg04fz --from dev-wallet --gas-prices 0.5ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# fund 5k kava to x/community account
kava tx community fund-community-pool 5000000000ukava --from dev-wallet --gas-prices 0.5ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# deploy and fund USDC ERC20 contract
MULTICHAIN_USDC_CONTRACT_DEPLOY=$(npx hardhat --network "${ERC20_DEPLOYER_NETWORK_NAME}" deploy-erc20 "USD Coin" USDC 6)
MULTICHAIN_USDC_CONTRACT_ADDRESS=${MULTICHAIN_USDC_CONTRACT_DEPLOY: -42}
@ -89,6 +101,8 @@ npx hardhat --network "${ERC20_DEPLOYER_NETWORK_NAME}" mint-erc20 "$AXL_USDC_CON
kava tx issuance issue 6000000000ukava kava1vlpsrmdyuywvaqrv7rx6xga224sqfwz3fyfhwq \
--from dev-wallet --gas-prices 0.5ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# parse space seperated list of validators
# into bash array
read -r -a GENESIS_VALIDATOR_ADDRESS_ARRAY <<< "$GENESIS_VALIDATOR_ADDRESSES"
@ -97,11 +111,14 @@ read -r -a GENESIS_VALIDATOR_ADDRESS_ARRAY <<< "$GENESIS_VALIDATOR_ADDRESSES"
for validator in "${GENESIS_VALIDATOR_ADDRESS_ARRAY[@]}"
do
kava tx staking delegate "${validator}" 300000000ukava --from dev-wallet --gas-prices 0.5ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
done
# create a text proposal
kava tx gov submit-legacy-proposal --deposit 1000000000ukava --type "Text" --title "Example Proposal" --description "This is an example proposal" --gas auto --gas-adjustment 1.2 --from dev-wallet --gas-prices 0.01ukava -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# setup god's wallet
echo "${KAVA_TESTNET_GOD_MNEMONIC}" | kava keys add --recover god
@ -147,12 +164,16 @@ printf "original evm util module params\n %s" , "$originalEvmUtilParams"
# change the params of the chain like a god - make it so 🖖🏽
# make sure to update god committee member permissions for the module
# 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
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# vote on the proposal. this assumes no other committee proposal has ever been submitted (id=1)
kava tx committee vote 1 yes --gas 2000000 --gas-prices 0.01ukava --from god -y
sleep $AVG_SECONDS_BETWEEN_BLOCKS
# fetch current module params
updatedEvmUtilParams=$(curl https://api.app.internal.testnet.us-east.production.kava.io/kava/evmutil/v1beta1/params)
printf "updated evm util module params\n %s" , "$updatedEvmUtilParams"

View File

@ -1,5 +1,6 @@
name: Continuous Deployment (Internal Testnet)
# run after every successful CI job of new commits to the master branch
# if deploy version or config has changed
on:
workflow_run:
workflows: [Continuous Integration (Kava Master)]
@ -7,6 +8,23 @@ on:
- completed
jobs:
changed_files:
runs-on: ubuntu-latest
# define output for first job forwarding output of changedInternalTestnetConfig job
outputs:
changedInternalTestnetConfig: ${{ steps.changed-internal-testnet-config.outputs.any_changed }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # OR "2" -> To retrieve the preceding commit.
- name: Get all changed internal testnet files
id: changed-internal-testnet-config
uses: tj-actions/changed-files@v42
with:
# Avoid using single or double quotes for multiline patterns
files: |
ci/env/kava-internal-testnet/**
# in order:
# enter standby (prevents autoscaling group from killing node during deploy)
# stop kava
@ -14,8 +32,9 @@ jobs:
# download updated binary and genesis
# reset application database state (only done on internal testnet)
reset-chain-to-zero-state:
needs: [changed_files]
# only start cd pipeline if last ci run was successful
if: ${{ github.event.workflow_run.conclusion == 'success' }}
if: ${{ github.event.workflow_run.conclusion == 'success' && needs.changed_files.outputs.changedInternalTestnetConfig == 'true' }}
uses: ./.github/workflows/cd-reset-internal-testnet.yml
with:
aws-region: us-east-1

View File

@ -10,8 +10,6 @@ jobs:
# 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

View File

@ -76,8 +76,8 @@ jobs:
- name: compile default erc20 contracts
run: make compile-contracts
working-directory: kava-bridge
- name: download seed script from master
run: wget https://raw.githubusercontent.com/Kava-Labs/kava/master/.github/scripts/${SEED_SCRIPT_FILENAME} && chmod +x ${SEED_SCRIPT_FILENAME}
- name: download seed script from current commit
run: wget https://raw.githubusercontent.com/Kava-Labs/kava/${GITHUB_SHA}/.github/scripts/${SEED_SCRIPT_FILENAME} && chmod +x ${SEED_SCRIPT_FILENAME}
working-directory: kava-bridge/contract
env:
SEED_SCRIPT_FILENAME: ${{ inputs.seed-script-filename }}

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.work
go.work.sum
.build/0gchaind
.build/da
# runtime
run

View File

@ -1,2 +1,2 @@
golang 1.20
golang 1.21
nodejs 18.16.0

View File

@ -36,12 +36,18 @@ Ref: https://keepachangelog.com/en/1.0.0/
## [Unreleased]
## [v0.26.0]
### 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
- (cli) [#1804] Add `rocksdb compact` command for manual DB compaction of state or blockstore
- (cosmos-sdk) [#1811] [#1846] Upgrades app to cosmos-sdk v0.47.10 with iavl v1 support
- (validator-vesting) [#1832] Add grpc query service to replace removed legacy querier
- (incentive) [#1836] Update x/incentive cli to use grpc query client
- (ibc) [#1839] Add ibc packet forward middleware for ibc transfers
- (evmutil) [#1848] Update evm native conversion logic to handle bep3 assets
## [v0.25.0]
@ -324,6 +330,11 @@ 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
large-scale simulations remotely using aws-batch
[#1846]: https://github.com/Kava-Labs/kava/pull/1846
[#1848]: https://github.com/Kava-Labs/kava/pull/1848
[#1839]: https://github.com/Kava-Labs/kava/pull/1839
[#1836]: https://github.com/Kava-Labs/kava/pull/1836
[#1832]: https://github.com/Kava-Labs/kava/pull/1832
[#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

View File

@ -1,4 +1,4 @@
FROM golang:1.20-alpine AS build-env
FROM golang:1.21-alpine AS build-env
# Set up dependencies
# bash, jq, curl for debugging
@ -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
# Set working directory for the build
WORKDIR /root/kava
WORKDIR /root/0g-chain
# default home directory is /root
# 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
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
RUN apt-get update \
@ -19,7 +19,7 @@ RUN git clone https://github.com/facebook/rocksdb.git \
&& make -j$(nproc) install-shared \
&& ldconfig
WORKDIR /root/kava
WORKDIR /root/0gchain
# Copy dependency files first to facilitate dependency caching
COPY ./go.mod ./
COPY ./go.sum ./
@ -32,13 +32,13 @@ RUN --mount=type=cache,target=/root/.cache/go-build \
# Add source files
COPY . .
ARG kava_database_backend=rocksdb
ENV KAVA_DATABASE_BACKEND=$kava_database_backend
ARG 0gchain_database_backend=rocksdb
ENV 0GCHAIN_DATABASE_BACKEND=$0gchain_database_backend
# Mount go build and mod caches as container caches, persisted between builder invocations
RUN --mount=type=cache,target=/root/.cache/go-build \
--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
@ -48,10 +48,10 @@ RUN apt-get update \
&& rm -rf /var/lib/apt/lists/*
# 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
# copy kava binary
COPY --from=kava-builder /go/bin/kava /bin/kava
# copy 0g-chain binary
COPY --from=chain-builder /go/bin/0gchaind /bin/0gchaind
CMD ["kava"]
CMD ["0gchaind"]

View File

@ -1,8 +1,10 @@
################################################################################
### 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
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
@ -37,7 +39,7 @@ print-git-info:
.PHONY: 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 ###
@ -45,7 +47,7 @@ print-version:
LEDGER_ENABLED ?= true
DOCKER:=docker
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 ###
@ -76,7 +78,7 @@ print-machine-info:
BUILD_DIR := build# build files
BIN_DIR := $(BUILD_DIR)/bin# for binary dev dependencies
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
export PATH := $(ROOT_DIR)/$(BIN_DIR):$(PATH)# add local bin first in path
@ -142,8 +144,8 @@ build_tags_comma_sep := $(subst $(whitespace),$(comma),$(build_tags))
# process linker flags
ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=kava \
-X github.com/cosmos/cosmos-sdk/version.AppName=kava \
ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=$(PROJECT_NAME) \
-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.Commit=$(GIT_COMMIT) \
-X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \
@ -188,16 +190,16 @@ all: install
build: go.sum
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
$(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
build-linux: go.sum
LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build
install: go.sum
$(GO_BIN) install -mod=readonly $(BUILD_FLAGS) ./cmd/kava
$(GO_BIN) install -mod=readonly $(BUILD_FLAGS) $(MAIN_ENTRY)
########################################
### Tools & dependencies
@ -219,6 +221,7 @@ go.sum: go.mod
# Set to exclude riot links as they trigger false positives
link-check:
@$(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*"
@ -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 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/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
###############################################################################
### Localnet ###
###############################################################################
# Build docker image and tag as kava/kava:local
# Build docker image and tag as 0glabs/0g-chain:local
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_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
# Run a 4-node testnet locally
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
localnet-stop:
@ -261,7 +264,7 @@ localnet-stop:
# Launch a new single validator chain
start:
./contrib/devnet/init-new-chain.sh
kava start
$(BINARY_NAME) start
#proto-format:
#@echo "Formatting Protobuf files"
@ -302,7 +305,7 @@ test:
@$(GO_BIN) test $$($(GO_BIN) list ./... | grep -v 'contrib' | grep -v 'tests/e2e')
test-rocksdb:
@go test -tags=rocksdb ./cmd/kava/opendb
@go test -tags=rocksdb $(MAIN_ENTRY)/opendb
# Run cli integration tests
# `-p 4` to use 4 cores, `-tags cli_test` to tell $(GO_BIN) not to ignore the cli package
@ -318,15 +321,15 @@ test-migrate:
# 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:
# 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
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
aws batch submit-job \
-—job-name "master-$(VERSION)" \
-—job-queue “simulation-1-queue-spot" \
-—array-properties size=1000 \
-—job-definition kava-sim-master \
-—job-definition $(BINARY_NAME)-sim-master \
-—container-override environment=[{SIM_NAME=master-$(VERSION)}]
update-kvtool:

View File

@ -1,27 +1,20 @@
<!---
<p align="center">
<img src="./kava-logo.svg" width="300">
<img src="./0g-logo.svg" width="300">
</p>
--->
# 0G Chain
<div align="center">
[![version](https://img.shields.io/github/tag/kava-labs/kava.svg)](https://github.com/kava-labs/kava/releases/latest)
[![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)
### [Telegram](https://t.me/web3_0glabs) | [Discord](https://discord.com/invite/0glabs)
</div>
<div align="center">
### [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).
Reference implementation of 0G Chain, the first modular AI chain. Built using the [cosmos-sdk](https://github.com/cosmos/cosmos-sdk).
<!---
## 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.
@ -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.
Licensed under the [Apache v2 License](LICENSE.md).
--->

View File

@ -32,15 +32,10 @@ import (
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/supply"
"github.com/kava-labs/kava/x/auction"
"github.com/kava-labs/kava/x/bep3"
"github.com/kava-labs/kava/x/cdp"
"github.com/kava-labs/kava/x/committee"
"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"
"github.com/0glabs/0g-chain/x/bep3"
"github.com/0glabs/0g-chain/x/committee"
"github.com/0glabs/0g-chain/x/pricefeed"
validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting"
)
type StoreKeysPrefixes struct {

View File

@ -8,8 +8,8 @@ import (
"net/http/httptest"
"testing"
sdkmath "cosmossdk.io/math"
"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"
@ -52,9 +52,9 @@ func (suite *SimulateRequestTestSuite) TearDownTest() {
}
func (suite *SimulateRequestTestSuite) TestSimulateRequest() {
fromAddr, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea")
fromAddr, err := sdk.AccAddressFromBech32("0g1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea")
suite.Require().NoError(err)
toAddr, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w")
toAddr, err := sdk.AccAddressFromBech32("0g1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w")
suite.Require().NoError(err)
simRequest := app.SimulateRequest{
@ -62,11 +62,11 @@ func (suite *SimulateRequestTestSuite) TestSimulateRequest() {
bank.MsgSend{
FromAddress: fromAddr,
ToAddress: toAddr,
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
Amount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e6)),
},
},
Fee: auth.StdFee{
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5e4))),
Amount: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(5e4)),
Gas: 1e6,
},
Memo: "test memo",

View File

@ -22,13 +22,14 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app"
bep3types "github.com/kava-labs/kava/x/bep3/types"
pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
bep3types "github.com/0glabs/0g-chain/x/bep3/types"
pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
)
func TestMain(m *testing.M) {
app.SetSDKConfig()
chaincfg.SetSDKConfig()
os.Exit(m.Run())
}
@ -53,7 +54,7 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) {
App: *app.NewApp(
log.NewNopLogger(),
tmdb.NewMemDB(),
app.DefaultNodeHome,
chaincfg.DefaultNodeHome,
nil,
encodingConfig,
opts,
@ -67,7 +68,7 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) {
chainID,
app.NewFundedGenStateWithSameCoins(
tApp.AppCodec(),
sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e9)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e9)),
testAddresses,
),
newBep3GenStateMulti(tApp.AppCodec(), deputy),
@ -115,7 +116,7 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) {
banktypes.NewMsgSend(
tc.address,
testAddresses[0],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 1_000_000)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1_000_000)),
),
},
sdk.NewCoins(), // no fee

View File

@ -10,8 +10,9 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/ante"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/ante"
"github.com/0glabs/0g-chain/chaincfg"
)
var _ sdk.AnteHandler = (&MockAnteHandler{}).AnteHandle
@ -45,7 +46,7 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_NotCheckTx(t *testing.T) {
banktypes.NewMsgSend(
testAddresses[0],
testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100_000_000)),
),
},
sdk.NewCoins(), // no fee
@ -80,12 +81,12 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Pass(t *testing.T) {
banktypes.NewMsgSend(
testAddresses[0],
testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
),
banktypes.NewMsgSend(
testAddresses[2],
testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
),
},
sdk.NewCoins(), // no fee
@ -121,7 +122,7 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Reject(t *testing.T) {
banktypes.NewMsgSend(
testAddresses[0],
testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
),
},
sdk.NewCoins(), // no fee

View File

@ -14,8 +14,9 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/ante"
"github.com/0glabs/0g-chain/app"
"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 {
@ -58,7 +59,7 @@ func TestAuthzLimiterDecorator(t *testing.T) {
banktypes.NewMsgSend(
testAddresses[0],
testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100e6)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100e6)),
),
},
checkTx: false,
@ -128,7 +129,7 @@ func TestAuthzLimiterDecorator(t *testing.T) {
[]sdk.Msg{banktypes.NewMsgSend(
testAddresses[0],
testAddresses[3],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100e6)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100e6)),
)}),
},
checkTx: false,
@ -161,7 +162,7 @@ func TestAuthzLimiterDecorator(t *testing.T) {
banktypes.NewMsgSend(
testAddresses[0],
testAddresses[3],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100e6)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100e6)),
),
&evmtypes.MsgEthereumTx{},
},

View File

@ -33,13 +33,12 @@ import (
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
"github.com/stretchr/testify/suite"
"github.com/kava-labs/kava/app"
cdptypes "github.com/kava-labs/kava/x/cdp/types"
evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper"
evmutiltestutil "github.com/kava-labs/kava/x/evmutil/testutil"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types"
hardtypes "github.com/kava-labs/kava/x/hard/types"
pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/chaincfg"
evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
evmutiltestutil "github.com/0glabs/0g-chain/x/evmutil/testutil"
evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
)
const (
@ -158,7 +157,7 @@ func (suite *EIP712TestSuite) SetupTest() {
// Genesis states
evmGs := evmtypes.NewGenesisState(
evmtypes.NewParams(
"akava", // evmDenom
chaincfg.EvmDenom, // evmDenom
false, // allowedUnprotectedTxs
true, // enableCreate
true, // enableCall
@ -173,47 +172,6 @@ func (suite *EIP712TestSuite) SetupTest() {
feemarketGenesis.Params.EnableHeight = 1
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.Params.Markets = []pricefeedtypes.Market{
{
@ -262,15 +220,13 @@ func (suite *EIP712TestSuite) SetupTest() {
genState := app.GenesisState{
evmtypes.ModuleName: cdc.MustMarshalJSON(evmGs),
feemarkettypes.ModuleName: cdc.MustMarshalJSON(feemarketGenesis),
cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenState),
hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGenState),
pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState),
}
// funds our test accounts with some ukava
// funds our test accounts with some gas denom
coinsGenState := app.NewFundedGenStateWithSameCoins(
tApp.AppCodec(),
sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e9)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(1e9)),
[]sdk.AccAddress{suite.testAddr, suite.testAddr2},
)
@ -357,45 +313,17 @@ func (suite *EIP712TestSuite) SetupTest() {
params := evmKeeper.GetParams(suite.ctx)
params.EIP712AllowedMsgs = []evmtypes.EIP712AllowedMsg{
{
MsgTypeUrl: "/kava.evmutil.v1beta1.MsgConvertERC20ToCoin",
MsgTypeUrl: "/zgc.evmutil.v1beta1.MsgConvertERC20ToCoin",
MsgValueTypeName: "MsgValueEVMConvertERC20ToCoin",
ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "initiator", Type: "string"},
{Name: "receiver", Type: "string"},
{Name: "kava_erc20_address", Type: "string"},
{Name: "zgchain_erc20_address", Type: "string"},
{Name: "amount", Type: "string"},
},
},
{
MsgTypeUrl: "/kava.cdp.v1beta1.MsgCreateCDP",
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",
MsgTypeUrl: "/zgc.evmutil.v1beta1.MsgConvertCoinToERC20",
MsgValueTypeName: "MsgValueEVMConvertCoinToERC20",
ValueTypes: []evmtypes.EIP712MsgAttrType{
{Name: "initiator", Type: "string"},
@ -403,23 +331,6 @@ func (suite *EIP712TestSuite) SetupTest() {
{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)
@ -465,7 +376,7 @@ func (suite *EIP712TestSuite) deployUSDCERC20(app app.TestApp, ctx sdk.Context)
suite.tApp.FundModuleAccount(
suite.ctx,
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))
@ -487,40 +398,43 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx bool
errMsg string
}{
{
name: "processes deposit eip712 messages successfully",
usdcDepositAmt: 100,
usdxToMintAmt: 99,
},
// TODO: need fix
// {
// name: "processes deposit eip712 messages successfully",
// usdcDepositAmt: 100,
// usdxToMintAmt: 99,
// },
{
name: "fails when convertion more erc20 usdc than balance",
usdcDepositAmt: 51_000,
usdxToMintAmt: 100,
errMsg: "transfer amount exceeds balance",
},
{
name: "fails when minting more usdx than allowed",
usdcDepositAmt: 100,
usdxToMintAmt: 100,
errMsg: "proposed collateral ratio is below liquidation ratio",
},
{
name: "fails when trying to convert usdc for another address",
usdcDepositAmt: 100,
usdxToMintAmt: 90,
errMsg: "unauthorized",
failCheckTx: true,
updateMsgs: func(msgs []sdk.Msg) []sdk.Msg {
convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin(
suite.testEVMAddr2,
suite.testAddr,
suite.usdcEVMAddr,
suite.getEVMAmount(100),
)
msgs[0] = &convertMsg
return msgs
},
},
// TODO: need fix
// {
// name: "fails when minting more usdx than allowed",
// usdcDepositAmt: 100,
// usdxToMintAmt: 100,
// errMsg: "proposed collateral ratio is below liquidation ratio",
// },
// TODO: need fix
// {
// name: "fails when trying to convert usdc for another address",
// usdcDepositAmt: 100,
// usdxToMintAmt: 90,
// errMsg: "unauthorized",
// failCheckTx: true,
// updateMsgs: func(msgs []sdk.Msg) []sdk.Msg {
// convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin(
// suite.testEVMAddr2,
// suite.testAddr,
// suite.usdcEVMAddr,
// suite.getEVMAmount(100),
// )
// msgs[0] = &convertMsg
// return msgs
// },
// },
{
name: "fails when trying to convert erc20 for non-whitelisted contract",
usdcDepositAmt: 100,
@ -562,7 +476,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
errMsg: "insufficient funds",
updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder {
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))
return txBuilder
},
@ -574,7 +488,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx: true,
errMsg: "invalid chain-id",
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(
suite.testAddr, suite.testPrivKey, "kavatest_12-1", uint64(sims.DefaultGenTxGas*10), gasAmt, msgs,
)
@ -587,7 +501,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx: true,
errMsg: "invalid pubkey",
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(
suite.testAddr2, suite.testPrivKey2, ChainID, uint64(sims.DefaultGenTxGas*10), gasAmt, msgs,
)
@ -607,27 +521,15 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
suite.usdcEVMAddr,
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{
&convertMsg,
&mintMsg,
&lendMsg,
}
if tc.updateMsgs != nil {
msgs = tc.updateMsgs(msgs)
}
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20)))
gasAmt := sdk.NewCoins(chaincfg.MakeCoinForGasDenom(20))
txBuilder := suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, ChainID, uint64(sims.DefaultGenTxGas*10), gasAmt, msgs,
)
@ -665,17 +567,17 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
suite.Require().Equal(sdk.ZeroInt(), amt.Amount)
// validate cdp
cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType)
suite.Require().True(found)
suite.Require().Equal(suite.testAddr, cdp.Owner)
suite.Require().Equal(sdk.NewCoin(USDCCoinDenom, suite.getEVMAmount(100)), cdp.Collateral)
suite.Require().Equal(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000)), cdp.Principal)
// cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType)
// suite.Require().True(found)
// suite.Require().Equal(suite.testAddr, cdp.Owner)
// suite.Require().Equal(sdk.NewCoin(USDCCoinDenom, suite.getEVMAmount(100)), cdp.Collateral)
// suite.Require().Equal(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000)), cdp.Principal)
// validate hard
hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().True(found)
suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
// hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
// suite.Require().True(found)
// suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
// suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
} else {
suite.Require().NotEqual(resDeliverTx.Code, uint32(0), resCheckTx.Log)
suite.Require().Contains(resDeliverTx.Log, tc.errMsg)
@ -695,25 +597,13 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.usdcEVMAddr,
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{
&convertMsg,
&mintMsg,
&lendMsg,
}
// deliver deposit msg
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20)))
gasAmt := sdk.NewCoins(chaincfg.MakeCoinForGasDenom(20))
txBuilder := suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, ChainID, uint64(sims.DefaultGenTxGas*10), gasAmt, depositMsgs,
)
@ -727,10 +617,10 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log)
// validate hard
hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().True(found)
suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
// hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
// suite.Require().True(found)
// suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
// suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
// validate erc20 balance
coinBal, err := suite.evmutilKeeper.QueryERC20BalanceOf(suite.ctx, suite.usdcEVMAddr, suite.testEVMAddr)
@ -743,18 +633,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.testEVMAddr.String(),
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{
&hardWithdrawMsg,
&cdpWithdrawMsg,
&withdrawConvertMsg,
}
@ -772,10 +651,10 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log)
// validate hard & cdp should be repayed
_, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().False(found)
_, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType)
suite.Require().False(found)
// _, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
// suite.Require().False(found)
// _, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType)
// suite.Require().False(found)
// validate user cosmos erc20/usd balance
bk := suite.tApp.GetBankKeeper()

View File

@ -11,8 +11,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/ante"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/ante"
"github.com/0glabs/0g-chain/chaincfg"
)
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()})
tApp.GetEvmKeeper().SetParams(ctx, evmtypes.Params{
EvmDenom: "akava",
EvmDenom: chaincfg.EvmDenom,
})
testCases := []struct {
@ -44,29 +45,29 @@ func TestEvmMinGasFilter(t *testing.T) {
mustParseDecCoins(""),
},
{
"zero ukava gas price",
mustParseDecCoins("0ukava"),
mustParseDecCoins("0ukava"),
"zero ua0gi gas price",
mustParseDecCoins("0ua0gi"),
mustParseDecCoins("0ua0gi"),
},
{
"non-zero ukava gas price",
mustParseDecCoins("0.001ukava"),
mustParseDecCoins("0.001ukava"),
"non-zero ua0gi gas price",
mustParseDecCoins("0.001ua0gi"),
mustParseDecCoins("0.001ua0gi"),
},
{
"zero ukava gas price, min akava price",
mustParseDecCoins("0ukava;100000akava"),
mustParseDecCoins("0ukava"), // akava is removed
"zero ua0gi gas price, min neuron price",
mustParseDecCoins("0ua0gi;100000neuron"),
mustParseDecCoins("0ua0gi"), // neuron is removed
},
{
"zero ukava gas price, min akava price, other token",
mustParseDecCoins("0ukava;100000akava;0.001other"),
mustParseDecCoins("0ukava;0.001other"), // akava is removed
"zero ua0gi gas price, min neuron price, other token",
mustParseDecCoins("0ua0gi;100000neuron;0.001other"),
mustParseDecCoins("0ua0gi;0.001other"), // neuron is removed
},
{
"non-zero ukava gas price, min akava price",
mustParseDecCoins("0.25ukava;100000akava;0.001other"),
mustParseDecCoins("0.25ukava;0.001other"), // akava is removed
"non-zero ua0gi gas price, min neuron price",
mustParseDecCoins("0.25ua0gi;100000neuron;0.001other"),
mustParseDecCoins("0.25ua0gi;0.001other"), // neuron is removed
},
}

View File

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

View File

@ -12,8 +12,9 @@ import (
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/ante"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/ante"
"github.com/0glabs/0g-chain/chaincfg"
)
func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing.T) {
@ -33,7 +34,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing
"MsgCreateVestingAccount",
vesting.NewMsgCreateVestingAccount(
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(),
false,
),
@ -44,7 +45,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing
"MsgCreateVestingAccount",
vesting.NewMsgCreatePermanentLockedAccount(
testAddresses[0], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
),
true,
"MsgTypeURL /cosmos.vesting.v1beta1.MsgCreatePermanentLockedAccount not supported",
@ -63,7 +64,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing
"other messages not affected",
banktypes.NewMsgSend(
testAddresses[0], testAddresses[1],
sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)),
sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100)),
),
false,
"",

View File

@ -3,10 +3,7 @@ package app
import (
"fmt"
"io"
stdlog "log"
"net/http"
"os"
"path/filepath"
dbm "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
@ -31,6 +28,7 @@ import (
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"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"
"github.com/cosmos/cosmos-sdk/x/authz"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
@ -79,6 +77,9 @@ import (
upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client"
upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
"github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/packetforward"
packetforwardkeeper "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/packetforward/keeper"
packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/packetforward/types"
transfer "github.com/cosmos/ibc-go/v7/modules/apps/transfer"
ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper"
ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"
@ -86,90 +87,56 @@ import (
ibcclient "github.com/cosmos/ibc-go/v7/modules/core/02-client"
ibcclientclient "github.com/cosmos/ibc-go/v7/modules/core/02-client/client"
ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types"
porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types"
ibcporttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types"
ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported"
ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper"
solomachine "github.com/cosmos/ibc-go/v7/modules/light-clients/06-solomachine"
ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint"
evmante "github.com/evmos/ethermint/app/ante"
ethermintconfig "github.com/evmos/ethermint/server/config"
"github.com/evmos/ethermint/x/evm"
evmkeeper "github.com/evmos/ethermint/x/evm/keeper"
evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/evmos/ethermint/x/evm/vm/geth"
"github.com/evmos/ethermint/x/feemarket"
feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
"github.com/gorilla/mux"
"github.com/kava-labs/kava/app/ante"
kavaparams "github.com/kava-labs/kava/app/params"
"github.com/kava-labs/kava/x/auction"
auctionkeeper "github.com/kava-labs/kava/x/auction/keeper"
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"
)
"github.com/0glabs/0g-chain/app/ante"
chainparams "github.com/0glabs/0g-chain/app/params"
"github.com/0glabs/0g-chain/chaincfg"
dasignersprecompile "github.com/0glabs/0g-chain/precompiles/dasigners"
const (
appName = "kava"
"github.com/0glabs/0g-chain/x/bep3"
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 (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome string
// ModuleBasics manages simple versions of full app modules.
// It's used for things such as codec registration and genesis file verification.
ModuleBasics = module.NewBasicManager(
@ -185,18 +152,15 @@ var (
upgradeclient.LegacyCancelProposalHandler,
ibcclientclient.UpdateClientProposalHandler,
ibcclientclient.UpgradeProposalHandler,
kavadistclient.ProposalHandler,
committeeclient.ProposalHandler,
earnclient.DepositProposalHandler,
earnclient.WithdrawProposalHandler,
communityclient.LendDepositProposalHandler,
communityclient.LendWithdrawProposalHandler,
}),
params.AppModuleBasic{},
crisis.AppModuleBasic{},
slashing.AppModuleBasic{},
ibc.AppModuleBasic{},
ibctm.AppModuleBasic{},
solomachine.AppModuleBasic{},
packetforward.AppModuleBasic{},
upgrade.AppModuleBasic{},
evidence.AppModuleBasic{},
authzmodule.AppModuleBasic{},
@ -204,25 +168,15 @@ var (
vesting.AppModuleBasic{},
evm.AppModuleBasic{},
feemarket.AppModuleBasic{},
kavadist.AppModuleBasic{},
auction.AppModuleBasic{},
issuance.AppModuleBasic{},
bep3.AppModuleBasic{},
pricefeed.AppModuleBasic{},
swap.AppModuleBasic{},
cdp.AppModuleBasic{},
hard.AppModuleBasic{},
committee.AppModuleBasic{},
incentive.AppModuleBasic{},
savings.AppModuleBasic{},
validatorvesting.AppModuleBasic{},
evmutil.AppModuleBasic{},
liquid.AppModuleBasic{},
earn.AppModuleBasic{},
router.AppModuleBasic{},
mint.AppModuleBasic{},
community.AppModuleBasic{},
metrics.AppModuleBasic{},
council.AppModuleBasic{},
dasigners.AppModuleBasic{},
consensus.AppModuleBasic{},
)
@ -238,20 +192,9 @@ var (
ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner},
evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // used for secure addition and subtraction of balance using module account
evmutiltypes.ModuleName: {authtypes.Minter, authtypes.Burner},
kavadisttypes.KavaDistMacc: {authtypes.Minter},
auctiontypes.ModuleName: nil,
issuancetypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner},
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},
communitytypes.ModuleName: nil,
}
)
@ -270,7 +213,6 @@ type Options struct {
MempoolAuthAddresses []sdk.AccAddress
EVMTrace string
EVMMaxGasWanted uint64
TelemetryOptions metricstypes.TelemetryOptions
}
// DefaultOptions is a sensible default Options value.
@ -279,7 +221,7 @@ var DefaultOptions = Options{
EVMMaxGasWanted: ethermintconfig.DefaultMaxTxGasWanted,
}
// App is the Kava ABCI application.
// App is the 0gChain ABCI application.
type App struct {
*baseapp.BaseApp
@ -305,28 +247,21 @@ type App struct {
crisisKeeper crisiskeeper.Keeper
slashingKeeper slashingkeeper.Keeper
ibcKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly
packetForwardKeeper *packetforwardkeeper.Keeper
evmKeeper *evmkeeper.Keeper
evmutilKeeper evmutilkeeper.Keeper
feeMarketKeeper feemarketkeeper.Keeper
upgradeKeeper upgradekeeper.Keeper
evidenceKeeper evidencekeeper.Keeper
transferKeeper ibctransferkeeper.Keeper
kavadistKeeper kavadistkeeper.Keeper
auctionKeeper auctionkeeper.Keeper
CouncilKeeper councilkeeper.Keeper
issuanceKeeper issuancekeeper.Keeper
bep3Keeper bep3keeper.Keeper
pricefeedKeeper pricefeedkeeper.Keeper
swapKeeper swapkeeper.Keeper
cdpKeeper cdpkeeper.Keeper
hardKeeper hardkeeper.Keeper
committeeKeeper committeekeeper.Keeper
incentiveKeeper incentivekeeper.Keeper
savingsKeeper savingskeeper.Keeper
liquidKeeper liquidkeeper.Keeper
earnKeeper earnkeeper.Keeper
routerKeeper routerkeeper.Keeper
vestingKeeper vestingkeeper.VestingKeeper
mintKeeper mintkeeper.Keeper
communityKeeper communitykeeper.Keeper
dasignersKeeper dasignerskeeper.Keeper
consensusParamsKeeper consensusparamkeeper.Keeper
// make scoped keepers public for test purposes
@ -344,12 +279,6 @@ type App struct {
}
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.
@ -358,7 +287,7 @@ func NewApp(
db dbm.DB,
homePath string,
traceStore io.Writer,
encodingConfig kavaparams.EncodingConfig,
encodingConfig chainparams.EncodingConfig,
options Options,
baseAppOptions ...func(*baseapp.BaseApp),
) *App {
@ -366,22 +295,24 @@ func NewApp(
legacyAmino := encodingConfig.Amino
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.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
keys := sdk.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey,
distrtypes.StoreKey, slashingtypes.StoreKey,
distrtypes.StoreKey, slashingtypes.StoreKey, packetforwardtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey,
upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey,
evmtypes.StoreKey, feemarkettypes.StoreKey, authzkeeper.StoreKey,
capabilitytypes.StoreKey, kavadisttypes.StoreKey, auctiontypes.StoreKey,
capabilitytypes.StoreKey,
issuancetypes.StoreKey, bep3types.StoreKey, pricefeedtypes.StoreKey,
swaptypes.StoreKey, cdptypes.StoreKey, hardtypes.StoreKey, communitytypes.StoreKey,
committeetypes.StoreKey, incentivetypes.StoreKey, evmutiltypes.StoreKey,
savingstypes.StoreKey, earntypes.StoreKey, minttypes.StoreKey,
committeetypes.StoreKey, evmutiltypes.StoreKey,
minttypes.StoreKey,
counciltypes.StoreKey,
dasignerstypes.StoreKey,
vestingtypes.StoreKey,
consensusparamtypes.StoreKey, crisistypes.StoreKey,
)
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey)
@ -415,22 +346,15 @@ func NewApp(
slashingSubspace := app.paramsKeeper.Subspace(slashingtypes.ModuleName)
govSubspace := app.paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable())
crisisSubspace := app.paramsKeeper.Subspace(crisistypes.ModuleName)
kavadistSubspace := app.paramsKeeper.Subspace(kavadisttypes.ModuleName)
auctionSubspace := app.paramsKeeper.Subspace(auctiontypes.ModuleName)
issuanceSubspace := app.paramsKeeper.Subspace(issuancetypes.ModuleName)
bep3Subspace := app.paramsKeeper.Subspace(bep3types.ModuleName)
pricefeedSubspace := app.paramsKeeper.Subspace(pricefeedtypes.ModuleName)
swapSubspace := app.paramsKeeper.Subspace(swaptypes.ModuleName)
cdpSubspace := app.paramsKeeper.Subspace(cdptypes.ModuleName)
hardSubspace := app.paramsKeeper.Subspace(hardtypes.ModuleName)
incentiveSubspace := app.paramsKeeper.Subspace(incentivetypes.ModuleName)
savingsSubspace := app.paramsKeeper.Subspace(savingstypes.ModuleName)
ibcSubspace := app.paramsKeeper.Subspace(ibcexported.ModuleName)
ibctransferSubspace := app.paramsKeeper.Subspace(ibctransfertypes.ModuleName)
packetforwardSubspace := app.paramsKeeper.Subspace(packetforwardtypes.ModuleName).WithKeyTable(packetforwardtypes.ParamKeyTable())
feemarketSubspace := app.paramsKeeper.Subspace(feemarkettypes.ModuleName)
evmSubspace := app.paramsKeeper.Subspace(evmtypes.ModuleName)
evmutilSubspace := app.paramsKeeper.Subspace(evmutiltypes.ModuleName)
earnSubspace := app.paramsKeeper.Subspace(earntypes.ModuleName)
mintSubspace := app.paramsKeeper.Subspace(minttypes.ModuleName)
// set the BaseApp's parameter store
@ -458,11 +382,14 @@ func NewApp(
app.loadBlockedMaccAddrs(),
govAuthAddrStr,
)
app.vestingKeeper = vestingkeeper.NewVestingKeeper(app.accountKeeper, app.bankKeeper, keys[vestingtypes.StoreKey])
app.stakingKeeper = stakingkeeper.NewKeeper(
appCodec,
keys[stakingtypes.StoreKey],
app.accountKeeper,
app.bankKeeper,
app.vestingKeeper,
govAuthAddrStr,
)
app.authzKeeper = authzkeeper.NewKeeper(
@ -537,44 +464,72 @@ func NewApp(
)
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(
appCodec, keys[evmtypes.StoreKey], tkeys[evmtypes.TransientKey],
govAuthAddr,
app.accountKeeper, evmBankKeeper, app.stakingKeeper, app.feeMarketKeeper,
nil, // precompiled contracts
geth.NewEVM,
options.EVMTrace,
evmSubspace,
precompiles,
)
app.evmutilKeeper.SetEvmKeeper(app.evmKeeper)
// It's important to note that the PFM Keeper must be initialized before the Transfer Keeper
app.packetForwardKeeper = packetforwardkeeper.NewKeeper(
appCodec,
keys[packetforwardtypes.StoreKey],
nil, // will be zero-value here, reference is set later on with SetTransferKeeper.
app.ibcKeeper.ChannelKeeper,
app.distrKeeper,
app.bankKeeper,
app.ibcKeeper.ChannelKeeper,
govAuthAddrStr,
)
app.transferKeeper = ibctransferkeeper.NewKeeper(
appCodec,
keys[ibctransfertypes.StoreKey],
ibctransferSubspace,
app.ibcKeeper.ChannelKeeper,
app.packetForwardKeeper,
app.ibcKeeper.ChannelKeeper,
&app.ibcKeeper.PortKeeper,
app.accountKeeper,
app.bankKeeper,
scopedTransferKeeper,
)
app.packetForwardKeeper.SetTransferKeeper(app.transferKeeper)
transferModule := transfer.NewAppModule(app.transferKeeper)
transferIBCModule := transfer.NewIBCModule(app.transferKeeper)
// allow ibc packet forwarding for ibc transfers.
// transfer stack contains (from top to bottom):
// - Packet Forward Middleware
// - Transfer
var transferStack ibcporttypes.IBCModule
transferStack = transfer.NewIBCModule(app.transferKeeper)
transferStack = packetforward.NewIBCMiddleware(
transferStack,
app.packetForwardKeeper,
0, // retries on timeout
packetforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp,
packetforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp,
)
// Create static IBC router, add transfer route, then set and seal it
ibcRouter := porttypes.NewRouter()
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferIBCModule)
ibcRouter := ibcporttypes.NewRouter()
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferStack)
app.ibcKeeper.SetRouter(ibcRouter)
app.auctionKeeper = auctionkeeper.NewKeeper(
appCodec,
keys[auctiontypes.StoreKey],
auctionSubspace,
app.bankKeeper,
app.accountKeeper,
)
app.issuanceKeeper = issuancekeeper.NewKeeper(
appCodec,
keys[issuancetypes.StoreKey],
@ -595,68 +550,6 @@ func NewApp(
keys[pricefeedtypes.StoreKey],
pricefeedSubspace,
)
swapKeeper := swapkeeper.NewKeeper(
appCodec,
keys[swaptypes.StoreKey],
swapSubspace,
app.accountKeeper,
app.bankKeeper,
)
cdpKeeper := cdpkeeper.NewKeeper(
appCodec,
keys[cdptypes.StoreKey],
cdpSubspace,
app.pricefeedKeeper,
app.auctionKeeper,
app.bankKeeper,
app.accountKeeper,
mAccPerms,
)
hardKeeper := hardkeeper.NewKeeper(
appCodec,
keys[hardtypes.StoreKey],
hardSubspace,
app.accountKeeper,
app.bankKeeper,
app.pricefeedKeeper,
app.auctionKeeper,
)
app.liquidKeeper = liquidkeeper.NewDefaultKeeper(
appCodec,
app.accountKeeper,
app.bankKeeper,
app.stakingKeeper,
&app.distrKeeper,
)
savingsKeeper := savingskeeper.NewKeeper(
appCodec,
keys[savingstypes.StoreKey],
savingsSubspace,
app.accountKeeper,
app.bankKeeper,
app.liquidKeeper,
)
earnKeeper := earnkeeper.NewKeeper(
appCodec,
keys[earntypes.StoreKey],
earnSubspace,
app.accountKeeper,
app.bankKeeper,
&app.liquidKeeper,
&hardKeeper,
&savingsKeeper,
&app.distrKeeper,
)
app.kavadistKeeper = kavadistkeeper.NewKeeper(
appCodec,
keys[kavadisttypes.StoreKey],
kavadistSubspace,
app.bankKeeper,
app.accountKeeper,
app.distrKeeper,
app.loadBlockedMaccAddrs(),
)
app.mintKeeper = mintkeeper.NewKeeper(
appCodec,
@ -668,49 +561,10 @@ func NewApp(
govAuthAddrStr,
)
// x/community's deposit/withdraw to lend proposals depend on hard keeper.
app.communityKeeper = communitykeeper.NewKeeper(
appCodec,
keys[communitytypes.StoreKey],
app.accountKeeper,
app.bankKeeper,
&cdpKeeper,
app.distrKeeper,
&hardKeeper,
&app.mintKeeper,
&app.kavadistKeeper,
app.stakingKeeper,
govAuthAddr,
)
app.incentiveKeeper = incentivekeeper.NewKeeper(
appCodec,
keys[incentivetypes.StoreKey],
incentiveSubspace,
app.bankKeeper,
&cdpKeeper,
&hardKeeper,
app.accountKeeper,
app.stakingKeeper,
&swapKeeper,
&savingsKeeper,
&app.liquidKeeper,
&earnKeeper,
app.mintKeeper,
app.distrKeeper,
app.pricefeedKeeper,
)
app.routerKeeper = routerkeeper.NewKeeper(
&app.earnKeeper,
app.liquidKeeper,
app.stakingKeeper,
)
// create committee keeper with router
committeeGovRouter := govv1beta1.NewRouter()
committeeGovRouter.
AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler).
AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)).
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.
@ -729,15 +583,8 @@ func NewApp(
stakingtypes.NewMultiStakingHooks(
app.distrKeeper.Hooks(),
app.slashingKeeper.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
// NOTE this must be done after any keepers referenced in the gov router (ie committee) are defined
govRouter := govv1beta1.NewRouter()
@ -746,9 +593,6 @@ func NewApp(
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.upgradeKeeper)).
AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper)).
AddRoute(kavadisttypes.RouterKey, kavadist.NewCommunityPoolMultiSpendProposalHandler(app.kavadistKeeper)).
AddRoute(earntypes.RouterKey, earn.NewCommunityPoolProposalHandler(app.earnKeeper)).
AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)).
AddRoute(committeetypes.RouterKey, committee.NewProposalHandler(app.committeeKeeper))
govConfig := govtypes.DefaultConfig()
@ -767,11 +611,14 @@ func NewApp(
// override x/gov tally handler with custom implementation
tallyHandler := NewTallyHandler(
app.govKeeper, *app.stakingKeeper, app.savingsKeeper, app.earnKeeper,
app.liquidKeeper, app.bankKeeper,
app.govKeeper, *app.stakingKeeper, app.bankKeeper,
)
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
// must be passed by reference here.)
app.mm = module.NewManager(
@ -787,38 +634,26 @@ func NewApp(
slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper, slashingSubspace),
consensus.NewAppModule(appCodec, app.consensusParamsKeeper),
ibc.NewAppModule(app.ibcKeeper),
packetforward.NewAppModule(app.packetForwardKeeper, packetforwardSubspace),
evm.NewAppModule(app.evmKeeper, app.accountKeeper),
feemarket.NewAppModule(app.feeMarketKeeper, feemarketSubspace),
upgrade.NewAppModule(&app.upgradeKeeper),
evidence.NewAppModule(app.evidenceKeeper),
transferModule,
vesting.NewAppModule(app.accountKeeper, app.bankKeeper),
vesting.NewAppModule(app.accountKeeper, app.bankKeeper, app.vestingKeeper),
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),
bep3.NewAppModule(app.bep3Keeper, app.accountKeeper, app.bankKeeper),
pricefeed.NewAppModule(app.pricefeedKeeper, app.accountKeeper),
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),
incentive.NewAppModule(app.incentiveKeeper, app.accountKeeper, app.bankKeeper, app.cdpKeeper),
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
mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper, nil, mintSubspace),
community.NewAppModule(app.communityKeeper, app.accountKeeper),
metrics.NewAppModule(options.TelemetryOptions),
)
// Warning: Some begin blockers must run before others. Ensure the dependencies are understood before modifying this list.
app.mm.SetOrderBeginBlockers(
metricstypes.ModuleName,
// Upgrade begin blocker runs migrations on the first block after an upgrade. It should run before any other module.
upgradetypes.ModuleName,
// Capability begin blocker runs non state changing initialization.
@ -828,7 +663,6 @@ func NewApp(
committeetypes.ModuleName,
// Community begin blocker should run before x/mint and x/kavadist since
// the disable inflation upgrade will update those modules' params.
communitytypes.ModuleName,
minttypes.ModuleName,
distrtypes.ModuleName,
// During begin block slashing happens after distr.BeginBlocker so that
@ -839,18 +673,12 @@ func NewApp(
stakingtypes.ModuleName,
feemarkettypes.ModuleName,
evmtypes.ModuleName,
kavadisttypes.ModuleName,
// 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.
auctiontypes.ModuleName,
cdptypes.ModuleName,
bep3types.ModuleName,
hardtypes.ModuleName,
issuancetypes.ModuleName,
incentivetypes.ModuleName,
ibcexported.ModuleName,
// Add all remaining modules with an empty begin blocker below since cosmos 0.45.0 requires it
swaptypes.ModuleName,
vestingtypes.ModuleName,
pricefeedtypes.ModuleName,
validatorvestingtypes.ModuleName,
@ -863,11 +691,8 @@ func NewApp(
paramstypes.ModuleName,
authz.ModuleName,
evmutiltypes.ModuleName,
savingstypes.ModuleName,
liquidtypes.ModuleName,
earntypes.ModuleName,
routertypes.ModuleName,
consensusparamtypes.ModuleName,
packetforwardtypes.ModuleName,
)
// Warning: Some end blockers must run before others. Ensure the dependencies are understood before modifying this list.
@ -881,19 +706,13 @@ func NewApp(
pricefeedtypes.ModuleName,
// Add all remaining modules with an empty end blocker below since cosmos 0.45.0 requires it
capabilitytypes.ModuleName,
incentivetypes.ModuleName,
issuancetypes.ModuleName,
slashingtypes.ModuleName,
distrtypes.ModuleName,
auctiontypes.ModuleName,
bep3types.ModuleName,
cdptypes.ModuleName,
hardtypes.ModuleName,
committeetypes.ModuleName,
upgradetypes.ModuleName,
evidencetypes.ModuleName,
kavadisttypes.ModuleName,
swaptypes.ModuleName,
vestingtypes.ModuleName,
ibcexported.ModuleName,
validatorvestingtypes.ModuleName,
@ -904,14 +723,9 @@ func NewApp(
paramstypes.ModuleName,
authz.ModuleName,
evmutiltypes.ModuleName,
savingstypes.ModuleName,
liquidtypes.ModuleName,
earntypes.ModuleName,
routertypes.ModuleName,
minttypes.ModuleName,
communitytypes.ModuleName,
metricstypes.ModuleName,
consensusparamtypes.ModuleName,
packetforwardtypes.ModuleName,
)
// Warning: Some init genesis methods must run before others. Ensure the dependencies are understood before modifying this list
@ -930,30 +744,19 @@ func NewApp(
ibctransfertypes.ModuleName,
evmtypes.ModuleName,
feemarkettypes.ModuleName,
kavadisttypes.ModuleName,
auctiontypes.ModuleName,
issuancetypes.ModuleName,
savingstypes.ModuleName,
bep3types.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,
evmutiltypes.ModuleName,
earntypes.ModuleName,
communitytypes.ModuleName,
genutiltypes.ModuleName, // runs arbitrary txs included in genisis state, so run after modules have been initialized
// Add all remaining modules with an empty InitGenesis below since cosmos 0.45.0 requires it
vestingtypes.ModuleName,
paramstypes.ModuleName,
upgradetypes.ModuleName,
validatorvestingtypes.ModuleName,
liquidtypes.ModuleName,
routertypes.ModuleName,
metricstypes.ModuleName,
consensusparamtypes.ModuleName,
packetforwardtypes.ModuleName,
crisistypes.ModuleName, // runs the invariants at genesis, should run after other modules
)
@ -1056,7 +859,7 @@ func (app *App) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.Res
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.
app.upgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
@ -1118,7 +921,7 @@ func RegisterAPIRouteRewrites(router *mux.Router) {
// Eg: querying /cosmos/distribution/v1beta1/community_pool will return
// the same response as querying /kava/community/v1beta1/total_balance
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 {
@ -1159,16 +962,6 @@ func (app *App) RegisterNodeService(clientCtx client.Context) {
func (app *App) loadBlockedMaccAddrs() map[string]bool {
modAccAddrs := app.ModuleAccountAddrs()
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.
}

View File

@ -8,6 +8,7 @@ import (
"testing"
"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"
@ -17,6 +18,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
solomachine "github.com/cosmos/ibc-go/v7/modules/light-clients/06-solomachine"
ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint"
evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/assert"
@ -24,11 +26,11 @@ import (
)
func TestNewApp(t *testing.T) {
SetSDKConfig()
chaincfg.SetSDKConfig()
NewApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db.NewMemDB(),
DefaultNodeHome,
chaincfg.DefaultNodeHome,
nil,
MakeEncodingConfig(),
DefaultOptions,
@ -36,9 +38,9 @@ func TestNewApp(t *testing.T) {
}
func TestExport(t *testing.T) {
SetSDKConfig()
chaincfg.SetSDKConfig()
db := db.NewMemDB()
app := NewApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, DefaultNodeHome, nil, MakeEncodingConfig(), DefaultOptions, baseapp.SetChainID(TestChainId))
app := NewApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, chaincfg.DefaultNodeHome, nil, MakeEncodingConfig(), DefaultOptions, baseapp.SetChainID(TestChainId))
genesisState := GenesisStateWithSingleValidator(&TestApp{App: *app}, NewDefaultGenesisState())
@ -151,7 +153,7 @@ func unmarshalJSONKeys(jsonBytes []byte) ([]string, error) {
func removeIbcTmModule(modules []string) []string {
var result []string
for _, str := range modules {
if str != ibctm.ModuleName {
if str != ibctm.ModuleName && str != solomachine.ModuleName {
result = append(result, str)
}
}

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 (
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.

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
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"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
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{}
@ -20,23 +16,16 @@ var _ govv1.TallyHandler = TallyHandler{}
type TallyHandler struct {
gk govkeeper.Keeper
stk stakingkeeper.Keeper
svk savingskeeper.Keeper
ek earnkeeper.Keeper
lk liquidkeeper.Keeper
bk bankkeeper.Keeper
}
// NewTallyHandler creates a new tally handler.
func NewTallyHandler(
gk govkeeper.Keeper, stk stakingkeeper.Keeper, svk savingskeeper.Keeper,
ek earnkeeper.Keeper, lk liquidkeeper.Keeper, bk bankkeeper.Keeper,
gk govkeeper.Keeper, stk stakingkeeper.Keeper, bk bankkeeper.Keeper,
) TallyHandler {
return TallyHandler{
gk: gk,
stk: stk,
svk: svk,
ek: ek,
lk: lk,
bk: bk,
}
}
@ -105,34 +94,34 @@ func (th TallyHandler) Tally(
})
// get voter bkava and update total voting power and results
addrBkava := th.getAddrBkava(ctx, voter).toCoins()
for _, coin := range addrBkava {
valAddr, err := liquidtypes.ParseLiquidStakingTokenDenom(coin.Denom)
if err != nil {
break
}
// addrBkava := th.getAddrBkava(ctx, voter).toCoins()
// for _, coin := range addrBkava {
// valAddr, err := liquidtypes.ParseLiquidStakingTokenDenom(coin.Denom)
// if err != nil {
// break
// }
// reduce delegator shares by the amount of voter bkava for the validator
valAddrStr := valAddr.String()
if val, ok := currValidators[valAddrStr]; ok {
val.DelegatorDeductions = val.DelegatorDeductions.Add(sdk.NewDecFromInt(coin.Amount))
currValidators[valAddrStr] = val
}
// // reduce delegator shares by the amount of voter bkava for the validator
// valAddrStr := valAddr.String()
// if val, ok := currValidators[valAddrStr]; ok {
// val.DelegatorDeductions = val.DelegatorDeductions.Add(sdk.NewDecFromInt(coin.Amount))
// currValidators[valAddrStr] = val
// }
// votingPower = amount of ukava coin
stakedCoins, err := th.lk.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin))
if err != nil {
// error is returned only if the bkava denom is incorrect, which should never happen here.
panic(err)
}
votingPower := sdk.NewDecFromInt(stakedCoins.Amount)
// // votingPower = amount of ukava coin
// stakedCoins, err := th.lk.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin))
// if err != nil {
// // error is returned only if the bkava denom is incorrect, which should never happen here.
// panic(err)
// }
// votingPower := sdk.NewDecFromInt(stakedCoins.Amount)
for _, option := range vote.Options {
subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight))
results[option.Option] = results[option.Option].Add(subPower)
}
totalVotingPower = totalVotingPower.Add(votingPower)
}
// for _, option := range vote.Options {
// subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight))
// results[option.Option] = results[option.Option].Add(subPower)
// }
// totalVotingPower = totalVotingPower.Add(votingPower)
// }
th.gk.DeleteVote(ctx, vote.ProposalId, voter)
return false
@ -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.
func (th TallyHandler) addBkavaFromWallet(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) {
coins := th.bk.GetAllBalances(ctx, addr)
for _, coin := range coins {
if th.lk.IsDerivativeDenom(ctx, coin.Denom) {
bkava.add(coin)
}
}
// coins := th.bk.GetAllBalances(ctx, addr)
// for _, coin := range coins {
// if th.lk.IsDerivativeDenom(ctx, coin.Denom) {
// bkava.add(coin)
// }
// }
}
// addBkavaFromSavings adds all addr deposits of bkava in x/savings.
func (th TallyHandler) addBkavaFromSavings(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) {
deposit, found := th.svk.GetDeposit(ctx, addr)
if !found {
return
}
for _, coin := range deposit.Amount {
if th.lk.IsDerivativeDenom(ctx, coin.Denom) {
bkava.add(coin)
}
}
// deposit, found := th.svk.GetDeposit(ctx, addr)
// if !found {
// return
// }
// for _, coin := range deposit.Amount {
// if th.lk.IsDerivativeDenom(ctx, coin.Denom) {
// bkava.add(coin)
// }
// }
}
// addBkavaFromEarn adds all addr deposits of bkava in x/earn.
func (th TallyHandler) addBkavaFromEarn(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) {
shares, found := th.ek.GetVaultAccountShares(ctx, addr)
if !found {
return
}
for _, share := range shares {
if th.lk.IsDerivativeDenom(ctx, share.Denom) {
if coin, err := th.ek.ConvertToAssets(ctx, share); err == nil {
bkava.add(coin)
}
}
}
// shares, found := th.ek.GetVaultAccountShares(ctx, addr)
// if !found {
// return
// }
// for _, share := range shares {
// if th.lk.IsDerivativeDenom(ctx, share.Denom) {
// if coin, err := th.ek.ConvertToAssets(ctx, share); err == nil {
// bkava.add(coin)
// }
// }
// }
}

View File

@ -17,8 +17,7 @@ import (
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/suite"
earntypes "github.com/kava-labs/kava/x/earn/types"
liquidtypes "github.com/kava-labs/kava/x/liquid/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
// d is an alias for sdk.MustNewDecFromStr
@ -271,39 +270,40 @@ func (suite *tallyHandlerSuite) newBondCoin(amount sdkmath.Int) sdk.Coin {
}
func (suite *tallyHandlerSuite) allowBKavaEarnDeposits() {
ek := suite.app.GetEarnKeeper()
earnParams := ek.GetParams(suite.ctx)
// ek := suite.app.GetEarnKeeper()
// earnParams := ek.GetParams(suite.ctx)
vault := earntypes.NewAllowedVault(
liquidtypes.DefaultDerivativeDenom,
earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS},
false,
nil,
)
// vault := earntypes.NewAllowedVault(
// liquidtypes.DefaultDerivativeDenom,
// earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS},
// false,
// nil,
// )
earnParams.AllowedVaults = append(earnParams.AllowedVaults, vault)
ek.SetParams(suite.ctx, earnParams)
// earnParams.AllowedVaults = append(earnParams.AllowedVaults, vault)
// ek.SetParams(suite.ctx, earnParams)
sk := suite.app.GetSavingsKeeper()
savingsParams := sk.GetParams(suite.ctx)
savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, liquidtypes.DefaultDerivativeDenom)
sk.SetParams(suite.ctx, savingsParams)
// sk := suite.app.GetSavingsKeeper()
// savingsParams := sk.GetParams(suite.ctx)
// savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, liquidtypes.DefaultDerivativeDenom)
// sk.SetParams(suite.ctx, savingsParams)
}
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)
suite.Require().NoError(err)
// err := ek.Deposit(suite.ctx, owner, derivative, earntypes.STRATEGY_TYPE_SAVINGS)
// suite.Require().NoError(err)
}
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))
suite.Require().NoError(err)
// minted, err := lk.MintDerivative(suite.ctx, owner, validator, suite.newBondCoin(amount))
// 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 {

View File

@ -41,22 +41,12 @@ import (
feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper"
"github.com/stretchr/testify/require"
auctionkeeper "github.com/kava-labs/kava/x/auction/keeper"
bep3keeper "github.com/kava-labs/kava/x/bep3/keeper"
cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper"
committeekeeper "github.com/kava-labs/kava/x/committee/keeper"
communitykeeper "github.com/kava-labs/kava/x/community/keeper"
earnkeeper "github.com/kava-labs/kava/x/earn/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"
"github.com/0glabs/0g-chain/chaincfg"
bep3keeper "github.com/0glabs/0g-chain/x/bep3/keeper"
committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper"
evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
issuancekeeper "github.com/0glabs/0g-chain/x/issuance/keeper"
pricefeedkeeper "github.com/0glabs/0g-chain/x/pricefeed/keeper"
)
var (
@ -89,7 +79,7 @@ type TestApp struct {
//
// Note, it also sets the sdk config with the app's address prefix, coin type, etc.
func NewTestApp() TestApp {
SetSDKConfig()
chaincfg.SetSDKConfig()
return NewTestAppFromSealed()
}
@ -101,7 +91,7 @@ func NewTestAppFromSealed() TestApp {
encCfg := MakeEncodingConfig()
app := NewApp(
log.NewNopLogger(), db, DefaultNodeHome, nil,
log.NewNopLogger(), db, chaincfg.DefaultNodeHome, nil,
encCfg, DefaultOptions, baseapp.SetChainID(TestChainId),
)
return TestApp{App: *app}
@ -117,24 +107,13 @@ func (tApp TestApp) GetDistrKeeper() distkeeper.Keeper { return tApp.di
func (tApp TestApp) GetGovKeeper() govkeeper.Keeper { return tApp.govKeeper }
func (tApp TestApp) GetCrisisKeeper() crisiskeeper.Keeper { return tApp.crisisKeeper }
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) GetBep3Keeper() bep3keeper.Keeper { return tApp.bep3Keeper }
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) GetIncentiveKeeper() incentivekeeper.Keeper { return tApp.incentiveKeeper }
func (tApp TestApp) GetEvmutilKeeper() evmutilkeeper.Keeper { return tApp.evmutilKeeper }
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) 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 {
return tApp.keys[key]
@ -174,7 +153,7 @@ func GenesisStateWithSingleValidator(
balances := []banktypes.Balance{
{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100000000000000))),
Coins: sdk.NewCoins(chaincfg.MakeCoinForGasDenom(100000000000000)),
},
}
@ -237,7 +216,7 @@ func genesisStateWithValSet(
}
// set validators and delegations
currentStakingGenesis := stakingtypes.GetGenesisStateFromAppState(app.appCodec, genesisState)
currentStakingGenesis.Params.BondDenom = "ukava"
currentStakingGenesis.Params.BondDenom = chaincfg.GasDenom // TODO:
stakingGenesis := stakingtypes.NewGenesisState(
currentStakingGenesis.Params,
@ -257,13 +236,13 @@ func genesisStateWithValSet(
for range delegations {
// 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
balances = append(balances, banktypes.Balance{
Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(),
Coins: sdk.Coins{sdk.NewCoin("ukava", bondAmt)},
Coins: sdk.Coins{chaincfg.MakeCoinForGasDenom(bondAmt)},
})
bankGenesis := banktypes.NewGenesisState(

View File

@ -1,3 +1,133 @@
package app
func (app App) RegisterUpgradeHandlers() {}
import (
"fmt"
"github.com/cosmos/cosmos-sdk/baseapp"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types"
crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
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"
packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/packetforward/types"
ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"
ibctmmigrations "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint/migrations"
)
const (
UpgradeName_Mainnet = "v0.26.0"
UpgradeName_Testnet = "v0.26.0-alpha.0"
CDPLiquidationBlockInterval = int64(50)
)
// RegisterUpgradeHandlers registers the upgrade handlers for the app.
func (app App) RegisterUpgradeHandlers() {
app.upgradeKeeper.SetUpgradeHandler(
UpgradeName_Mainnet,
upgradeHandler(app, UpgradeName_Mainnet),
)
app.upgradeKeeper.SetUpgradeHandler(
UpgradeName_Testnet,
upgradeHandler(app, UpgradeName_Testnet),
)
upgradeInfo, err := app.upgradeKeeper.ReadUpgradeInfoFromDisk()
if err != nil {
panic(err)
}
doUpgrade := upgradeInfo.Name == UpgradeName_Mainnet ||
upgradeInfo.Name == UpgradeName_Testnet
if doUpgrade && !app.upgradeKeeper.IsSkipHeight(upgradeInfo.Height) {
storeUpgrades := storetypes.StoreUpgrades{
Added: []string{
crisistypes.ModuleName,
consensustypes.ModuleName,
packetforwardtypes.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,
) 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))
baseAppLegacySS := app.paramsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable())
// Set param key table for params module migration
for _, subspace := range app.paramsKeeper.GetSubspaces() {
subspace := subspace
var keyTable paramstypes.KeyTable
switch subspace.Name() {
// sdk
case authtypes.ModuleName:
keyTable = authtypes.ParamKeyTable() //nolint:staticcheck
case banktypes.ModuleName:
keyTable = banktypes.ParamKeyTable() //nolint:staticcheck,nolintlint
case stakingtypes.ModuleName:
keyTable = stakingtypes.ParamKeyTable()
case minttypes.ModuleName:
keyTable = minttypes.ParamKeyTable() //nolint:staticcheck
case distrtypes.ModuleName:
keyTable = distrtypes.ParamKeyTable() //nolint:staticcheck,nolintlint
case slashingtypes.ModuleName:
keyTable = slashingtypes.ParamKeyTable() //nolint:staticcheck
case govtypes.ModuleName:
keyTable = govv1.ParamKeyTable() //nolint:staticcheck
case crisistypes.ModuleName:
keyTable = crisistypes.ParamKeyTable() //nolint:staticcheck
// ibc
case ibctransfertypes.ModuleName:
keyTable = ibctransfertypes.ParamKeyTable() //nolint:staticcheck
default:
continue
}
if !subspace.HasKeyTable() {
// NOTE: This modifies the internal map used to store the key table entries
// which is a pointer.
subspace.WithKeyTable(keyTable)
}
}
// optional migration: prune expired tendermint consensus states to save storage space
// see https://github.com/cosmos/ibc-go/blob/v7.2.0/docs/migrations/v6-to-v7.md#chains
if _, err := ibctmmigrations.PruneExpiredConsensusStates(ctx, app.appCodec, app.ibcKeeper.ClientKeeper); err != nil {
return nil, err
}
// migrate tendermint consensus parameters from x/params module to a
// dedicated x/consensus module.
baseapp.MigrateParams(ctx, baseAppLegacySS, &app.consensusParamsKeeper)
// run migrations for all modules and return new consensus version map
versionMap, err := app.mm.RunMigrations(ctx, app.configurator, fromVM)
return versionMap, err
}
}

View File

@ -7,7 +7,7 @@ proto-lint check-proto-lint: install-build-deps
proto-gen: install-build-deps
@echo "Generating go proto files"
@$(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
.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))
}

17
chaincfg/config.go Normal file
View File

@ -0,0 +1,17 @@
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

@ -582,6 +582,10 @@
"denom": "erc20/axelar/wbtc",
"amount": "1000000000"
},
{
"denom": "erc20/tether/usdt",
"amount": "100000000000"
},
{
"denom": "hard",
"amount": "1000000000"

View File

@ -3000,6 +3000,12 @@
}
},
"params": null,
"packetfowardmiddleware": {
"params": {
"fee_percentage": "0.000000000000000000"
},
"in_flight_packets": {}
},
"pricefeed": {
"params": {
"markets": [

View File

@ -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")
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
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.Equal(t, "kava1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj", f.KeyAddress("test-recover-legacy").String())
require.Equal(t, "0g1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj", f.KeyAddress("test-recover-legacy").String())
// Cleanup testing directories
f.Cleanup()
}
func TestKavaCLIKeysAddRecoverHDPath(t *testing.T) {
func TestZgChainCLIKeysAddRecoverHDPath(t *testing.T) {
t.Parallel()
f := InitFixtures(t)
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)
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)
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)
require.Equal(t, "kava1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH4").String())
require.Equal(t, "0g1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH4").String())
// 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")
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")
require.False(t, exitSuccess)
@ -99,11 +99,11 @@ func TestKavaCLIKeysAddRecoverHDPath(t *testing.T) {
// 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")
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")
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
f.Cleanup()

View File

@ -28,7 +28,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/slashing"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/kava-labs/kava/app"
"github.com/0glabs/0g-chain/app"
)
const (
@ -65,8 +65,7 @@ var (
func init() {
// set the address prefixes
config := sdk.GetConfig()
app.SetBech32AddressPrefixes(config)
chaincfg.SetSDKConfig()
// config.Seal()
}
@ -92,7 +91,7 @@ type Fixtures struct {
// NewFixtures creates a new instance of Fixtures with many vars set
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)
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) {
cmd := fmt.Sprintf("%s --home=%s unsafe-reset-all", f.KvdBinary, f.KvdHome)
executeWrite(f.T, addFlags(cmd, flags))
@ -211,7 +210,7 @@ func (f *Fixtures) UnsafeResetAll(flags ...string) {
require.NoError(f.T, err)
}
// KvInit is kavad init
// KvInit is 0gchaind init
// NOTE: KvInit sets the ChainID for the Fixtures instance
func (f *Fixtures) KvInit(moniker string, flags ...string) {
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
}
// AddGenesisAccount is kavad add-genesis-account
// AddGenesisAccount is 0gchaind add-genesis-account
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)
executeWriteCheckErr(f.T, addFlags(cmd, flags))
}
// GenTx is kavad gentx
// GenTx is 0gchaind gentx
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)
executeWriteCheckErr(f.T, addFlags(cmd, flags))
}
// CollectGenTxs is kavad collect-gentxs
// CollectGenTxs is 0gchaind collect-gentxs
func (f *Fixtures) CollectGenTxs(flags ...string) {
cmd := fmt.Sprintf("%s collect-gentxs --home=%s", f.KvdBinary, f.KvdHome)
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 {
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))
@ -256,7 +255,7 @@ func (f *Fixtures) GDStart(flags ...string) *tests.Process {
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 {
cmd := fmt.Sprintf("%s tendermint %s --home=%s", f.KvdBinary, query, f.KvdHome)
success, stdout, stderr := executeWriteRetStdStreams(f.T, cmd)
@ -265,7 +264,7 @@ func (f *Fixtures) GDTendermint(query string) string {
return strings.TrimSpace(stdout)
}
// ValidateGenesis runs kavad validate-genesis
// ValidateGenesis runs 0gchaind validate-genesis
func (f *Fixtures) ValidateGenesis() {
cmd := fmt.Sprintf("%s validate-genesis --home=%s", f.KvdBinary, f.KvdHome)
executeWriteCheckErr(f.T, cmd)

View File

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

View File

@ -5,7 +5,7 @@ info:
version: 1.0.0
externalDocs:
description: GitHub
url: https://github.com/Kava-Labs/kava
url: https://github.com/0glabs/0g-chain
host: api.data.kava.io
schemes:
- https

View File

@ -16,7 +16,7 @@ The Kava gRPC client is a tool for making gRPC queries on a Kava chain.
package main
import (
kavaGrpc "github.com/kava-labs/kava/client/grpc"
kavaGrpc "github.com/0glabs/0g-chain/client/grpc"
)
grpcUrl := "https://grpc.kava.io:443"
client, err := kavaGrpc.NewClient(grpcUrl)
@ -46,7 +46,7 @@ Example: Query Kava module `x/evmutil` for params
```go
import (
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types"
evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
)
rsp, err := client.Query.Evmutil.Params(

View File

@ -3,8 +3,8 @@ package grpc
import (
"errors"
"github.com/kava-labs/kava/client/grpc/query"
"github.com/kava-labs/kava/client/grpc/util"
"github.com/0glabs/0g-chain/client/grpc/query"
"github.com/0glabs/0g-chain/client/grpc/util"
)
// KavaGrpcClient enables the usage of kava grpc query clients and query utils

View File

@ -3,7 +3,7 @@ package grpc_test
import (
"testing"
"github.com/kava-labs/kava/client/grpc"
"github.com/0glabs/0g-chain/client/grpc"
"github.com/stretchr/testify/require"
)

View File

@ -8,6 +8,7 @@ import (
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"
consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/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"
@ -23,21 +24,11 @@ import (
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"
bep3types "github.com/0glabs/0g-chain/x/bep3/types"
committeetypes "github.com/0glabs/0g-chain/x/committee/types"
evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
issuancetypes "github.com/0glabs/0g-chain/x/issuance/types"
pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
)
// QueryClient is a wrapper with all Cosmos and Kava grpc query clients
@ -58,6 +49,7 @@ type QueryClient struct {
Slashing slashingtypes.QueryClient
Staking stakingtypes.QueryClient
Upgrade upgradetypes.QueryClient
Consensus consensustypes.QueryClient
// 3rd party query clients
@ -106,6 +98,7 @@ func NewQueryClient(grpcEndpoint string) (*QueryClient, error) {
Slashing: slashingtypes.NewQueryClient(conn),
Staking: stakingtypes.NewQueryClient(conn),
Upgrade: upgradetypes.NewQueryClient(conn),
Consensus: consensustypes.NewQueryClient(conn),
Evm: evmtypes.NewQueryClient(conn),
Feemarket: feemarkettypes.NewQueryClient(conn),

View File

@ -3,7 +3,7 @@ package query_test
import (
"testing"
"github.com/kava-labs/kava/client/grpc/query"
"github.com/0glabs/0g-chain/client/grpc/query"
"github.com/stretchr/testify/require"
)
@ -46,6 +46,7 @@ func TestNewQueryClient_ValidClient(t *testing.T) {
require.NotNil(t, client.Slashing)
require.NotNil(t, client.Staking)
require.NotNil(t, client.Upgrade)
require.NotNil(t, client.Consensus)
// validate 3rd party clients
require.NotNil(t, client.Evm)

View File

@ -7,9 +7,9 @@ import (
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"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/params"
query "github.com/0glabs/0g-chain/client/grpc/query"
)
// Util contains utility functions for the Kava gRPC client

View File

@ -132,7 +132,7 @@ func (br BaseReq) ValidateBasic(w http.ResponseWriter) bool {
return true
}
// ReadRESTReq reads and unmarshals a Request's body to the the BaseReq struct.
// ReadRESTReq reads and unmarshals a Request's body to the BaseReq struct.
// Writes an error response to ResponseWriter and returns false if errors occurred.
func ReadRESTReq(w http.ResponseWriter, r *http.Request, cdc *codec.LegacyAmino, req interface{}) bool {
body, err := io.ReadAll(r.Body)

View File

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

View File

@ -1,4 +1,4 @@
package cmd
package main
import (
"errors"
@ -23,17 +23,17 @@ import (
"github.com/spf13/cast"
"github.com/spf13/cobra"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/params"
metricstypes "github.com/kava-labs/kava/x/metrics/types"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/params"
)
const (
flagMempoolEnableAuth = "mempool.enable-authentication"
flagMempoolAuthAddresses = "mempool.authorized-addresses"
flagSkipLoadLatest = "skip-load-latest"
)
// 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
type appCreator struct {
encodingConfig params.EncodingConfig
@ -46,6 +46,7 @@ func (ac appCreator) newApp(
traceStore io.Writer,
appOpts servertypes.AppOptions,
) servertypes.Application {
fmt.Println("newApp")
var cache sdk.MultiStorePersistentCache
if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) {
cache = store.NewCommitKVStoreCacheManager()
@ -101,10 +102,15 @@ func (ac appCreator) newApp(
chainID = appGenesis.ChainID
}
skipLoadLatest := false
if appOpts.Get(flagSkipLoadLatest) != nil {
skipLoadLatest = cast.ToBool(appOpts.Get(flagSkipLoadLatest))
}
return app.NewApp(
logger, db, homeDir, traceStore, ac.encodingConfig,
app.Options{
SkipLoadLatest: false,
SkipLoadLatest: skipLoadLatest,
SkipUpgradeHeights: skipUpgradeHeights,
SkipGenesisInvariants: cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)),
InvariantCheckPeriod: cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
@ -112,7 +118,6 @@ func (ac appCreator) newApp(
MempoolAuthAddresses: mempoolAuthAddresses,
EVMTrace: cast.ToString(appOpts.Get(ethermintflags.EVMTracer)),
EVMMaxGasWanted: cast.ToUint64(appOpts.Get(ethermintflags.EVMMaxTxGasWanted)),
TelemetryOptions: metricstypes.TelemetryOptionsFromAppOpts(appOpts),
},
baseapp.SetPruning(pruningOpts),
baseapp.SetMinGasPrices(strings.Replace(cast.ToString(appOpts.Get(server.FlagMinGasPrices)), ";", ",", -1)),

View File

@ -1,4 +1,4 @@
package cmd
package main
import (
"encoding/json"
@ -9,8 +9,8 @@ import (
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/spf13/cobra"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/params"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/params"
)
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
package cmd
package main
import (
"bufio"

View File

@ -0,0 +1,56 @@
package iavlviewer
import (
"crypto/sha256"
"fmt"
"github.com/cosmos/iavl"
ethermintserver "github.com/evmos/ethermint/server"
"github.com/spf13/cobra"
)
func newDataCmd(opts ethermintserver.StartOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "data <prefix> [version number]",
Short: "View all keys, hash, & size of tree.",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
prefix := args[0]
version := 0
if len(args) == 2 {
var err error
version, err = parseVersion(args[1])
if err != nil {
return err
}
}
tree, err := openPrefixTree(opts, cmd, prefix, version)
if err != nil {
return err
}
printKeys(tree)
hash, err := tree.Hash()
if err != nil {
return err
}
fmt.Printf("Hash: %X\n", hash)
fmt.Printf("Size: %X\n", tree.Size())
return nil
},
}
return cmd
}
func printKeys(tree *iavl.MutableTree) {
fmt.Println("Printing all keys with hashed values (to detect diff)")
tree.Iterate(func(key []byte, value []byte) bool { //nolint:errcheck
printKey := parseWeaveKey(key)
digest := sha256.Sum256(value)
fmt.Printf(" %s\n %X\n", printKey, digest)
return false
})
}

View File

@ -0,0 +1,42 @@
package iavlviewer
import (
"fmt"
ethermintserver "github.com/evmos/ethermint/server"
"github.com/spf13/cobra"
)
func newHashCmd(opts ethermintserver.StartOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "hash <prefix> [version number]",
Short: "Print the root hash of the iavl tree.",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
prefix := args[0]
version := 0
if len(args) == 2 {
var err error
version, err = parseVersion(args[1])
if err != nil {
return err
}
}
tree, err := openPrefixTree(opts, cmd, prefix, version)
if err != nil {
return err
}
hash, err := tree.Hash()
if err != nil {
return err
}
fmt.Printf("Hash: %X\n", hash)
return nil
},
}
return cmd
}

View File

@ -0,0 +1,83 @@
package iavlviewer
import (
"fmt"
"strconv"
dbm "github.com/cometbft/cometbft-db"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/server"
ethermintserver "github.com/evmos/ethermint/server"
"github.com/spf13/cobra"
"github.com/cosmos/iavl"
)
const (
DefaultCacheSize int = 10000
)
func NewCmd(opts ethermintserver.StartOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "iavlviewer <data|hash|shape|versions> <prefix> [version number]",
Short: "Output various data, hashes, and calculations for an iavl tree",
}
cmd.AddCommand(newDataCmd(opts))
cmd.AddCommand(newHashCmd(opts))
cmd.AddCommand(newShapeCmd(opts))
cmd.AddCommand(newVersionsCmd(opts))
return cmd
}
func parseVersion(arg string) (int, error) {
version, err := strconv.Atoi(arg)
if err != nil {
return 0, fmt.Errorf("invalid version number: '%s'", arg)
}
return version, nil
}
func openPrefixTree(opts ethermintserver.StartOptions, cmd *cobra.Command, prefix string, version int) (*iavl.MutableTree, error) {
clientCtx := client.GetClientContextFromCmd(cmd)
ctx := server.GetServerContextFromCmd(cmd)
ctx.Config.SetRoot(clientCtx.HomeDir)
db, err := opts.DBOpener(ctx.Viper, clientCtx.HomeDir, server.GetAppDBBackend(ctx.Viper))
if err != nil {
return nil, fmt.Errorf("failed to open database at %s: %s", clientCtx.HomeDir, err)
}
defer func() {
if err := db.Close(); err != nil {
ctx.Logger.Error("error closing db", "error", err.Error())
}
}()
tree, err := readTree(db, version, []byte(prefix))
if err != nil {
return nil, fmt.Errorf("failed to read tree with prefix %s: %s", prefix, err)
}
return tree, nil
}
// ReadTree loads an iavl tree from the directory
// If version is 0, load latest, otherwise, load named version
// The prefix represents which iavl tree you want to read. The iaviwer will always set a prefix.
func readTree(db dbm.DB, version int, prefix []byte) (*iavl.MutableTree, error) {
if len(prefix) != 0 {
db = dbm.NewPrefixDB(db, prefix)
}
tree, err := iavl.NewMutableTree(db, DefaultCacheSize, false)
if err != nil {
return nil, err
}
ver, err := tree.LoadVersion(int64(version))
if err != nil {
return nil, err
}
fmt.Printf("Latest version: %d\n", ver)
fmt.Printf("Got version: %d\n", version)
return tree, err
}

View File

@ -0,0 +1,47 @@
package iavlviewer
import (
"fmt"
"strings"
"github.com/cosmos/iavl"
ethermintserver "github.com/evmos/ethermint/server"
"github.com/spf13/cobra"
)
func newShapeCmd(opts ethermintserver.StartOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "shape <prefix> [version number]",
Short: "View shape of iavl tree.",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
prefix := args[0]
version := 0
if len(args) == 2 {
var err error
version, err = parseVersion(args[1])
if err != nil {
return err
}
}
tree, err := openPrefixTree(opts, cmd, prefix, version)
if err != nil {
return err
}
printShape(tree)
return nil
},
}
return cmd
}
func printShape(tree *iavl.MutableTree) {
// shape := tree.RenderShape(" ", nil)
// TODO: handle this error
shape, _ := tree.RenderShape(" ", nodeEncoder)
fmt.Println(strings.Join(shape, "\n"))
}

View File

@ -0,0 +1,74 @@
package iavlviewer
import (
"bytes"
"encoding/hex"
"fmt"
"strings"
"github.com/cosmos/iavl"
ethermintserver "github.com/evmos/ethermint/server"
"github.com/spf13/cobra"
)
func newVersionsCmd(opts ethermintserver.StartOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "versions <prefix>",
Short: "Print all versions of iavl tree",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
prefix := args[0]
tree, err := openPrefixTree(opts, cmd, prefix, 15)
if err != nil {
return err
}
printVersions(tree)
return nil
},
}
return cmd
}
func printVersions(tree *iavl.MutableTree) {
versions := tree.AvailableVersions()
fmt.Println("Available versions:")
for _, v := range versions {
fmt.Printf(" %d\n", v)
}
}
// parseWeaveKey assumes a separating : where all in front should be ascii,
// and all afterwards may be ascii or binary
func parseWeaveKey(key []byte) string {
cut := bytes.IndexRune(key, ':')
if cut == -1 {
return encodeID(key)
}
prefix := key[:cut]
id := key[cut+1:]
return fmt.Sprintf("%s:%s", encodeID(prefix), encodeID(id))
}
// casts to a string if it is printable ascii, hex-encodes otherwise
func encodeID(id []byte) string {
for _, b := range id {
if b < 0x20 || b >= 0x80 {
return strings.ToUpper(hex.EncodeToString(id))
}
}
return string(id)
}
func nodeEncoder(id []byte, depth int, isLeaf bool) string {
prefix := fmt.Sprintf("-%d ", depth)
if isLeaf {
prefix = fmt.Sprintf("*%d ", depth)
}
if len(id) == 0 {
return fmt.Sprintf("%s<nil>", prefix)
}
return fmt.Sprintf("%s%s", prefix, parseWeaveKey(id))
}

View File

@ -1,4 +1,4 @@
package cmd
package main
import (
"bufio"

View File

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

View File

@ -1,4 +1,4 @@
package cmd
package main
import (
"github.com/cosmos/cosmos-sdk/client"
@ -7,7 +7,7 @@ import (
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"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.

View File

@ -1,4 +1,4 @@
package cmd
package main
import (
"fmt"
@ -8,6 +8,7 @@ import (
"github.com/cosmos/cosmos-sdk/client/config"
"github.com/cosmos/cosmos-sdk/client/debug"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
tmcfg "github.com/cometbft/cometbft/config"
@ -23,21 +24,25 @@ import (
servercfg "github.com/evmos/ethermint/server/config"
"github.com/spf13/cobra"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/app/params"
"github.com/kava-labs/kava/cmd/kava/cmd/rocksdb"
"github.com/kava-labs/kava/cmd/kava/opendb"
"github.com/0glabs/0g-chain/app"
"github.com/0glabs/0g-chain/app/params"
"github.com/0glabs/0g-chain/chaincfg"
"github.com/0glabs/0g-chain/cmd/0gchaind/iavlviewer"
"github.com/0glabs/0g-chain/cmd/0gchaind/rocksdb"
"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.
const EnvPrefix = "KAVA"
func customKeyringOptions() keyring.Option {
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 {
app.SetSDKConfig().Seal()
encodingConfig := app.MakeEncodingConfig()
initClientCtx := client.Context{}.
WithCodec(encodingConfig.Marshaler).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
@ -46,13 +51,12 @@ func NewRootCmd() *cobra.Command {
WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}).
WithBroadcastMode(flags.FlagBroadcastMode).
WithHomeDir(app.DefaultNodeHome).
WithKeyringOptions(hd.EthSecp256k1Option()).
WithViper(EnvPrefix)
WithHomeDir(chaincfg.DefaultNodeHome).
WithKeyringOptions(customKeyringOptions()).
WithViper(chaincfg.EnvPrefix)
rootCmd := &cobra.Command{
Use: "kava",
Short: "Daemon and CLI for the Kava blockchain.",
Use: chaincfg.AppName,
Short: "Daemon and CLI for the 0g-chain blockchain.",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())
@ -71,7 +75,7 @@ func NewRootCmd() *cobra.Command {
return err
}
customAppTemplate, customAppConfig := servercfg.AppConfig("ukava")
customAppTemplate, customAppConfig := servercfg.AppConfig(chaincfg.GasDenom)
return server.InterceptConfigsPreRunHandler(
cmd,
@ -82,12 +86,11 @@ func NewRootCmd() *cobra.Command {
},
}
addSubCmds(rootCmd, encodingConfig, app.DefaultNodeHome)
addSubCmds(rootCmd, encodingConfig, chaincfg.DefaultNodeHome)
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) {
gentxModule, ok := app.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic)
if !ok {
@ -116,7 +119,7 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de
opts := ethermintserver.StartOptions{
AppCreator: ac.newApp,
DefaultNodeHome: app.DefaultNodeHome,
DefaultNodeHome: chaincfg.DefaultNodeHome,
DBOpener: opendb.OpenDB,
}
// ethermintserver adds additional flags to start the JSON-RPC server for evm support
@ -131,8 +134,9 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de
rootCmd.AddCommand(
newQueryCmd(),
newTxCmd(),
keyCommands(app.DefaultNodeHome),
keyCommands(chaincfg.DefaultNodeHome),
rocksdb.RocksDBCmd,
newShardCmd(opts),
iavlviewer.NewCmd(opts),
)
}

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

@ -0,0 +1,319 @@
package main
import (
"fmt"
"strings"
"github.com/0glabs/0g-chain/app"
"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"
flagShardForceAppVersion = "force-app-version"
flagShardOnlyCometbftState = "only-cometbft-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] [--only-cometbft-state] [--force-app-version <app-version>]",
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 application.db can be loaded at a particular height via the --force-app-version option. This is useful if the sharding process is prematurely terminated while the application.db is being sharded.
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.
Similarly, the --only-cometbft-state flag skips pruning app state. This can be useful if the shard command is prematurely terminated during the shard process.
The shard command only flags the iavl tree nodes for deletion. Actual removal from the databases will be performed when each database is compacted.
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 {
//////////////////////////
// parse & 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
}
forceAppVersion, err := cmd.Flags().GetInt64(flagShardForceAppVersion)
if err != nil {
return err
}
onlyCometbftState, err := cmd.Flags().GetBool(flagShardOnlyCometbftState)
if err != nil {
return err
}
clientCtx := client.GetClientContextFromCmd(cmd)
ctx := server.GetServerContextFromCmd(cmd)
ctx.Config.SetRoot(clientCtx.HomeDir)
////////////////////////
// manage db connection
////////////////////////
// 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())
}
}()
///////////////////
// load multistore
///////////////////
// create app in order to load the multistore
// skip loading the latest version so the desired height can be manually loaded
ctx.Viper.Set("skip-load-latest", true)
app := opts.AppCreator(ctx.Logger, db, nil, ctx.Viper).(*app.App)
if forceAppVersion == shardEndBlockLatest {
if err := app.LoadLatestVersion(); err != nil {
return err
}
} else {
if err := app.LoadVersion(forceAppVersion); err != nil {
return err
}
}
// get the multistore
cms := app.CommitMultiStore()
multistore, ok := cms.(*rootmulti.Store)
if !ok {
return fmt.Errorf("only sharding of rootmulti.Store type is supported")
}
////////////////////////
// shard application.db
////////////////////////
if !onlyCometbftState {
if err := shardApplicationDb(multistore, startBlock, endBlock); err != nil {
return err
}
} else {
fmt.Printf("[%s] skipping sharding of application.db\n", flagShardOnlyCometbftState)
}
//////////////////////////////////
// shard blockstore.db & state.db
//////////////////////////////////
// open block store & cometbft state
blockStore, stateStore, err := openCometBftDbs(ctx.Config)
if err != nil {
return fmt.Errorf("failed to open cometbft dbs: %s", err)
}
if !onlyAppState {
if err := shardCometBftDbs(blockStore, stateStore, startBlock, endBlock); err != nil {
return err
}
} else {
fmt.Printf("[%s] skipping sharding of blockstore.db and state.db\n", flagShardOnlyAppState)
fmt.Printf("blockstore contains blocks %d - %d\n", blockStore.Base(), blockStore.Height())
}
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")
cmd.Flags().Bool(flagShardOnlyCometbftState, false, "Skip pruning of application state")
cmd.Flags().Int64(flagShardForceAppVersion, shardEndBlockLatest, "Instead of loading latest, force set the version of the multistore that is loaded")
return cmd
}
// shardApplicationDb prunes the multistore up to startBlock and rolls it back to endBlock
func shardApplicationDb(multistore *rootmulti.Store, startBlock, endBlock int64) error {
//////////////////////////////
// Rollback state to endBlock
//////////////////////////////
// handle desired endblock being latest
latest := multistore.LastCommitID().Version
if latest == 0 {
return fmt.Errorf("failed to find latest height >0")
}
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 down to heights %d - %d (%d blocks)\n", 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)
}
//////////////////////////////
// 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 {
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)
}
}
return nil
}
// shardCometBftDbs shrinks blockstore.db & state.db down to the desired block range
func shardCometBftDbs(blockStore *store.BlockStore, stateStore tmstate.Store, startBlock, endBlock int64) error {
var err error
latest := blockStore.Height()
if endBlock == shardEndBlockLatest {
endBlock = latest
}
//////////////////////////////
// Rollback state to endBlock
//////////////////////////////
// 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 {
beforeRollbackHeight := height
printRollbackProgress(height - 1)
height, _, err = tmstate.Rollback(blockStore, stateStore, true)
if err != nil {
return fmt.Errorf("failed to rollback cometbft state: %w", err)
}
if beforeRollbackHeight == height {
return fmt.Errorf("attempting to rollback cometbft state height %d failed (no rollback performed)", height)
}
}
if needsRollback {
fmt.Println()
} else {
fmt.Printf("latest store height is already %d\n", latest)
}
//////////////////////////////
// Prune blocks to startBlock
//////////////////////////////
// get starting block of block store
baseBlock := blockStore.Base()
// only prune if data exists, otherwise blockStore.PruneBlocks will panic
if 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)
}
return nil
}
// 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,4 +1,4 @@
package cmd
package main
import (
"context"

View File

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

View File

@ -1,232 +0,0 @@
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

@ -4,11 +4,11 @@ pragma solidity ^0.8.18;
import "@openzeppelin/contracts/token/ERC20/ERC20.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.
/// @author Kava Labs, LLC
/// @custom:security-contact security@kava.io
contract ERC20KavaWrappedCosmosCoin is ERC20, Ownable {
/// @author 0g Labs, LLC
/// @custom:security-contact security@0g.ai
contract ERC20ZgChainWrappedCosmosCoin is ERC20, Ownable {
/// @notice The decimals places of the token. For display purposes only.
uint8 private immutable _decimals;

View File

@ -5,7 +5,7 @@ const config: HardhatUserConfig = {
solidity: {
version: "0.8.18",
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",
// optimize build for deployment to mainnet!
optimizer: {
@ -16,21 +16,21 @@ const config: HardhatUserConfig = {
},
networks: {
// kvtool's local network
kava: {
chain: {
url: "http://127.0.0.1:8545",
accounts: [
// kava keys unsafe-export-eth-key whale2
// 0g-chain keys unsafe-export-eth-key whale2
"AA50F4C6C15190D9E18BF8B14FC09BFBA0E7306331A4F232D10A77C2879E7966",
],
},
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: [
"247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9",
],
},
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: [
"247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9",
],

View File

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

View File

@ -1,9 +1,9 @@
{
"name": "kava-contracts",
"name": "0g-chain-contracts",
"version": "0.0.1",
"author": "Kava Labs",
"author": "0g Labs",
"private": true,
"description": "Solidity contracts for Kava Blockchain",
"description": "Solidity contracts for 0g Blockchain",
"engines": {
"node": ">=18.0.0"
},
@ -12,7 +12,7 @@
"clean": "hardhat clean",
"compile": "hardhat compile",
"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",
"lint": "eslint '**/*.{js,ts}'",
"lint-fix": "eslint '**/*.{js,ts}' --fix",

View File

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

View File

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

View File

@ -106,4 +106,4 @@ jq '.app_state.earn.params.allowed_vaults = [
jq '.app_state.savings.params.supported_denoms = ["bkava-kavavaloper1ffv7nhd3z6sych2qpqkk03ec6hzkmufyz4scd0"]' $DATA/config/genesis.json | sponge $DATA/config/genesis.json
$BINARY config broadcast-mode block
$BINARY config broadcast-mode sync

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/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// 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"
tmcrypto "github.com/cometbft/cometbft/crypto"
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"
)
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:
kvdnode0:
container_name: kvdnode0
image: "kava/kavanode"
image: "0glabs/0g-chain-node"
ports:
- "26656-26657:26656-26657"
environment:
@ -17,7 +17,7 @@ services:
kvdnode1:
container_name: kvdnode1
image: "kava/kavanode"
image: "0glabs/0g-chain-node"
ports:
- "26659-26660:26656-26657"
environment:
@ -31,7 +31,7 @@ services:
kvdnode2:
container_name: kvdnode2
image: "kava/kavanode"
image: "0glabs/0g-chain-node"
environment:
- ID=2
- LOG=${LOG:-kvd.log}
@ -45,7 +45,7 @@ services:
kvdnode3:
container_name: kvdnode3
image: "kava/kavanode"
image: "0glabs/0g-chain-node"
environment:
- ID=3
- LOG=${LOG:-kvd.log}

File diff suppressed because it is too large Load Diff

121
go.mod
View File

@ -1,19 +1,22 @@
module github.com/kava-labs/kava
module github.com/0glabs/0g-chain
go 1.21
require (
cosmossdk.io/errors v1.0.0
cosmossdk.io/math v1.2.0
cosmossdk.io/simapp v0.0.0-20231127212628-044ff4d8c015
cosmossdk.io/errors v1.0.1
cosmossdk.io/math v1.3.0
github.com/cenkalti/backoff/v4 v4.1.3
github.com/cometbft/cometbft v0.37.4
github.com/cometbft/cometbft-db v0.9.1
github.com/cosmos/cosmos-proto v1.0.0-beta.3
github.com/cosmos/cosmos-sdk v0.47.7
github.com/coniks-sys/coniks-go v0.0.0-20180722014011-11acf4819b71
github.com/consensys/gnark-crypto v0.12.1
github.com/cosmos/cosmos-proto v1.0.0-beta.4
github.com/cosmos/cosmos-sdk v0.47.10
github.com/cosmos/go-bip39 v1.0.0
github.com/cosmos/gogoproto v1.4.10
github.com/cosmos/ibc-go/v7 v7.3.1
github.com/cosmos/iavl v0.20.1
github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7 v7.1.3
github.com/cosmos/ibc-go/v7 v7.4.0
github.com/ethereum/go-ethereum v1.10.26
github.com/evmos/ethermint v0.21.0
github.com/go-kit/kit v0.12.0
@ -21,32 +24,37 @@ require (
github.com/golang/protobuf v1.5.3
github.com/gorilla/mux v1.8.0
github.com/grpc-ecosystem/grpc-gateway v1.16.0
github.com/influxdata/influxdb v1.8.3
github.com/kava-labs/kava v0.26.1
github.com/linxGnu/grocksdb v1.8.6
github.com/pelletier/go-toml/v2 v2.0.8
github.com/pelletier/go-toml/v2 v2.1.0
github.com/prometheus/client_golang v1.14.0
github.com/spf13/cast v1.5.1
github.com/shopspring/decimal v1.4.0
github.com/spf13/cast v1.6.0
github.com/spf13/cobra v1.7.0
github.com/spf13/viper v1.16.0
github.com/stretchr/testify v1.8.4
github.com/subosito/gotenv v1.4.2
golang.org/x/crypto v0.15.0
golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb
google.golang.org/genproto/googleapis/api v0.0.0-20231002182017-d307bd883b97
google.golang.org/grpc v1.59.0
google.golang.org/protobuf v1.31.0
sigs.k8s.io/yaml v1.3.0
github.com/subosito/gotenv v1.6.0
github.com/tendermint/tendermint v0.35.9
golang.org/x/crypto v0.24.0
golang.org/x/exp v0.0.0-20230905200255-921286631fa9
google.golang.org/genproto/googleapis/api v0.0.0-20231212172506-995d672761c0
google.golang.org/grpc v1.60.1
google.golang.org/protobuf v1.32.0
sigs.k8s.io/yaml v1.4.0
)
require (
cloud.google.com/go v0.110.8 // indirect
cloud.google.com/go/compute v1.23.0 // indirect
cloud.google.com/go v0.111.0 // indirect
cloud.google.com/go/compute v1.23.3 // indirect
cloud.google.com/go/compute/metadata v0.2.3 // indirect
cloud.google.com/go/iam v1.1.2 // indirect
cloud.google.com/go/storage v1.30.1 // indirect
cloud.google.com/go/iam v1.1.5 // indirect
cloud.google.com/go/storage v1.35.1 // indirect
cosmossdk.io/api v0.3.1 // indirect
cosmossdk.io/core v0.6.1 // indirect
cosmossdk.io/depinject v1.0.0-alpha.4 // indirect
cosmossdk.io/log v1.2.1 // indirect
cosmossdk.io/log v1.3.1 // indirect
cosmossdk.io/simapp v0.0.0-20231127212628-044ff4d8c015 // indirect
cosmossdk.io/tools/rosetta v0.2.1 // indirect
filippo.io/edwards25519 v1.0.0 // indirect
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
@ -54,12 +62,12 @@ require (
github.com/ChainSafe/go-schnorrkel v1.0.0 // indirect
github.com/StackExchange/wmi v1.2.1 // indirect
github.com/VictoriaMetrics/fastcache v1.6.0 // indirect
github.com/allegro/bigcache v1.2.1 // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/aws/aws-sdk-go v1.44.203 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect
github.com/bits-and-blooms/bitset v1.7.0 // indirect
github.com/btcsuite/btcd v0.23.4 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
github.com/btcsuite/btcd/btcutil v1.1.3 // indirect
@ -73,15 +81,15 @@ require (
github.com/cockroachdb/redact v1.1.5 // indirect
github.com/coinbase/rosetta-sdk-go v0.7.9 // indirect
github.com/confio/ics23/go v0.9.0 // indirect
github.com/consensys/bavard v0.1.13 // indirect
github.com/cosmos/btcutil v1.0.5 // indirect
github.com/cosmos/gogogateway v1.2.0 // indirect
github.com/cosmos/iavl v0.20.1 // indirect
github.com/cosmos/ics23/go v0.10.0 // indirect
github.com/cosmos/ledger-cosmos-go v0.13.1 // indirect
github.com/cosmos/rosetta-sdk-go v0.10.0 // indirect
github.com/creachadair/taskgroup v0.4.2 // indirect
github.com/danieljoos/wincred v1.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/deckarep/golang-set v1.8.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect
@ -91,14 +99,16 @@ require (
github.com/dlclark/regexp2 v1.4.1-0.20201116162257-a2a8dda75c91 // indirect
github.com/dop251/goja v0.0.0-20220405120441-9037c2b61cbf // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/dvsekhvalnov/jose2go v1.5.0 // indirect
github.com/dvsekhvalnov/jose2go v1.6.0 // indirect
github.com/edsrzf/mmap-go v1.0.0 // indirect
github.com/felixge/httpsnoop v1.0.2 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect
github.com/getsentry/sentry-go v0.23.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
github.com/go-stack/stack v1.8.1 // indirect
@ -109,11 +119,11 @@ require (
github.com/golang/mock v1.6.0 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/btree v1.1.2 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/orderedcode v0.0.1 // indirect
github.com/google/s2a-go v0.1.4 // indirect
github.com/google/uuid v1.3.1 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.2.4 // indirect
github.com/google/s2a-go v0.1.7 // indirect
github.com/google/uuid v1.4.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
github.com/gorilla/handlers v1.5.1 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
@ -133,12 +143,13 @@ require (
github.com/holiman/uint256 v1.2.1 // indirect
github.com/huandu/skiplist v1.2.0 // indirect
github.com/huin/goupnp v1.0.3 // indirect
github.com/iancoleman/orderedmap v0.2.0 // indirect
github.com/improbable-eng/grpc-web v0.15.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/klauspost/compress v1.16.7 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/lib/pq v1.10.7 // indirect
@ -146,7 +157,7 @@ require (
github.com/magiconair/properties v1.8.7 // indirect
github.com/manifoldco/promptui v0.9.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/mimoo/StrobeGo v0.0.0-20210601165009-122bf33a46e0 // indirect
@ -154,11 +165,12 @@ require (
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mmcloughlin/addchain v0.4.0 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.42.0 // indirect
github.com/prometheus/procfs v0.9.0 // indirect
@ -168,14 +180,13 @@ require (
github.com/rjeczalik/notify v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/rs/cors v1.8.3 // indirect
github.com/rs/zerolog v1.30.0 // indirect
github.com/rs/zerolog v1.32.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/status-im/keycard-go v0.2.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tidwall/btree v1.6.0 // indirect
@ -187,23 +198,27 @@ require (
github.com/zondax/ledger-go v0.14.3 // indirect
go.etcd.io/bbolt v1.3.8 // indirect
go.opencensus.io v0.24.0 // indirect
golang.org/x/net v0.18.0 // indirect
golang.org/x/oauth2 v0.11.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sys v0.14.0 // indirect
golang.org/x/term v0.14.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
google.golang.org/api v0.128.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20231012201019-e917dd12ba7a // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b // indirect
go.opentelemetry.io/otel v1.19.0 // indirect
go.opentelemetry.io/otel/metric v1.19.0 // indirect
go.opentelemetry.io/otel/trace v1.19.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/oauth2 v0.15.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/term v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/api v0.153.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/genproto v0.0.0-20240102182953-50ed04b92917 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240108191215-35c7eff3a6b1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.6 // indirect
pgregory.net/rapid v0.5.5 // indirect
pgregory.net/rapid v1.1.0 // indirect
rsc.io/tmplfunc v0.0.3 // indirect
)
replace (
@ -213,13 +228,17 @@ replace (
github.com/cometbft/cometbft => github.com/kava-labs/cometbft v0.37.4-kava.1
github.com/cometbft/cometbft-db => github.com/kava-labs/cometbft-db v0.9.1-kava.1
// Use cosmos-sdk fork with backported fix for unsafe-reset-all, staking transfer events, and custom tally handler support
github.com/cosmos/cosmos-sdk => github.com/kava-labs/cosmos-sdk v0.47.7-kava.1
// github.com/cosmos/cosmos-sdk => github.com/0glabs/cosmos-sdk v0.46.11-kava.3
github.com/cosmos/cosmos-sdk => /home/wenhui/v047/cosmos-sdk
// See https://github.com/cosmos/cosmos-sdk/pull/13093
github.com/dgrijalva/jwt-go => github.com/golang-jwt/jwt/v4 v4.4.2
// Use go-ethereum fork with precompiles
github.com/ethereum/go-ethereum => github.com/evmos/go-ethereum v1.10.26-evmos-rc2
// Use ethermint fork that respects min-gas-price with NoBaseFee true and london enabled, and includes eip712 support
github.com/evmos/ethermint => github.com/kava-labs/ethermint v0.21.0-kava-v26.1
github.com/evmos/ethermint => github.com/0g-wh/ethermint v0.21.0-0glabs-v26.3.1
// See https://github.com/cosmos/cosmos-sdk/pull/10401, https://github.com/cosmos/cosmos-sdk/commit/0592ba6158cd0bf49d894be1cef4faeec59e8320
github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.9.0
// Downgraded to avoid bugs in following commits which causes "version does not exist" errors
github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7
golang.org/x/exp => golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb
)

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