From 4e4322001f7113d0acba9d5f7684af664243bec2 Mon Sep 17 00:00:00 2001 From: Woosang Son Date: Thu, 29 Apr 2021 18:09:42 +0900 Subject: [PATCH] chore: remove link-modules (#156) --- go.mod | 6 +- go.sum | 76 +- x/account/alias.go | 19 - x/account/client/alias.go | 19 - x/account/client/cli/query.go | 238 ---- x/account/client/cli/tx.go | 81 -- x/account/client/rest/query.go | 141 -- x/account/client/rest/rest.go | 17 - x/account/client/rest/simulate.go | 90 -- x/account/client/rest/simulate_test.go | 142 -- x/account/client/types/block_with_txs.go | 53 - x/account/client/types/result.go | 145 --- x/account/client/utils/alias.go | 11 - x/account/client/utils/block_with_txs.go | 103 -- x/account/client/utils/block_with_txs_test.go | 262 ---- x/account/client/utils/mock/client_mock.go | 1146 ----------------- x/account/client/utils/query.go | 359 ------ x/account/client/utils/query_test.go | 407 ------ x/account/handler.go | 61 - x/account/handler_test.go | 105 -- x/account/internal/types/codec.go | 19 - x/account/internal/types/errors.go | 9 - x/account/internal/types/events.go | 16 - x/account/internal/types/key.go | 7 - x/account/internal/types/msgs.go | 81 -- x/account/module.go | 100 -- x/account/spec/01_concept.md | 2 - x/account/spec/02_keepers.md | 2 - x/account/spec/03_messages.md | 36 - x/account/spec/04_events.md | 20 - x/account/spec/README.md | 14 - x/coin/alias.go | 31 - x/coin/client/cli/tx.go | 64 - x/coin/client/rest/query.go | 85 -- x/coin/client/rest/tx.go | 60 - x/coin/handler.go | 69 - x/coin/handler_test.go | 138 -- x/coin/internal/keeper/blacklist.go | 19 - x/coin/internal/keeper/hooks.go | 11 - x/coin/internal/keeper/keeper.go | 104 -- x/coin/internal/keeper/keeper_test.go | 78 -- x/coin/internal/keeper/querier.go | 81 -- x/coin/internal/keeper/querier_test.go | 111 -- x/coin/internal/keeper/test_common.go | 67 - x/coin/internal/types/codec.go | 18 - x/coin/internal/types/errors.go | 17 - x/coin/internal/types/events.go | 11 - x/coin/internal/types/expected_keepers.go | 26 - x/coin/internal/types/key.go | 21 - x/coin/internal/types/msgs.go | 202 --- x/coin/internal/types/msgs_test.go | 97 -- x/coin/internal/types/querier.go | 35 - x/coin/internal/types/symbol.go | 24 - x/coin/module.go | 106 -- x/coin/spec/01_state.md | 3 - x/coin/spec/02_keepers.md | 3 - x/coin/spec/03_messages.md | 57 - x/coin/spec/04_events.md | 24 - x/coin/spec/README.md | 18 - x/collection/alias.go | 107 -- x/collection/client/cli/query.go | 465 ------- x/collection/client/cli/tx.go | 706 ---------- .../client/internal/types/retriever.go | 316 ----- x/collection/client/rest/query.go | 524 -------- x/collection/genesis.go | 42 - x/collection/internal/handler/burn.go | 71 - x/collection/internal/handler/burn_test.go | 209 --- x/collection/internal/handler/composable.go | 75 -- .../internal/handler/composable_test.go | 251 ---- x/collection/internal/handler/create.go | 29 - x/collection/internal/handler/create_test.go | 38 - x/collection/internal/handler/handler.go | 86 -- x/collection/internal/handler/handler_test.go | 84 -- x/collection/internal/handler/issue.go | 73 -- x/collection/internal/handler/issue_test.go | 382 ------ x/collection/internal/handler/mint.go | 52 - x/collection/internal/handler/mint_test.go | 89 -- x/collection/internal/handler/modify.go | 22 - x/collection/internal/handler/modify_test.go | 172 --- x/collection/internal/handler/perm.go | 39 - x/collection/internal/handler/perm_test.go | 160 --- x/collection/internal/handler/proxy.go | 41 - x/collection/internal/handler/proxy_test.go | 148 --- x/collection/internal/handler/transfer.go | 75 -- .../internal/handler/transfer_test.go | 192 --- x/collection/internal/keeper/account.go | 91 -- x/collection/internal/keeper/account_test.go | 114 -- x/collection/internal/keeper/bank.go | 99 -- x/collection/internal/keeper/bank_test.go | 25 - x/collection/internal/keeper/burn.go | 235 ---- x/collection/internal/keeper/burn_test.go | 277 ---- x/collection/internal/keeper/collection.go | 133 -- .../internal/keeper/collection_test.go | 108 -- x/collection/internal/keeper/composable.go | 417 ------ .../internal/keeper/composable_test.go | 491 ------- x/collection/internal/keeper/issue.go | 71 - x/collection/internal/keeper/issue_test.go | 34 - x/collection/internal/keeper/keeper.go | 78 -- x/collection/internal/keeper/keeper_test.go | 169 --- x/collection/internal/keeper/mint.go | 115 -- x/collection/internal/keeper/mint_test.go | 45 - x/collection/internal/keeper/modify.go | 152 --- x/collection/internal/keeper/modify_test.go | 218 ---- x/collection/internal/keeper/msg_encoder.go | 291 ----- .../internal/keeper/msg_encoder_test.go | 311 ----- x/collection/internal/keeper/nftowner.go | 61 - x/collection/internal/keeper/nftowner_test.go | 120 -- x/collection/internal/keeper/params.go | 16 - x/collection/internal/keeper/perm.go | 91 -- x/collection/internal/keeper/perm_test.go | 96 -- x/collection/internal/keeper/proxy.go | 111 -- x/collection/internal/keeper/proxy_test.go | 53 - x/collection/internal/keeper/supply.go | 98 -- x/collection/internal/keeper/supply_test.go | 222 ---- x/collection/internal/keeper/test_common.go | 59 - x/collection/internal/keeper/token.go | 318 ----- x/collection/internal/keeper/token_test.go | 282 ---- x/collection/internal/keeper/token_type.go | 119 -- .../internal/keeper/token_type_test.go | 117 -- x/collection/internal/keeper/transfer.go | 179 --- x/collection/internal/keeper/transfer_test.go | 132 -- x/collection/internal/legacy/upgrade.go | 13 - x/collection/internal/querier/querier.go | 382 ------ .../internal/querier/querier_encoder.go | 247 ---- .../internal/querier/querier_encoder_test.go | 442 ------- x/collection/internal/querier/querier_test.go | 554 -------- x/collection/internal/types/account.go | 56 - x/collection/internal/types/codec.go | 59 - x/collection/internal/types/coin.go | 698 ---------- x/collection/internal/types/coin_test.go | 712 ---------- x/collection/internal/types/collection.go | 69 - .../internal/types/collection_test.go | 17 - x/collection/internal/types/common_test.go | 26 - x/collection/internal/types/encoder.go | 134 -- x/collection/internal/types/errors.go | 68 - x/collection/internal/types/events.go | 54 - .../internal/types/expected_keeper.go | 12 - x/collection/internal/types/key.go | 96 -- x/collection/internal/types/key_test.go | 19 - x/collection/internal/types/modify.go | 29 - .../internal/types/msgs_collection.go | 51 - .../internal/types/msgs_compossible.go | 255 ---- x/collection/internal/types/msgs_issue.go | 117 -- x/collection/internal/types/msgs_mint.go | 327 ----- x/collection/internal/types/msgs_modify.go | 67 - .../internal/types/msgs_modify_test.go | 200 --- x/collection/internal/types/msgs_perm.go | 95 -- x/collection/internal/types/msgs_proxy.go | 91 -- x/collection/internal/types/msgs_test.go | 615 --------- x/collection/internal/types/msgs_transfer.go | 287 ----- x/collection/internal/types/params.go | 87 -- x/collection/internal/types/params_test.go | 25 - x/collection/internal/types/perm.go | 145 --- x/collection/internal/types/perm_test.go | 24 - x/collection/internal/types/querier.go | 86 -- x/collection/internal/types/supply.go | 108 -- x/collection/internal/types/supply_test.go | 78 -- x/collection/internal/types/symbol.go | 40 - x/collection/internal/types/token.go | 128 -- x/collection/internal/types/token_test.go | 77 -- x/collection/internal/types/token_type.go | 69 - .../internal/types/token_type_test.go | 39 - x/collection/internal/types/validators.go | 133 -- .../internal/types/validators_test.go | 158 --- x/collection/module.go | 155 --- x/collection/spec/01_concept.md | 2 - x/collection/spec/02_keepers.md | 2 - x/collection/spec/03_messages.md | 454 ------- x/collection/spec/04_events.md | 275 ---- x/collection/spec/README.md | 14 - x/contract/alias.go | 24 - x/contract/internal/keeper/keeper.go | 106 -- x/contract/internal/keeper/keeper_test.go | 51 - x/contract/internal/types/errors.go | 10 - x/contract/internal/types/types.go | 31 - x/contract/validator.go | 14 - x/genesis/alias.go | 21 - x/genesis/genesis.go | 28 - x/genesis/internal/keeper/keeper.go | 33 - x/genesis/internal/types/codec.go | 10 - x/genesis/internal/types/types.go | 11 - x/genesis/module.go | 111 -- x/token/alias.go | 63 - x/token/client/cli/query.go | 197 --- x/token/client/cli/tx.go | 364 ------ x/token/client/internal/types/retriever.go | 124 -- x/token/client/rest/query.go | 206 --- x/token/genesis.go | 28 - x/token/internal/handler/handler.go | 61 - x/token/internal/handler/handler_test.go | 67 - x/token/internal/handler/issue.go | 29 - x/token/internal/handler/issue_test.go | 63 - x/token/internal/handler/mintburn.go | 56 - x/token/internal/handler/mintburn_test.go | 139 -- x/token/internal/handler/modify.go | 23 - x/token/internal/handler/modify_test.go | 68 - x/token/internal/handler/perm.go | 40 - x/token/internal/handler/perm_test.go | 79 -- x/token/internal/handler/proxy.go | 24 - x/token/internal/handler/proxy_test.go | 51 - x/token/internal/handler/transfer.go | 41 - x/token/internal/handler/transfer_test.go | 78 -- x/token/internal/keeper/account.go | 79 -- x/token/internal/keeper/account_test.go | 94 -- x/token/internal/keeper/bank.go | 107 -- x/token/internal/keeper/bank_test.go | 127 -- x/token/internal/keeper/blacklist.go | 19 - x/token/internal/keeper/blacklist_test.go | 21 - x/token/internal/keeper/burn.go | 70 - x/token/internal/keeper/burn_test.go | 101 -- x/token/internal/keeper/hooks.go | 11 - x/token/internal/keeper/issue.go | 70 - x/token/internal/keeper/issue_test.go | 82 -- x/token/internal/keeper/keeper.go | 57 - x/token/internal/keeper/keeper_test.go | 88 -- x/token/internal/keeper/mint.go | 45 - x/token/internal/keeper/mint_test.go | 89 -- x/token/internal/keeper/modify.go | 49 - x/token/internal/keeper/modify_test.go | 69 - x/token/internal/keeper/msg_encoder.go | 134 -- x/token/internal/keeper/msg_encoder_test.go | 154 --- x/token/internal/keeper/perm.go | 91 -- x/token/internal/keeper/perm_test.go | 94 -- x/token/internal/keeper/proxy.go | 89 -- x/token/internal/keeper/proxy_test.go | 50 - x/token/internal/keeper/supply.go | 112 -- x/token/internal/keeper/supply_test.go | 219 ---- x/token/internal/keeper/test_common.go | 49 - x/token/internal/keeper/token.go | 79 -- x/token/internal/keeper/token_test.go | 86 -- x/token/internal/keeper/transfer.go | 54 - x/token/internal/keeper/transfer_test.go | 56 - x/token/internal/legacy/upgrade.go | 13 - x/token/internal/querier/querier.go | 150 --- x/token/internal/querier/querier_encoder.go | 154 --- .../internal/querier/querier_encoder_test.go | 143 -- x/token/internal/querier/querier_test.go | 193 --- x/token/internal/types/account.go | 56 - x/token/internal/types/account_test.go | 23 - x/token/internal/types/codec.go | 35 - x/token/internal/types/common_test.go | 21 - x/token/internal/types/encoder.go | 93 -- x/token/internal/types/errors.go | 45 - x/token/internal/types/events.go | 30 - x/token/internal/types/expected_keeper.go | 12 - x/token/internal/types/key.go | 49 - x/token/internal/types/key_test.go | 31 - x/token/internal/types/modify.go | 29 - x/token/internal/types/msgs_modify.go | 48 - x/token/internal/types/msgs_modify_test.go | 132 -- x/token/internal/types/msgs_perm.go | 95 -- x/token/internal/types/msgs_proxy.go | 49 - x/token/internal/types/msgs_test.go | 252 ---- x/token/internal/types/msgs_token.go | 213 --- x/token/internal/types/msgs_transfer.go | 122 -- x/token/internal/types/perm.go | 137 -- x/token/internal/types/perm_test.go | 50 - x/token/internal/types/querier.go | 60 - x/token/internal/types/supply.go | 94 -- x/token/internal/types/supply_test.go | 51 - x/token/internal/types/symbol.go | 24 - x/token/internal/types/token.go | 80 -- x/token/internal/types/token_test.go | 56 - x/token/internal/types/validators.go | 98 -- x/token/internal/types/validators_test.go | 98 -- x/token/module.go | 129 -- x/token/spec/01_concept.md | 2 - x/token/spec/02_keepers.md | 2 - x/token/spec/03_messages.md | 180 --- x/token/spec/04_events.md | 121 -- x/token/spec/README.md | 14 - 271 files changed, 21 insertions(+), 31113 deletions(-) delete mode 100644 x/account/alias.go delete mode 100644 x/account/client/alias.go delete mode 100644 x/account/client/cli/query.go delete mode 100644 x/account/client/cli/tx.go delete mode 100644 x/account/client/rest/query.go delete mode 100644 x/account/client/rest/rest.go delete mode 100644 x/account/client/rest/simulate.go delete mode 100644 x/account/client/rest/simulate_test.go delete mode 100644 x/account/client/types/block_with_txs.go delete mode 100644 x/account/client/types/result.go delete mode 100644 x/account/client/utils/alias.go delete mode 100644 x/account/client/utils/block_with_txs.go delete mode 100644 x/account/client/utils/block_with_txs_test.go delete mode 100644 x/account/client/utils/mock/client_mock.go delete mode 100644 x/account/client/utils/query.go delete mode 100644 x/account/client/utils/query_test.go delete mode 100644 x/account/handler.go delete mode 100644 x/account/handler_test.go delete mode 100644 x/account/internal/types/codec.go delete mode 100644 x/account/internal/types/errors.go delete mode 100644 x/account/internal/types/events.go delete mode 100644 x/account/internal/types/key.go delete mode 100644 x/account/internal/types/msgs.go delete mode 100644 x/account/module.go delete mode 100644 x/account/spec/01_concept.md delete mode 100644 x/account/spec/02_keepers.md delete mode 100644 x/account/spec/03_messages.md delete mode 100644 x/account/spec/04_events.md delete mode 100644 x/account/spec/README.md delete mode 100644 x/coin/alias.go delete mode 100644 x/coin/client/cli/tx.go delete mode 100644 x/coin/client/rest/query.go delete mode 100644 x/coin/client/rest/tx.go delete mode 100644 x/coin/handler.go delete mode 100644 x/coin/handler_test.go delete mode 100644 x/coin/internal/keeper/blacklist.go delete mode 100644 x/coin/internal/keeper/hooks.go delete mode 100644 x/coin/internal/keeper/keeper.go delete mode 100644 x/coin/internal/keeper/keeper_test.go delete mode 100644 x/coin/internal/keeper/querier.go delete mode 100644 x/coin/internal/keeper/querier_test.go delete mode 100644 x/coin/internal/keeper/test_common.go delete mode 100644 x/coin/internal/types/codec.go delete mode 100644 x/coin/internal/types/errors.go delete mode 100644 x/coin/internal/types/events.go delete mode 100644 x/coin/internal/types/expected_keepers.go delete mode 100644 x/coin/internal/types/key.go delete mode 100644 x/coin/internal/types/msgs.go delete mode 100644 x/coin/internal/types/msgs_test.go delete mode 100644 x/coin/internal/types/querier.go delete mode 100644 x/coin/internal/types/symbol.go delete mode 100644 x/coin/module.go delete mode 100644 x/coin/spec/01_state.md delete mode 100644 x/coin/spec/02_keepers.md delete mode 100644 x/coin/spec/03_messages.md delete mode 100644 x/coin/spec/04_events.md delete mode 100644 x/coin/spec/README.md delete mode 100644 x/collection/alias.go delete mode 100644 x/collection/client/cli/query.go delete mode 100644 x/collection/client/cli/tx.go delete mode 100644 x/collection/client/internal/types/retriever.go delete mode 100644 x/collection/client/rest/query.go delete mode 100644 x/collection/genesis.go delete mode 100644 x/collection/internal/handler/burn.go delete mode 100644 x/collection/internal/handler/burn_test.go delete mode 100644 x/collection/internal/handler/composable.go delete mode 100644 x/collection/internal/handler/composable_test.go delete mode 100644 x/collection/internal/handler/create.go delete mode 100644 x/collection/internal/handler/create_test.go delete mode 100644 x/collection/internal/handler/handler.go delete mode 100644 x/collection/internal/handler/handler_test.go delete mode 100644 x/collection/internal/handler/issue.go delete mode 100644 x/collection/internal/handler/issue_test.go delete mode 100644 x/collection/internal/handler/mint.go delete mode 100644 x/collection/internal/handler/mint_test.go delete mode 100644 x/collection/internal/handler/modify.go delete mode 100644 x/collection/internal/handler/modify_test.go delete mode 100644 x/collection/internal/handler/perm.go delete mode 100644 x/collection/internal/handler/perm_test.go delete mode 100644 x/collection/internal/handler/proxy.go delete mode 100644 x/collection/internal/handler/proxy_test.go delete mode 100644 x/collection/internal/handler/transfer.go delete mode 100644 x/collection/internal/handler/transfer_test.go delete mode 100644 x/collection/internal/keeper/account.go delete mode 100644 x/collection/internal/keeper/account_test.go delete mode 100644 x/collection/internal/keeper/bank.go delete mode 100644 x/collection/internal/keeper/bank_test.go delete mode 100644 x/collection/internal/keeper/burn.go delete mode 100644 x/collection/internal/keeper/burn_test.go delete mode 100644 x/collection/internal/keeper/collection.go delete mode 100644 x/collection/internal/keeper/collection_test.go delete mode 100644 x/collection/internal/keeper/composable.go delete mode 100644 x/collection/internal/keeper/composable_test.go delete mode 100644 x/collection/internal/keeper/issue.go delete mode 100644 x/collection/internal/keeper/issue_test.go delete mode 100644 x/collection/internal/keeper/keeper.go delete mode 100644 x/collection/internal/keeper/keeper_test.go delete mode 100644 x/collection/internal/keeper/mint.go delete mode 100644 x/collection/internal/keeper/mint_test.go delete mode 100644 x/collection/internal/keeper/modify.go delete mode 100644 x/collection/internal/keeper/modify_test.go delete mode 100644 x/collection/internal/keeper/msg_encoder.go delete mode 100644 x/collection/internal/keeper/msg_encoder_test.go delete mode 100644 x/collection/internal/keeper/nftowner.go delete mode 100644 x/collection/internal/keeper/nftowner_test.go delete mode 100644 x/collection/internal/keeper/params.go delete mode 100644 x/collection/internal/keeper/perm.go delete mode 100644 x/collection/internal/keeper/perm_test.go delete mode 100644 x/collection/internal/keeper/proxy.go delete mode 100644 x/collection/internal/keeper/proxy_test.go delete mode 100644 x/collection/internal/keeper/supply.go delete mode 100644 x/collection/internal/keeper/supply_test.go delete mode 100644 x/collection/internal/keeper/test_common.go delete mode 100644 x/collection/internal/keeper/token.go delete mode 100644 x/collection/internal/keeper/token_test.go delete mode 100644 x/collection/internal/keeper/token_type.go delete mode 100644 x/collection/internal/keeper/token_type_test.go delete mode 100644 x/collection/internal/keeper/transfer.go delete mode 100644 x/collection/internal/keeper/transfer_test.go delete mode 100644 x/collection/internal/legacy/upgrade.go delete mode 100644 x/collection/internal/querier/querier.go delete mode 100644 x/collection/internal/querier/querier_encoder.go delete mode 100644 x/collection/internal/querier/querier_encoder_test.go delete mode 100644 x/collection/internal/querier/querier_test.go delete mode 100644 x/collection/internal/types/account.go delete mode 100644 x/collection/internal/types/codec.go delete mode 100644 x/collection/internal/types/coin.go delete mode 100644 x/collection/internal/types/coin_test.go delete mode 100644 x/collection/internal/types/collection.go delete mode 100644 x/collection/internal/types/collection_test.go delete mode 100644 x/collection/internal/types/common_test.go delete mode 100644 x/collection/internal/types/encoder.go delete mode 100644 x/collection/internal/types/errors.go delete mode 100644 x/collection/internal/types/events.go delete mode 100644 x/collection/internal/types/expected_keeper.go delete mode 100644 x/collection/internal/types/key.go delete mode 100644 x/collection/internal/types/key_test.go delete mode 100644 x/collection/internal/types/modify.go delete mode 100644 x/collection/internal/types/msgs_collection.go delete mode 100644 x/collection/internal/types/msgs_compossible.go delete mode 100644 x/collection/internal/types/msgs_issue.go delete mode 100644 x/collection/internal/types/msgs_mint.go delete mode 100644 x/collection/internal/types/msgs_modify.go delete mode 100644 x/collection/internal/types/msgs_modify_test.go delete mode 100644 x/collection/internal/types/msgs_perm.go delete mode 100644 x/collection/internal/types/msgs_proxy.go delete mode 100644 x/collection/internal/types/msgs_test.go delete mode 100644 x/collection/internal/types/msgs_transfer.go delete mode 100644 x/collection/internal/types/params.go delete mode 100644 x/collection/internal/types/params_test.go delete mode 100644 x/collection/internal/types/perm.go delete mode 100644 x/collection/internal/types/perm_test.go delete mode 100644 x/collection/internal/types/querier.go delete mode 100644 x/collection/internal/types/supply.go delete mode 100644 x/collection/internal/types/supply_test.go delete mode 100644 x/collection/internal/types/symbol.go delete mode 100644 x/collection/internal/types/token.go delete mode 100644 x/collection/internal/types/token_test.go delete mode 100644 x/collection/internal/types/token_type.go delete mode 100644 x/collection/internal/types/token_type_test.go delete mode 100644 x/collection/internal/types/validators.go delete mode 100644 x/collection/internal/types/validators_test.go delete mode 100644 x/collection/module.go delete mode 100644 x/collection/spec/01_concept.md delete mode 100644 x/collection/spec/02_keepers.md delete mode 100644 x/collection/spec/03_messages.md delete mode 100644 x/collection/spec/04_events.md delete mode 100644 x/collection/spec/README.md delete mode 100644 x/contract/alias.go delete mode 100644 x/contract/internal/keeper/keeper.go delete mode 100644 x/contract/internal/keeper/keeper_test.go delete mode 100644 x/contract/internal/types/errors.go delete mode 100644 x/contract/internal/types/types.go delete mode 100644 x/contract/validator.go delete mode 100644 x/genesis/alias.go delete mode 100644 x/genesis/genesis.go delete mode 100644 x/genesis/internal/keeper/keeper.go delete mode 100644 x/genesis/internal/types/codec.go delete mode 100644 x/genesis/internal/types/types.go delete mode 100644 x/genesis/module.go delete mode 100644 x/token/alias.go delete mode 100644 x/token/client/cli/query.go delete mode 100644 x/token/client/cli/tx.go delete mode 100644 x/token/client/internal/types/retriever.go delete mode 100644 x/token/client/rest/query.go delete mode 100644 x/token/genesis.go delete mode 100644 x/token/internal/handler/handler.go delete mode 100644 x/token/internal/handler/handler_test.go delete mode 100644 x/token/internal/handler/issue.go delete mode 100644 x/token/internal/handler/issue_test.go delete mode 100644 x/token/internal/handler/mintburn.go delete mode 100644 x/token/internal/handler/mintburn_test.go delete mode 100644 x/token/internal/handler/modify.go delete mode 100644 x/token/internal/handler/modify_test.go delete mode 100644 x/token/internal/handler/perm.go delete mode 100644 x/token/internal/handler/perm_test.go delete mode 100644 x/token/internal/handler/proxy.go delete mode 100644 x/token/internal/handler/proxy_test.go delete mode 100644 x/token/internal/handler/transfer.go delete mode 100644 x/token/internal/handler/transfer_test.go delete mode 100644 x/token/internal/keeper/account.go delete mode 100644 x/token/internal/keeper/account_test.go delete mode 100644 x/token/internal/keeper/bank.go delete mode 100644 x/token/internal/keeper/bank_test.go delete mode 100644 x/token/internal/keeper/blacklist.go delete mode 100644 x/token/internal/keeper/blacklist_test.go delete mode 100644 x/token/internal/keeper/burn.go delete mode 100644 x/token/internal/keeper/burn_test.go delete mode 100644 x/token/internal/keeper/hooks.go delete mode 100644 x/token/internal/keeper/issue.go delete mode 100644 x/token/internal/keeper/issue_test.go delete mode 100644 x/token/internal/keeper/keeper.go delete mode 100644 x/token/internal/keeper/keeper_test.go delete mode 100644 x/token/internal/keeper/mint.go delete mode 100644 x/token/internal/keeper/mint_test.go delete mode 100644 x/token/internal/keeper/modify.go delete mode 100644 x/token/internal/keeper/modify_test.go delete mode 100644 x/token/internal/keeper/msg_encoder.go delete mode 100644 x/token/internal/keeper/msg_encoder_test.go delete mode 100644 x/token/internal/keeper/perm.go delete mode 100644 x/token/internal/keeper/perm_test.go delete mode 100644 x/token/internal/keeper/proxy.go delete mode 100644 x/token/internal/keeper/proxy_test.go delete mode 100644 x/token/internal/keeper/supply.go delete mode 100644 x/token/internal/keeper/supply_test.go delete mode 100644 x/token/internal/keeper/test_common.go delete mode 100644 x/token/internal/keeper/token.go delete mode 100644 x/token/internal/keeper/token_test.go delete mode 100644 x/token/internal/keeper/transfer.go delete mode 100644 x/token/internal/keeper/transfer_test.go delete mode 100644 x/token/internal/legacy/upgrade.go delete mode 100644 x/token/internal/querier/querier.go delete mode 100644 x/token/internal/querier/querier_encoder.go delete mode 100644 x/token/internal/querier/querier_encoder_test.go delete mode 100644 x/token/internal/querier/querier_test.go delete mode 100644 x/token/internal/types/account.go delete mode 100644 x/token/internal/types/account_test.go delete mode 100644 x/token/internal/types/codec.go delete mode 100644 x/token/internal/types/common_test.go delete mode 100644 x/token/internal/types/encoder.go delete mode 100644 x/token/internal/types/errors.go delete mode 100644 x/token/internal/types/events.go delete mode 100644 x/token/internal/types/expected_keeper.go delete mode 100644 x/token/internal/types/key.go delete mode 100644 x/token/internal/types/key_test.go delete mode 100644 x/token/internal/types/modify.go delete mode 100644 x/token/internal/types/msgs_modify.go delete mode 100644 x/token/internal/types/msgs_modify_test.go delete mode 100644 x/token/internal/types/msgs_perm.go delete mode 100644 x/token/internal/types/msgs_proxy.go delete mode 100644 x/token/internal/types/msgs_test.go delete mode 100644 x/token/internal/types/msgs_token.go delete mode 100644 x/token/internal/types/msgs_transfer.go delete mode 100644 x/token/internal/types/perm.go delete mode 100644 x/token/internal/types/perm_test.go delete mode 100644 x/token/internal/types/querier.go delete mode 100644 x/token/internal/types/supply.go delete mode 100644 x/token/internal/types/supply_test.go delete mode 100644 x/token/internal/types/symbol.go delete mode 100644 x/token/internal/types/token.go delete mode 100644 x/token/internal/types/token_test.go delete mode 100644 x/token/internal/types/validators.go delete mode 100644 x/token/internal/types/validators_test.go delete mode 100644 x/token/module.go delete mode 100644 x/token/spec/01_concept.md delete mode 100644 x/token/spec/02_keepers.md delete mode 100644 x/token/spec/03_messages.md delete mode 100644 x/token/spec/04_events.md delete mode 100644 x/token/spec/README.md diff --git a/go.mod b/go.mod index 1e6dd185b7..73b480708d 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,6 @@ require ( github.com/btcsuite/btcd v0.21.0-beta github.com/btcsuite/btcutil v1.0.2 github.com/confio/ics23/go v0.6.3 - github.com/cosmos/cosmos-sdk v0.39.2 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/ledger-cosmos-go v0.11.1 github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b @@ -28,7 +27,7 @@ require ( github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/hashicorp/golang-lru v0.5.4 github.com/line/iavl/v2 v2.0.0-init.1.0.20210419041411-7de35b5f1306 - github.com/line/ostracon v0.34.9-0.20210429024836-e5495cecd765 + github.com/line/ostracon v0.34.9-0.20210429084710-ef4fe0a40c7d github.com/line/tm-db/v2 v2.0.0-init.1.0.20210413083915-5bb60e117524 github.com/magiconair/properties v1.8.4 github.com/mattn/go-isatty v0.0.12 @@ -52,7 +51,6 @@ require ( github.com/tendermint/btcd v0.1.1 github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 github.com/tendermint/go-amino v0.16.0 - github.com/tendermint/tendermint v0.34.7 github.com/tendermint/tm-db v0.6.4 golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 // indirect @@ -66,9 +64,7 @@ require ( replace ( github.com/CosmWasm/wasmvm => github.com/line/wasmvm v0.14.0-0.3.0 - github.com/cosmos/cosmos-sdk => github.com/line/lbm-sdk v0.39.2-0.2.0 github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 - github.com/tendermint/tendermint => github.com/line/linemint v1.0.0 github.com/tendermint/tm-db => github.com/line/tm-db v0.5.2 google.golang.org/grpc => google.golang.org/grpc v1.33.2 ) diff --git a/go.sum b/go.sum index ba71272d3f..6ab35a7417 100644 --- a/go.sum +++ b/go.sum @@ -18,7 +18,6 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d h1:nalkkPQcITbvhmL4+C4cKA87NW0tfm3Kl9VXRoPywFg= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= -github.com/DataDog/zstd v1.4.1 h1:3oxKN3wbHibqx897utPC2LTQU4J+IHWWJO+glkAkpFM= github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= @@ -51,8 +50,6 @@ github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6l github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= -github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d h1:1aAija9gr0Hyv4KfQcRcwlmFIrhkDmIj2dz5bkg/s/8= -github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d/go.mod h1:icNx/6QdFblhsEjZehARqbNumymUT/ydwlLojFdv7Sk= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -89,6 +86,7 @@ github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4 github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/confio/ics23/go v0.0.0-20200817220745-f173e6211efb/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= github.com/confio/ics23/go v0.6.3 h1:PuGK2V1NJWZ8sSkNDq91jgT/cahFEW9RGp4Y5jxulf0= github.com/confio/ics23/go v0.6.3/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= @@ -104,6 +102,8 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= +github.com/cosmos/iavl v0.15.0-rc3.0.20201009144442-230e9bdf52cd/go.mod h1:3xOIaNNX19p0QrX0VqWa6voPRoJRGGYtny+DH8NEPvE= +github.com/cosmos/iavl v0.15.0-rc5/go.mod h1:WqoPL9yPTQ85QBMT45OOUzPxG/U/JcJoN7uMjgxke/I= github.com/cosmos/iavl v0.15.3/go.mod h1:OLjQiAQ4fGD2KDZooyJG9yz+p2ao2IAYSbke8mVvSA4= github.com/cosmos/ledger-cosmos-go v0.11.1 h1:9JIYsGnXP613pb2vPjFeMMjBI5lEDsEaF6oYorTy6J4= github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY= @@ -113,7 +113,6 @@ github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwc github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/danieljoos/wincred v1.0.2 h1:zf4bhty2iLuwgjgpraD2E9UbvO+fe54XXGJbOwe23fU= github.com/danieljoos/wincred v1.0.2/go.mod h1:SnuYRW9lp1oJrZX/dXJqr0cPK5gYXqx3EJbmjhLdK9U= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -142,13 +141,11 @@ github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25 h1:2vLKys4RBU4 github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25/go.mod h1:hTr8+TLQmkUkgcuh3mcr5fjrT9c64ZzsBCdCEC6UppY= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51 h1:0JZ+dUmQeA8IIVUMzysrX4/AKuQwWhV2dYQuPZdvdSQ= github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51/go.mod h1:Yg+htXGokKKdzcwhuNDwVvN+uBxDGXJ7G/VN1d8fa64= github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c h1:8ISkoahWXwZR41ois5lSJBSVw4D0OV19Ht/JSTzvSv0= github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c/go.mod h1:Yg+htXGokKKdzcwhuNDwVvN+uBxDGXJ7G/VN1d8fa64= github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 h1:JWuenKqqX8nojtoVVWjGfOF9635RETekkoH6Cc9SX0A= github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqLaRiH3MsBH8va0n7s1pQYcu3uTb8G4tygF4Zg= -github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870 h1:E2s37DuLxFhQDg5gKsWoLBOB0n+ZW8s599zru8FJ2/Y= github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0= github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 h1:7HZCaLC5+BZpmbhCOZJ293Lz68O7PYrF2EzeiFMwCLk= github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0= @@ -185,7 +182,6 @@ github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4er github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= @@ -207,8 +203,6 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw= -github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= @@ -216,12 +210,10 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= -github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -236,12 +228,10 @@ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5m github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= @@ -250,12 +240,14 @@ github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0U github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.1/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= github.com/grpc-ecosystem/go-grpc-middleware v1.2.2 h1:FlFbCRLd5Jr4iYXZufAvgWN6Ao0JrI5chLINnUXDDr0= github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.14.7/go.mod h1:oYZKL012gGh6LMyg/xA7Q2yq6j8bu0wa+9w14EEthWU= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= @@ -269,14 +261,12 @@ github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBt github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= @@ -323,7 +313,6 @@ github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8 github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d h1:Z+RDyXzjKE0i2sTjZ/b1uxiGtPhFy34Ou/Tk0qwN0kM= github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d/go.mod h1:JJNrCn9otv/2QP4D7SMJBgaleKpOf66PnW6F5WGNRIc= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= github.com/kkdai/bstream v1.0.0/go.mod h1:FDnDOHt5Yx4p3FaHcioFT0QjDOtgUpvjeZqAs+NVZZA= @@ -331,35 +320,25 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/libp2p/go-buffer-pool v0.0.2 h1:QNK2iAFa8gjAe1SPz6mHSMuCcjs+X1wlHzeOSqcmlfs= github.com/libp2p/go-buffer-pool v0.0.2/go.mod h1:MvaB6xw5vOrDl8rYZGLFdKAuk/hRoRZd1Vi32+RXyFM= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= github.com/line/gorocksdb v0.0.0-20210406043732-d4bea34b6d55 h1:cXVtMiJkvQ4kn0pxM2svH1ncJbFgQsLHtnFC9qJj2VM= github.com/line/gorocksdb v0.0.0-20210406043732-d4bea34b6d55/go.mod h1:DHRJroSL7NaRkpvocRx3OtRsleXVsYSxBI9SfHFlTQ0= -github.com/line/iavl/v2 v2.0.0-init.1.0.20210406065347-cfd73e5acce0 h1:Pcp/mxkvFmasaiPi9DS2ZXCKOalfDGtBKYjdswmF0nI= github.com/line/iavl/v2 v2.0.0-init.1.0.20210406065347-cfd73e5acce0/go.mod h1:Z2UTxsbKefd7bnEywGNxxmVYYGy9Ecd4nd1IZyR0bQM= github.com/line/iavl/v2 v2.0.0-init.1.0.20210419041411-7de35b5f1306 h1:1wc5BD4kY1v5GZxMq3HfE6dCAPUu6pHqC3PZ1ZEiwVs= github.com/line/iavl/v2 v2.0.0-init.1.0.20210419041411-7de35b5f1306/go.mod h1:cGVW9rgqmnLU+9ShXC/RWwmfmZu56PyzuwvdfJ04ryg= -github.com/line/lbm-sdk v0.39.2-0.2.0 h1:tlQHZcf+AXejSBAhYgO5Tn1NaoCF0XRNf/6c0jeo3HE= -github.com/line/lbm-sdk v0.39.2-0.2.0/go.mod h1:UTxdYWx+OeRezEP8P5BxipddlFpq4q92uYydSeYN7B0= -github.com/line/linemint v1.0.0 h1:sTrDaGP67/5Klxtsuid8wOkQ2y43Y5QkmD8cDMmDeaA= -github.com/line/linemint v1.0.0/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= github.com/line/ostracon v0.34.9-0.20210315041958-2a1f43c788f5/go.mod h1:1THU+kF+6fxLaNYQKcdNyLCO6t9LnqSMaExDMiLozbM= -github.com/line/ostracon v0.34.9-0.20210419031811-5254cabf172e h1:+F5duGTfSZiwD9LqMkdtwFgULjKn8pGRz/86U/SyIO0= github.com/line/ostracon v0.34.9-0.20210419031811-5254cabf172e/go.mod h1:w/itWXCU8Wttz/2Ftp+yJz0UXv9gX6qT1dASn+3kX5M= -github.com/line/ostracon v0.34.9-0.20210429024836-e5495cecd765 h1:Ktkqma9R7CAUi9/ByznJZdWn0TuL7YDnZ0SkiFET6pg= -github.com/line/ostracon v0.34.9-0.20210429024836-e5495cecd765/go.mod h1:w/itWXCU8Wttz/2Ftp+yJz0UXv9gX6qT1dASn+3kX5M= +github.com/line/ostracon v0.34.9-0.20210429084710-ef4fe0a40c7d h1:/6vnjrk3SpCUUiIDBv8UzbYexabZBYXxkwyc3Bp9hPo= +github.com/line/ostracon v0.34.9-0.20210429084710-ef4fe0a40c7d/go.mod h1:ttnbq+yQJMQ9a2MT5SEisOoa/+pOgh2KenTiK/rVdiw= github.com/line/tm-db v0.5.2 h1:P8kMpcrm9Xyfl6QLyafssNIoIeC01k0fhw2zDvKhtl4= github.com/line/tm-db v0.5.2/go.mod h1:VrPTx04QJhQ9d8TFUTc2GpPBvBf/U9vIdBIzkjBk7Lk= -github.com/line/tm-db/v2 v2.0.0-init.1.0.20210406062110-9424ca70955a h1:qSt/WwORC5+nVRnNqx+A0oo5gOCsoVJ0HmHF5Db1YvY= github.com/line/tm-db/v2 v2.0.0-init.1.0.20210406062110-9424ca70955a/go.mod h1:wmkyPabXjtVZ1dvRofmurjaceghywtCSYGqFuFS+TbI= github.com/line/tm-db/v2 v2.0.0-init.1.0.20210413083915-5bb60e117524 h1:eKXXnUm1SblC0AIXAMNDaSyvIbQ50yXqFbh9+Q8Kjvg= github.com/line/tm-db/v2 v2.0.0-init.1.0.20210413083915-5bb60e117524/go.mod h1:wmkyPabXjtVZ1dvRofmurjaceghywtCSYGqFuFS+TbI= @@ -380,7 +359,6 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5 github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 h1:hLDRPB66XQT/8+wG9WsDpiCvZf1yKO7sz7scAjSlBa0= github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= -github.com/minio/highwayhash v1.0.0/go.mod h1:xQboMTeM9nY9v/LlAOxFctujiv5+Aq2hR5dxBpaMbdc= github.com/minio/highwayhash v1.0.1 h1:dZ6IIu8Z14VlC0VpfKofAhCy74wu/Qb5gcn52yWoz/0= github.com/minio/highwayhash v1.0.1/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= @@ -410,7 +388,6 @@ github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxzi github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= @@ -420,17 +397,13 @@ github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4= github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= -github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= @@ -449,7 +422,6 @@ github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0Mw github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys= github.com/pelletier/go-toml v1.8.0 h1:Keo9qb7iRJs2voHvunFtuuYFsbWeOBh8/P9v/kVMFtw= github.com/pelletier/go-toml v1.8.0/go.mod h1:D6yutnOGMveHEPV7VQOuvI/gXY61bv+9bAOTRnLElKs= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= @@ -472,7 +444,6 @@ github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDf github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.5.1/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.8.0 h1:zvJNkoCFAnYFNC24FV8nW4JdRJ3GIFcLbg65lL/JDcw= github.com/prometheus/client_golang v1.8.0/go.mod h1:O9VU6huf47PktckDQfMTX0Y8tY0/7TSWwj+ITvv0TnM= @@ -502,7 +473,6 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O github.com/prometheus/procfs v0.2.0 h1:wH4vA7pcjKuZzjF7lM8awk4fnuJO6idemZXoKnULUx4= github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rakyll/statik v0.1.6/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs= github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Unghqrcc= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= @@ -524,6 +494,7 @@ github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/sasha-s/go-deadlock v0.2.0/go.mod h1:StQn567HiB1fF2yJ44N9au7wOhrPS3iZqiDbRupzT10= github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa h1:0U2s5loxrTy6/VgfVoLuVLFJcURKLH49ie0zSch7gh4= github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= @@ -535,7 +506,6 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykE github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa h1:YJfZp12Z3AFhSBeXOlv4BO55RMwPn2NoQeDsrdWnBtY= github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= @@ -543,7 +513,6 @@ github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasO github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/afero v1.2.1/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/afero v1.3.4 h1:8q6vk3hthlpb2SouZcnBVKboxWQWMDNF38bwholZrJc= github.com/spf13/afero v1.3.4/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= @@ -552,20 +521,17 @@ github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= -github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4= github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= +github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= -github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= -github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= -github.com/spf13/viper v1.6.3/go.mod h1:jUMtyi0/lB5yZH/FjyGAoH7IMNrIhlBf6pXZmbMDvzw= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= @@ -594,12 +560,12 @@ github.com/tendermint/btcd v0.1.1 h1:0VcxPfflS2zZ3RiOAHkBiFUcPvbtRj5O7zHmcJWHV7s github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 h1:hqAk8riJvK4RMWx1aInLzndwxKalgi5rTqgfXxOxbEI= github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= -github.com/tendermint/go-amino v0.14.1/go.mod h1:i/UKE5Uocn+argJJBb12qTZsCDBcAYMbR92AaJVmKso= -github.com/tendermint/go-amino v0.15.1/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= -github.com/tendermint/iavl v0.14.3 h1:tuiUAqJdA3OOyPU/9P3pMYnAcd+OL7BUdzNiE3ytUwQ= -github.com/tendermint/iavl v0.14.3/go.mod h1:vHLYxU/zuxBmxxr1v+5Vnd/JzcIsyK17n9P9RDubPVU= +github.com/tendermint/tendermint v0.34.0-rc4/go.mod h1:yotsojf2C1QBOw4dZrTcxbyxmPUrT4hNuOQWX9XUwB4= +github.com/tendermint/tendermint v0.34.0-rc6/go.mod h1:ugzyZO5foutZImv0Iyx/gOFCX6mjJTgbLHTwi17VDVg= +github.com/tendermint/tendermint v0.34.0/go.mod h1:Aj3PIipBFSNO21r+Lq3TtzQ+uKESxkbA3yo/INM4QwQ= +github.com/tendermint/tendermint v0.34.7/go.mod h1:JVuu3V1ZexOaZG8VJMRl8lnfrGw6hEB2TVnoUwKRbss= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= @@ -644,12 +610,12 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200406173513-056763e48d71/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= @@ -694,6 +660,7 @@ golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= @@ -701,8 +668,6 @@ golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw= @@ -756,21 +721,17 @@ golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201013132646-2da7054afaeb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211 h1:9UQO31fZ+0aKQOFldThf7BKPMJTiBfWycGh/u3UoO88= golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46 h1:V066+OYJ66oTjnhm4Yrn7SXIwSCiDQJxpBxmvqb1N1c= golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221 h1:/ZHdbVpdR/jk3g30/d4yUL0JU9kksj8+F/bnQUVLGDM= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -833,6 +794,8 @@ google.golang.org/genproto v0.0.0-20200324203455-a04cca1dde73/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201111145450-ac7456db90a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201119123407-9b1e624d6bc4/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210114201628-6edceaf6022f h1:izedQ6yVIc5mZsRuXzmSreCOlzI0lCU1HpG8yEdMiKw= google.golang.org/genproto v0.0.0-20210114201628-6edceaf6022f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= @@ -853,8 +816,9 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= diff --git a/x/account/alias.go b/x/account/alias.go deleted file mode 100644 index 8d21869b46..0000000000 --- a/x/account/alias.go +++ /dev/null @@ -1,19 +0,0 @@ -package account - -import ( - "github.com/line/lbm-sdk/v2/x/account/client/cli" - "github.com/line/lbm-sdk/v2/x/account/internal/types" -) - -const ( - ModuleName = types.ModuleName - RouterKey = types.RouterKey -) - -var ( - CreateAccountTxCmd = cli.CreateAccountCmd - EmptyTxCmd = cli.EmptyCmd - NewMsgEmpty = types.NewMsgEmpty - RegisterCodec = types.RegisterCodec - ModuleCdc = types.ModuleCdc -) diff --git a/x/account/client/alias.go b/x/account/client/alias.go deleted file mode 100644 index 3f5100c194..0000000000 --- a/x/account/client/alias.go +++ /dev/null @@ -1,19 +0,0 @@ -package client - -import ( - cosmoscli "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/line/lbm-sdk/v2/x/account/client/cli" - "github.com/line/lbm-sdk/v2/x/account/client/rest" -) - -var ( - GetAccountCmd = cosmoscli.GetAccountCmd - QueryTxsByEventsCmd = cli.QueryTxsByEventsCmd - QueryTxCmd = cli.QueryTxCmd - QueryBlockWithTxResponsesCommand = cli.QueryBlockWithTxResponsesCommand - GetSignCommand = cosmoscli.GetSignCommand - GetMultiSignCommand = cosmoscli.GetMultiSignCommand - GetBroadcastCommand = cosmoscli.GetBroadcastCommand - GetEncodeCommand = cosmoscli.GetEncodeCommand - RegisterTxRoutes = rest.RegisterTxRoutes -) diff --git a/x/account/client/cli/query.go b/x/account/client/cli/query.go deleted file mode 100644 index e00e27532f..0000000000 --- a/x/account/client/cli/query.go +++ /dev/null @@ -1,238 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - "strings" - - "github.com/line/lbm-sdk/v2/x/account/client/utils" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/tendermint/go-amino" - - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/types/rest" -) - -const ( - flagTags = "tags" - flagPage = "page" - flagLimit = "limit" - flagHeightFrom = "height-from" - flagHeightTo = "height-to" -) - -// ***** -// Original code: `github.com/cosmos/cosmos-sdk/x/auth/client/cli/query.go` -// Difference: referring import path of `utils` -// ***** - -// QueryTxsByEventsCmd returns a command to search through transactions by events. -func QueryTxsByEventsCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "txs", - Short: "Query for paginated transactions that match a set of tags", - Long: strings.TrimSpace(` -Search for transactions that match the exact given tags where results are paginated. - -Example: -$ query txs --tags 'message.action:send&message.sender:yoshi' --page 1 --limit 30 -$ query txs --tags 'message.action:send&message.sender:yoshi' --height-from 77 --height-to 79 - -You can also search by height range without tags: -$ query txs --height-from 77 --height-to 79 -`), - RunE: func(cmd *cobra.Command, args []string) error { - tagsStr := viper.GetString(flagTags) - tagsStr = strings.Trim(tagsStr, "'") - - var tags []string - if len(tagsStr) > 0 { - tags = strings.Split(tagsStr, "&") - } - - var tmTags []string - for _, tag := range tags { - if !strings.Contains(tag, ":") { - return fmt.Errorf("%s should be of the format :", tagsStr) - } else if strings.Count(tag, ":") > 1 { - return fmt.Errorf("%s should only contain one : pair", tagsStr) - } - - keyValue := strings.Split(tag, ":") - if keyValue[0] == tmtypes.TxHeightKey { - tag = fmt.Sprintf("%s=%s", keyValue[0], keyValue[1]) - } else { - tag = fmt.Sprintf("%s='%s'", keyValue[0], keyValue[1]) - } - - tmTags = append(tmTags, tag) - } - - heightFrom := viper.GetInt64(flagHeightFrom) - if heightFrom > 0 { - tag := fmt.Sprintf("%s>=%d", tmtypes.TxHeightKey, heightFrom) - tmTags = append(tmTags, tag) - } - - heightTo := viper.GetInt64(flagHeightTo) - if heightTo > 0 { - tag := fmt.Sprintf("%s<=%d", tmtypes.TxHeightKey, heightTo) - tmTags = append(tmTags, tag) - } - - page := viper.GetInt(flagPage) - limit := viper.GetInt(flagLimit) - - cliCtx := context.NewCLIContext().WithCodec(cdc) - txs, err := utils.QueryTxsByEvents(cliCtx, tmTags, page, limit) - if err != nil { - return err - } - - var output []byte - if cliCtx.Indent { - output, err = cdc.MarshalJSONIndent(txs, "", " ") - } else { - output, err = cdc.MarshalJSON(txs) - } - - if err != nil { - return err - } - - fmt.Println(string(output)) - return nil - }, - } - - cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") - err := viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) - if err != nil { - panic(err) - } - cmd.Flags().Bool(flags.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") - err = viper.BindPFlag(flags.FlagTrustNode, cmd.Flags().Lookup(flags.FlagTrustNode)) - if err != nil { - panic(err) - } - cmd.Flags().String(flagTags, "", "tag:value list of tags that must match") - cmd.Flags().Uint32(flagPage, rest.DefaultPage, "Query a specific page of paginated results") - cmd.Flags().Uint32(flagLimit, rest.DefaultLimit, "Query number of transactions results per page returned") - cmd.Flags().Int64(flagHeightFrom, 0, "Filter from a specific block height") - cmd.Flags().Int64(flagHeightTo, 0, "Filter to a specific block height") - - return cmd -} - -// QueryTxCmd implements the default command for a tx query. -func QueryTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "tx [hash]", - Short: "Query for a transaction by hash in a committed block", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - output, err := utils.QueryTx(cliCtx, args[0]) - if err != nil { - return err - } - - if output.Empty() { - return fmt.Errorf("no transaction found with hash %s", args[0]) - } - - return cliCtx.PrintOutput(output) - }, - } - - cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") - err := viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) - if err != nil { - panic(err) - } - cmd.Flags().Bool(flags.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") - err = viper.BindPFlag(flags.FlagTrustNode, cmd.Flags().Lookup(flags.FlagTrustNode)) - if err != nil { - panic(err) - } - return cmd -} - -var ( - DefaultBlockFetchSize int64 = 20 -) - -func QueryBlockWithTxResponsesCommand(cdc *amino.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "block-with-tx-result [from_block_height] [fetchsize]", - Short: "Get verified data for the block and tx and tx_result from given `from_block_height` to `fetchsize`.", - Long: "Up to 20 Items can be returned, and more are ignored. \n" + - "The Default fetchsize is 20 and if there are not enough blocks in the fetchsize requested from from_block_height, \n" + - "It will respond to the latest block height from from_block_height param. \n" + - "You can know latest block height by latest_block_height property of result. \n" + - "The direction of hasMore is from low to high blockHeight. \n" + - "Usage:\n" + - " linkcli query block-with-tx-result 1 10\n" + - " linkcli query block-with-tx-result 1 30 (it will return 20 Items)\n" + - " linkcli query block-with-tx-result 1", - - Args: cobra.RangeArgs(1, 2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - fromBlockHeight, fetchSize := parseCmdParams(args) - - latestBlockHeight, err := utils.LatestBlockHeight(cliCtx) - if err != nil { - return err - } - - if fromBlockHeight >= latestBlockHeight { - return fmt.Errorf("the block height does not exist. Requested: %d, Latest: %d", fromBlockHeight, latestBlockHeight) - } - - blockWithTxReponses, err := utils.BlockWithTxResponses(cliCtx, latestBlockHeight, fromBlockHeight, fetchSize) - if err != nil { - return err - } - return cliCtx.PrintOutput(blockWithTxReponses) - }, - } - - cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") - err := viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) - if err != nil { - panic(err) - } - - cmd.Flags().Bool(flags.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") - err = viper.BindPFlag(flags.FlagTrustNode, cmd.Flags().Lookup(flags.FlagTrustNode)) - if err != nil { - panic(err) - } - - return cmd -} - -func parseCmdParams(args []string) (int64, int64) { - fromBlockHeight, err := strconv.ParseInt(args[0], 10, 64) - if err != nil { - panic(err) - } - if len(args) == 1 { - return fromBlockHeight, DefaultBlockFetchSize - } - fetchSize, err := strconv.ParseInt(args[1], 10, 8) - if err != nil { - panic(err) - } - if fetchSize > DefaultBlockFetchSize { - fetchSize = DefaultBlockFetchSize - } - return fromBlockHeight, fetchSize -} diff --git a/x/account/client/cli/tx.go b/x/account/client/cli/tx.go deleted file mode 100644 index 5281e00902..0000000000 --- a/x/account/client/cli/tx.go +++ /dev/null @@ -1,81 +0,0 @@ -package cli - -import ( - "bufio" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/line/lbm-sdk/v2/x/account/client/utils" - "github.com/line/lbm-sdk/v2/x/account/internal/types" - "github.com/spf13/cobra" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *codec.Codec) *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Account commands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - txCmd.AddCommand( - CreateAccountCmd(cdc), - EmptyCmd(cdc), - ) - return txCmd -} - -func CreateAccountCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "create-account [from_key_or_address] [target_address]", - Short: "Create an account having target_address", - Args: cobra.ExactArgs(2), - RunE: makeCreateAccountCmd(cdc), - } - - return flags.PostCommands(cmd)[0] -} - -func EmptyCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "empty [from_key_or_address]", - Short: "Do nothing", - Args: cobra.ExactArgs(1), - RunE: makeEmptyCmd(cdc), - } - - return flags.PostCommands(cmd)[0] -} - -func makeCreateAccountCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { - return func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - target, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgCreateAccount(cliCtx.GetFromAddress(), target) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - } -} - -func makeEmptyCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { - return func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - msg := types.NewMsgEmpty(cliCtx.GetFromAddress()) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - } -} diff --git a/x/account/client/rest/query.go b/x/account/client/rest/query.go deleted file mode 100644 index 3363fb69c8..0000000000 --- a/x/account/client/rest/query.go +++ /dev/null @@ -1,141 +0,0 @@ -package rest - -import ( - "fmt" - "net/http" - "strconv" - "strings" - - "github.com/gorilla/mux" - "github.com/line/lbm-sdk/v2/x/account/client/utils" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - genutilrest "github.com/cosmos/cosmos-sdk/x/genutil/client/rest" -) - -// ***** -// Original code: `github.com/cosmos/cosmos-sdk/x/auth/client/rest/query.go` -// Difference: referring import path of `utils` -// ***** - -// QueryTxsHandlerFn implements a REST handler that searches for transactions. -// Genesis transactions are returned if the height parameter is set to zero, -// otherwise the transactions are searched for by events. -func QueryTxsRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - err := r.ParseForm() - if err != nil { - rest.WriteErrorResponse( - w, http.StatusBadRequest, - fmt.Sprintf("failed to parse query parameters: %s", err), - ) - return - } - - // if the height query param is set to zero, query for genesis transactions - heightStr := r.FormValue("height") - if heightStr != "" { - if height, err := strconv.ParseInt(heightStr, 10, 64); err == nil && height == 0 { - genutilrest.QueryGenesisTxs(cliCtx, w) - return - } - } - - var ( - events []string - txs []sdk.TxResponse - page, limit int - ) - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - if len(r.Form) == 0 { - rest.PostProcessResponseBare(w, cliCtx, txs) - return - } - - events, page, limit, err = utils.ParseHTTPArgs(r) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - searchResult, err := utils.QueryTxsByEvents(cliCtx, events, page, limit) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponseBare(w, cliCtx, searchResult) - } -} - -// QueryTxRequestHandlerFn implements a REST handler that queries a transaction -// by hash in a committed block. -func QueryTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - hashHexStr := vars["hash"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - output, err := utils.QueryTx(cliCtx, hashHexStr) - if err != nil { - if strings.Contains(err.Error(), hashHexStr) { - rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) - return - } - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - if output.Empty() { - rest.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("no transaction found with hash %s", hashHexStr)) - } - - rest.PostProcessResponseBare(w, cliCtx, output) - } -} - -func QueryBlockWithTxsRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - fromBlockHeight, err := strconv.ParseInt(vars["from_height"], 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("couldn't parse block height. Assumed format is '/blocks_with_tx_results/{from_height}'. because of %s", err.Error())) - return - } - fetchSize, err := strconv.ParseInt(r.URL.Query().Get("fetchsize"), 10, 8) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("couldn't parse fetchsize. because of %s", err.Error())) - return - } - - latestBlockHeight, err := utils.LatestBlockHeight(cliCtx) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't get latestBlockHeight. because of %s", err.Error())) - return - } - - if fromBlockHeight >= latestBlockHeight { - rest.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("the block height does not exist. Requested: %d, Latest: %d", fromBlockHeight, latestBlockHeight)) - return - } - - output, err := utils.BlockWithTxResponses(cliCtx, latestBlockHeight, fromBlockHeight, fetchSize) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't process request. because of %s", err.Error())) - return - } - rest.PostProcessResponseBare(w, cliCtx, output) - } -} diff --git a/x/account/client/rest/rest.go b/x/account/client/rest/rest.go deleted file mode 100644 index a05b18bf1b..0000000000 --- a/x/account/client/rest/rest.go +++ /dev/null @@ -1,17 +0,0 @@ -package rest - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - cosmosrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - "github.com/gorilla/mux" -) - -// RegisterTxRoutes registers all transaction routes on the provided router. -func RegisterTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/txs", QueryTxsRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/txs", cosmosrest.BroadcastTxRequest(cliCtx)).Methods("POST") - r.HandleFunc("/txs/encode", cosmosrest.EncodeTxRequestHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/txs/simulate", SimulateTxRequest(cliCtx)).Methods("POST") - r.HandleFunc("/blocks_with_tx_results/{from_height}", QueryBlockWithTxsRequestHandlerFn(cliCtx)).Methods("GET") -} diff --git a/x/account/client/rest/simulate.go b/x/account/client/rest/simulate.go deleted file mode 100644 index a356121080..0000000000 --- a/x/account/client/rest/simulate.go +++ /dev/null @@ -1,90 +0,0 @@ -package rest - -import ( - "fmt" - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// SimulateReq defines a tx simulating request. -type SimulateReq struct { - Tx types.StdTx `json:"tx" yaml:"tx"` - GasAdjustment string `json:"gas_adjustment"` -} - -type ABCIErrorResponse struct { - Codespace string `json:"codespace"` - Code uint32 `json:"code"` - Error string `json:"error"` -} - -// SimulateTxRequest implements a tx simulating handler that is responsible -// for simulating a valid and signed tx. -func SimulateTxRequest(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req SimulateReq - - body, err := ioutil.ReadAll(r.Body) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - err = cliCtx.Codec.UnmarshalJSON(body, &req) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - txBytes, err := cliCtx.Codec.MarshalBinaryLengthPrefixed(req.Tx) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - gasAdj, ok := rest.ParseFloat64OrReturnBadRequest(w, req.GasAdjustment, flags.DefaultGasAdjustment) - if !ok { - // ParseFloat64OrReturnBadRequest has already written error response. - return - } - - if gasAdj < 0 { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("invalid gas adjustment: %g", gasAdj)) - return - } - - _, adjusted, err := utils.CalculateGas(cliCtx.QueryWithData, cliCtx.Codec, txBytes, gasAdj) - if err != nil { - if ctxtErr, ok := err.(*context.Error); ok { - WriteABCIErrorResponse(w, http.StatusInternalServerError, cliCtx.Codec, ctxtErr) - } else { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - } - return - } - - rest.WriteSimulationResponse(w, cliCtx.Codec, adjusted) - } -} - -// nolint: errcheck -func WriteABCIErrorResponse(w http.ResponseWriter, status int, cdc *codec.Codec, err *context.Error) { - errBody := cdc.MustMarshalJSON( - ABCIErrorResponse{ - Codespace: err.Codespace, - Code: err.Code, - Error: err.Message, - }, - ) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - _, _ = w.Write(errBody) -} diff --git a/x/account/client/rest/simulate_test.go b/x/account/client/rest/simulate_test.go deleted file mode 100644 index c12b9b4b50..0000000000 --- a/x/account/client/rest/simulate_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package rest - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "testing" - - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/line/lbm-sdk/v2/x/account/client/utils/mock" -) - -type mockHTTPWriter struct { - statusCode int - bodyBuf bytes.Buffer -} - -func (m *mockHTTPWriter) Header() http.Header { - return http.Header{} -} - -func (m *mockHTTPWriter) Write(body []byte) (int, error) { - return m.bodyBuf.Write(body) -} - -func (m *mockHTTPWriter) WriteHeader(statusCode int) { - m.statusCode = statusCode -} - -var _ http.ResponseWriter = &mockHTTPWriter{} - -func setupCodec() *codec.Codec { - cdc := codec.New() - auth.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - sdk.RegisterCodec(cdc) - return cdc -} - -func TestSimulateTxRequest(t *testing.T) { - cdc := setupCodec() - - // assumes node response is - var gasUsed uint64 = 10000 - adjustment := 1.2 - - // set up mock node response - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - abciRes := &ctypes.ResultABCIQuery{ - Response: abci.ResponseQuery{ - Value: codec.Cdc.MustMarshalBinaryBare(sdk.SimulationResponse{ - GasInfo: sdk.GasInfo{ - GasUsed: gasUsed, - }, - }), - }, - } - mockClient.EXPECT().ABCIQueryWithOptions("/app/simulate", gomock.Any(), gomock.Any()).Return(abciRes, nil) - - // request - req := codec.MustMarshalJSONIndent(cdc, - &SimulateReq{ - Tx: types.StdTx{ - Memo: "empty tx", - }, - GasAdjustment: fmt.Sprintf("%f", adjustment), - }, - ) - request := http.Request{Body: ioutil.NopCloser(bytes.NewReader(req))} - - writer := mockHTTPWriter{} - SimulateTxRequest(cliCtx)(&writer, &request) - - res := rest.GasEstimateResponse{} - cdc.MustUnmarshalJSON(writer.bodyBuf.Bytes(), &res) - - require.Equal(t, uint64(float64(gasUsed)*adjustment), res.GasEstimate) -} - -func TestSimulateTxRequestWithABCIError(t *testing.T) { - cdc := setupCodec() - - var code uint32 = 10 - codespace := "codespace" - message := "error message" - adjustment := 1.2 - - // set up mock node response - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - abciRes := &ctypes.ResultABCIQuery{ - Response: abci.ResponseQuery{ - Code: code, - Codespace: codespace, - Log: message, - }, - } - mockClient.EXPECT().ABCIQueryWithOptions("/app/simulate", gomock.Any(), gomock.Any()).Return(abciRes, nil) - - // request - req := codec.MustMarshalJSONIndent(cdc, - &SimulateReq{ - Tx: types.StdTx{ - Memo: "empty tx", - }, - GasAdjustment: fmt.Sprintf("%f", adjustment), - }, - ) - request := http.Request{Body: ioutil.NopCloser(bytes.NewReader(req))} - - writer := mockHTTPWriter{} - SimulateTxRequest(cliCtx)(&writer, &request) - - res := ABCIErrorResponse{} - cdc.MustUnmarshalJSON(writer.bodyBuf.Bytes(), &res) - - require.Equal(t, code, res.Code) - require.Equal(t, codespace, res.Codespace) - require.Equal(t, message, res.Error) -} diff --git a/x/account/client/types/block_with_txs.go b/x/account/client/types/block_with_txs.go deleted file mode 100644 index 3c9fdd0e45..0000000000 --- a/x/account/client/types/block_with_txs.go +++ /dev/null @@ -1,53 +0,0 @@ -package types - -import ( - tmtypes "github.com/tendermint/tendermint/types" -) - -type FetchInfo struct { - InclusiveFromHeight int64 - ExclusiveToHeight int64 - HasMore bool - FetchItemCnt int64 - FetchItemRange []int64 -} - -func NewBlockFetchInfo(inclusiveFromHeight int64, exclusiveToHeight int64, hasMore bool) FetchInfo { - fetchItemCnt := exclusiveToHeight - inclusiveFromHeight - fetchItemRange := make([]int64, fetchItemCnt) - for i := range fetchItemRange { - fetchItemRange[i] = inclusiveFromHeight + int64(i) - } - return FetchInfo{inclusiveFromHeight, exclusiveToHeight, hasMore, - fetchItemCnt, fetchItemRange, - } -} - -func NewFetchInfo(latestBlockHeight, fromHeight, fetchSize int64) FetchInfo { - var fetchBlockHeight FetchInfo - switch exclusiveToBlockHeight := fromHeight + fetchSize; { - case latestBlockHeight > exclusiveToBlockHeight-1: - fetchBlockHeight = NewBlockFetchInfo(fromHeight, exclusiveToBlockHeight, true) - case latestBlockHeight == exclusiveToBlockHeight-1: - fetchBlockHeight = NewBlockFetchInfo(fromHeight, exclusiveToBlockHeight, false) - default: - fetchBlockHeight = NewBlockFetchInfo(fromHeight, latestBlockHeight+1, false) - } - return fetchBlockHeight -} - -type HasMoreResponseWrapper struct { - Items []*ResultBlockWithTxResponses `json:"items"` - HasMore bool `json:"has_more"` -} - -type ResultBlockWithTxResponses struct { - ResultBlock *ResultBlock `json:"result_block"` - TxResponses []TxResponse `json:"tx_responses"` -} - -type ResultBlock struct { - BlockSize int `json:"block_size"` - BlockID tmtypes.BlockID `json:"block_id"` - Block *tmtypes.Block `json:"block"` -} diff --git a/x/account/client/types/result.go b/x/account/client/types/result.go deleted file mode 100644 index 786e043f2e..0000000000 --- a/x/account/client/types/result.go +++ /dev/null @@ -1,145 +0,0 @@ -package types - -import ( - "encoding/hex" - "fmt" - "math" - "strings" - - ctypes "github.com/tendermint/tendermint/rpc/core/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/exported" -) - -type TxResponse struct { - Height int64 `json:"height"` - TxHash string `json:"txhash"` - Codespace string `json:"codespace,omitempty"` - Code uint32 `json:"code,omitempty"` - Index uint32 `json:"index"` // additional field - Data string `json:"data,omitempty"` - RawLog string `json:"raw_log,omitempty"` - Logs sdk.ABCIMessageLogs `json:"logs,omitempty"` - Info string `json:"info,omitempty"` - GasWanted int64 `json:"gas_wanted,omitempty"` - GasUsed int64 `json:"gas_used,omitempty"` - Tx sdk.Tx `json:"tx,omitempty"` - Timestamp string `json:"timestamp,omitempty"` -} - -// NewResponseResultTx returns a TxResponse given a ResultTx from tendermint -func NewResponseResultTx(res *ctypes.ResultTx, tx sdk.Tx, timestamp string) TxResponse { - if res == nil { - return TxResponse{} - } - - parsedLogs, err := sdk.ParseABCILogs(res.TxResult.Log) - if err != nil { - parsedLogs = nil - } - - return TxResponse{ - TxHash: res.Hash.String(), - Height: res.Height, - Codespace: res.TxResult.Codespace, - Code: res.TxResult.Code, - Index: res.Index, - Data: strings.ToUpper(hex.EncodeToString(res.TxResult.Data)), - RawLog: res.TxResult.Log, - Logs: parsedLogs, - Info: res.TxResult.Info, - GasWanted: res.TxResult.GasWanted, - GasUsed: res.TxResult.GasUsed, - Tx: tx, - Timestamp: timestamp, - } -} - -func (r TxResponse) String() string { - var sb strings.Builder - sb.WriteString("Response:\n") - - if r.Height > 0 { - sb.WriteString(fmt.Sprintf(" Height: %d\n", r.Height)) - sb.WriteString(fmt.Sprintf(" Index: %d\n", r.Index)) - } - if r.TxHash != "" { - sb.WriteString(fmt.Sprintf(" TxHash: %s\n", r.TxHash)) - } - if r.Codespace != "" { - sb.WriteString(fmt.Sprintf(" Codespace: %s\n", r.Codespace)) - } - if r.Code > 0 { - sb.WriteString(fmt.Sprintf(" Code: %d\n", r.Code)) - } - if r.Data != "" { - sb.WriteString(fmt.Sprintf(" Data: %s\n", r.Data)) - } - if r.RawLog != "" { - sb.WriteString(fmt.Sprintf(" Raw Log: %s\n", r.RawLog)) - } - if r.Logs != nil { - sb.WriteString(fmt.Sprintf(" Logs: %s\n", r.Logs)) - } - if r.Info != "" { - sb.WriteString(fmt.Sprintf(" Info: %s\n", r.Info)) - } - if r.GasWanted != 0 { - sb.WriteString(fmt.Sprintf(" GasWanted: %d\n", r.GasWanted)) - } - if r.GasUsed != 0 { - sb.WriteString(fmt.Sprintf(" GasUsed: %d\n", r.GasUsed)) - } - if r.Timestamp != "" { - sb.WriteString(fmt.Sprintf(" Timestamp: %s\n", r.Timestamp)) - } - - return strings.TrimSpace(sb.String()) -} - -// Empty returns true if the response is empty -func (r TxResponse) Empty() bool { - return r.TxHash == "" && r.Logs == nil -} - -// SearchTxsResult defines a structure for querying txs pageable -type SearchTxsResult struct { - TotalCount int `json:"total_count"` // Count of all txs - Count int `json:"count"` // Count of txs in current page - PageNumber int `json:"page_number"` // Index of current page, start from 1 - PageTotal int `json:"page_total"` // Count of total pages - Limit int `json:"limit"` // Max count txs per page - Txs []TxResponse `json:"txs"` // List of txs in current page -} - -func NewSearchTxsResult(totalCount, count, page, limit int, txs []TxResponse) SearchTxsResult { - return SearchTxsResult{ - TotalCount: totalCount, - Count: count, - PageNumber: page, - PageTotal: int(math.Ceil(float64(totalCount) / float64(limit))), - Limit: limit, - Txs: txs, - } -} - -type SearchGenesisAccountResult struct { - TotalCount int `json:"total_count"` - Count int `json:"count"` - PageNumber int `json:"page_number"` - PageTotal int `json:"page_total"` - Limit int `json:"limit"` - Accounts exported.GenesisAccounts `json:"accounts"` -} - -func NewSearchGenesisAccountResult(totalCount, count, page, limit int, accounts exported.GenesisAccounts) SearchGenesisAccountResult { - return SearchGenesisAccountResult{ - TotalCount: totalCount, - Count: count, - PageNumber: page, - PageTotal: int(math.Ceil(float64(totalCount) / float64(limit))), - Limit: limit, - Accounts: accounts, - } -} diff --git a/x/account/client/utils/alias.go b/x/account/client/utils/alias.go deleted file mode 100644 index ed9be45fd1..0000000000 --- a/x/account/client/utils/alias.go +++ /dev/null @@ -1,11 +0,0 @@ -package utils - -import ( - cosmosutils "github.com/cosmos/cosmos-sdk/x/auth/client/utils" -) - -var ( - GenerateOrBroadcastMsgs = cosmosutils.GenerateOrBroadcastMsgs - GetTxEncoder = cosmosutils.GetTxEncoder - WriteGenerateStdTxResponse = cosmosutils.WriteGenerateStdTxResponse -) diff --git a/x/account/client/utils/block_with_txs.go b/x/account/client/utils/block_with_txs.go deleted file mode 100644 index d1fa115261..0000000000 --- a/x/account/client/utils/block_with_txs.go +++ /dev/null @@ -1,103 +0,0 @@ -package utils - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/line/lbm-sdk/v2/x/account/client/types" - - tmliteProxy "github.com/tendermint/tendermint/lite/proxy" - ctypes "github.com/tendermint/tendermint/rpc/core/types" -) - -func LatestBlockHeight(cliCtx context.CLIContext) (int64, error) { - node, err := cliCtx.GetNode() - if err != nil { - return -1, err - } - - // Get the latest block - latestBlock, err := node.Block(nil) - if err != nil { - return -1, err - } - - return latestBlock.Block.Height, nil -} - -func BlockWithTxResponses(cliCtx context.CLIContext, latestBlockHeight, fromBlockHeight, fetchSize int64) (blockWithRxResultsWrapper *types.HasMoreResponseWrapper, err error) { - fbh := types.NewFetchInfo(latestBlockHeight, fromBlockHeight, fetchSize) - results := make([]*types.ResultBlockWithTxResponses, len(fbh.FetchItemRange)) - for idx, height := range fbh.FetchItemRange { - block, err := getBlock(cliCtx, height) - if err != nil { - return nil, fmt.Errorf("an error occurred while fetching a block by blockHeight(%d), err(%s)", height, err) - } - txs, err := getTxs(cliCtx, height) - if err != nil { - return nil, fmt.Errorf("an error occurred while fetching a block by blockHeight(%d), err(%s)", height, err) - } - results[idx] = &types.ResultBlockWithTxResponses{ - ResultBlock: &types.ResultBlock{ - BlockSize: block.Block.Size(), - BlockID: block.BlockID, - Block: block.Block, - }, - TxResponses: txs, - } - } - - return &types.HasMoreResponseWrapper{ - Items: results, - HasMore: fbh.HasMore, - }, nil -} - -func getBlock(cliCtx context.CLIContext, height int64) (*ctypes.ResultBlock, error) { - node, err := cliCtx.GetNode() - if err != nil { - return nil, err - } - resultBlock, err := node.Block(&height) - if err != nil { - return nil, err - } - - if !cliCtx.TrustNode { - check, err := cliCtx.Verify(resultBlock.Block.Height) - if err != nil { - return nil, err - } - - if err := tmliteProxy.ValidateHeader(&resultBlock.Block.Header, check); err != nil { - return nil, err - } - - if err = tmliteProxy.ValidateBlock(resultBlock.Block, check); err != nil { - return nil, err - } - } - return resultBlock, nil -} - -func getTxs(cliCtx context.CLIContext, height int64) ([]types.TxResponse, error) { - const defaultLimit = 100 - // nolint:prealloc - txResponses := []types.TxResponse{} - - nextTxPage := 1 - for { - searchResult, err := QueryTxsByEvents(cliCtx, []string{fmt.Sprintf("tx.height=%d", height)}, nextTxPage, defaultLimit) - if err != nil { - return nil, err - } - - txResponses = append(txResponses, searchResult.Txs...) - - nextTxPage++ - if nextTxPage > searchResult.PageTotal { - break - } - } - return txResponses, nil -} diff --git a/x/account/client/utils/block_with_txs_test.go b/x/account/client/utils/block_with_txs_test.go deleted file mode 100644 index 0e3fb46462..0000000000 --- a/x/account/client/utils/block_with_txs_test.go +++ /dev/null @@ -1,262 +0,0 @@ -package utils - -import ( - "encoding/binary" - "errors" - "fmt" - "math" - "math/rand" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/golang/mock/gomock" - "github.com/line/lbm-sdk/v2/x/account/client/types" - "github.com/line/lbm-sdk/v2/x/account/client/utils/mock" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/client/context" -) - -func TestLatestBlockHeight(t *testing.T) { - cdc := setupCodec() - height := int64(100) - - resBlock := &ctypes.ResultBlock{ - Block: &tmtypes.Block{ - Header: tmtypes.Header{ - Height: height, - Time: time.Time{}, - }, - }, - } - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - mockClient.EXPECT().Block(nil).Return(resBlock, nil) - - ret, err := LatestBlockHeight(cliCtx) - require.NoError(t, err) - require.Equal(t, height, ret) -} - -func TestBlockWithTxResponses(t *testing.T) { - rand.Seed(time.Now().UnixNano()) - cdc := setupCodec() - - height := int64(100) - - resBlock := &ctypes.ResultBlock{ - Block: &tmtypes.Block{ - Header: tmtypes.Header{ - Height: height, - Time: time.Time{}, - }, - }, - } - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - mockClient.EXPECT().Block(&height).Return(resBlock, nil) - - resTxSearch := &ctypes.ResultTxSearch{ - Txs: nil, - TotalCount: 0, - } - - const defaultLimit = 100 - mockClient.EXPECT(). - TxSearch(fmt.Sprintf("tx.height=%d", height), !cliCtx.TrustNode, 1, defaultLimit, ""). - Return(resTxSearch, nil) - - actual, err := BlockWithTxResponses(cliCtx, height+1, height, int64(1)) - - results := make([]*types.ResultBlockWithTxResponses, 1) - - txResponses := make([]types.TxResponse, 0) - results[0] = &types.ResultBlockWithTxResponses{ - ResultBlock: &types.ResultBlock{ - BlockSize: resBlock.Block.Size(), - BlockID: resBlock.BlockID, - Block: resBlock.Block, - }, - TxResponses: txResponses, - } - expected := &types.HasMoreResponseWrapper{ - Items: results, - HasMore: true, - } - require.NoError(t, err) - require.Equal(t, expected, actual) -} - -func TestLatestBlockHeightWithError(t *testing.T) { - cdc := setupCodec() - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - resError := errors.New("error") - mockClient.EXPECT().Block(nil).Return(nil, resError) - - ret, err := LatestBlockHeight(cliCtx) - require.Error(t, err) - require.Equal(t, int64(-1), ret) -} - -func makeTxs(t *testing.T, cdc *codec.Codec, count int, height int64) []*ctypes.ResultTx { - txs := make([]*ctypes.ResultTx, count) - - stdTx := &auth.StdTx{ - Memo: "empty tx", - } - - emptyTx, err := cdc.MarshalBinaryLengthPrefixed(stdTx) - require.NoError(t, err) - - for i := 0; i < count; i++ { - bs := make([]byte, 32) - binary.LittleEndian.PutUint32(bs, uint32(i)) - txs[i] = &ctypes.ResultTx{ - Hash: bs, - Height: height, - Index: uint32(i), - TxResult: abci.ResponseDeliverTx{ - Code: 0, - Codespace: "codespace", - Log: "[]", - }, - Tx: emptyTx, - } - } - return txs -} - -func TestGetTxs(t *testing.T) { - var parameterizedTests = []struct { - name string - txsCount int - }{ - {"multiple pages(txsCount=123)", 123}, - {"single page(txsCount=12)", 12}, - {"multiple pages fill(txsCount=300)", 300}, - {"single page fill(txsCount=100)", 100}, - {"empty(txsCount=0)", 0}, - } - - for _, pt := range parameterizedTests { - txsCount := pt.txsCount - t.Run(pt.name, func(t *testing.T) { - testGetTxsWithCount(t, txsCount) - }) - } -} - -func testGetTxsWithCount(t *testing.T, txsCount int) { - const defaultLimit = 100 - - cdc := setupCodec() - height := int64(100) - txs := makeTxs(t, cdc, txsCount, height) - - resBlock := &ctypes.ResultBlock{ - Block: &tmtypes.Block{ - Header: tmtypes.Header{ - Height: height, - Time: time.Time{}, - }, - }, - } - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - - mockClient.EXPECT().Block(gomock.Any()).Return(resBlock, nil).AnyTimes() - - if txsCount == 0 { - resTxSearch := &ctypes.ResultTxSearch{ - Txs: nil, - TotalCount: txsCount, - } - mockClient.EXPECT(). - TxSearch(fmt.Sprintf("tx.height=%d", height), !cliCtx.TrustNode, 1, defaultLimit, ""). - Return(resTxSearch, nil) - } else { - for i := 0; i < int(math.Ceil(float64(txsCount)/defaultLimit)); i++ { - start := i * defaultLimit - end := start + defaultLimit - if end > txsCount { - // the last segment - end = txsCount - } - pageTxs := txs[start:end] - resTxSearch := &ctypes.ResultTxSearch{ - Txs: pageTxs, - TotalCount: txsCount, - } - mockClient.EXPECT(). - TxSearch(fmt.Sprintf("tx.height=%d", height), !cliCtx.TrustNode, i+1, defaultLimit, ""). - Return(resTxSearch, nil) - } - } - - ret, err := getTxs(cliCtx, height) - require.NoError(t, err) - require.Len(t, ret, txsCount) -} - -func TestEmptyTxs(t *testing.T) { - const defaultLimit = 100 - - cdc := setupCodec() - height := int64(100) - - resBlock := &ctypes.ResultBlock{ - Block: &tmtypes.Block{ - Header: tmtypes.Header{ - Height: height, - Time: time.Time{}, - }, - }, - } - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - - mockClient.EXPECT().Block(gomock.Any()).Return(resBlock, nil).AnyTimes() - - resTxSearch := &ctypes.ResultTxSearch{ - Txs: nil, - TotalCount: 0, - } - mockClient.EXPECT(). - TxSearch(fmt.Sprintf("tx.height=%d", height), !cliCtx.TrustNode, 1, defaultLimit, ""). - Return(resTxSearch, nil) - - ret, err := getTxs(cliCtx, height) - require.NoError(t, err) - require.NotNil(t, ret) -} diff --git a/x/account/client/utils/mock/client_mock.go b/x/account/client/utils/mock/client_mock.go deleted file mode 100644 index 6b7800935f..0000000000 --- a/x/account/client/utils/mock/client_mock.go +++ /dev/null @@ -1,1146 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: /Users/kfangw/goworkspace/pkg/mod/github.com/tendermint/tendermint@v0.33.3/rpc/client/interface.go - -// Package mock_client is a generated GoMock package. -package mock - -import ( - context "context" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - bytes "github.com/tendermint/tendermint/libs/bytes" - log "github.com/tendermint/tendermint/libs/log" - client "github.com/tendermint/tendermint/rpc/client" - types "github.com/tendermint/tendermint/rpc/core/types" - types0 "github.com/tendermint/tendermint/types" -) - -// MockClient is a mock of Client interface -type MockClient struct { - ctrl *gomock.Controller - recorder *MockClientMockRecorder -} - -// MockClientMockRecorder is the mock recorder for MockClient -type MockClientMockRecorder struct { - mock *MockClient -} - -// NewMockClient creates a new mock instance -func NewMockClient(ctrl *gomock.Controller) *MockClient { - mock := &MockClient{ctrl: ctrl} - mock.recorder = &MockClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockClient) EXPECT() *MockClientMockRecorder { - return m.recorder -} - -// Start mocks base method -func (m *MockClient) Start() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Start") - ret0, _ := ret[0].(error) - return ret0 -} - -// Start indicates an expected call of Start -func (mr *MockClientMockRecorder) Start() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockClient)(nil).Start)) -} - -// OnStart mocks base method -func (m *MockClient) OnStart() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OnStart") - ret0, _ := ret[0].(error) - return ret0 -} - -// OnStart indicates an expected call of OnStart -func (mr *MockClientMockRecorder) OnStart() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnStart", reflect.TypeOf((*MockClient)(nil).OnStart)) -} - -// Stop mocks base method -func (m *MockClient) Stop() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Stop") - ret0, _ := ret[0].(error) - return ret0 -} - -// Stop indicates an expected call of Stop -func (mr *MockClientMockRecorder) Stop() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockClient)(nil).Stop)) -} - -// OnStop mocks base method -func (m *MockClient) OnStop() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "OnStop") -} - -// OnStop indicates an expected call of OnStop -func (mr *MockClientMockRecorder) OnStop() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnStop", reflect.TypeOf((*MockClient)(nil).OnStop)) -} - -// Reset mocks base method -func (m *MockClient) Reset() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Reset") - ret0, _ := ret[0].(error) - return ret0 -} - -// Reset indicates an expected call of Reset -func (mr *MockClientMockRecorder) Reset() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reset", reflect.TypeOf((*MockClient)(nil).Reset)) -} - -// OnReset mocks base method -func (m *MockClient) OnReset() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OnReset") - ret0, _ := ret[0].(error) - return ret0 -} - -// OnReset indicates an expected call of OnReset -func (mr *MockClientMockRecorder) OnReset() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnReset", reflect.TypeOf((*MockClient)(nil).OnReset)) -} - -// IsRunning mocks base method -func (m *MockClient) IsRunning() bool { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "IsRunning") - ret0, _ := ret[0].(bool) - return ret0 -} - -// IsRunning indicates an expected call of IsRunning -func (mr *MockClientMockRecorder) IsRunning() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsRunning", reflect.TypeOf((*MockClient)(nil).IsRunning)) -} - -// Quit mocks base method -func (m *MockClient) Quit() <-chan struct{} { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Quit") - ret0, _ := ret[0].(<-chan struct{}) - return ret0 -} - -// Quit indicates an expected call of Quit -func (mr *MockClientMockRecorder) Quit() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Quit", reflect.TypeOf((*MockClient)(nil).Quit)) -} - -// String mocks base method -func (m *MockClient) String() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "String") - ret0, _ := ret[0].(string) - return ret0 -} - -// String indicates an expected call of String -func (mr *MockClientMockRecorder) String() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockClient)(nil).String)) -} - -// SetLogger mocks base method -func (m *MockClient) SetLogger(arg0 log.Logger) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetLogger", arg0) -} - -// SetLogger indicates an expected call of SetLogger -func (mr *MockClientMockRecorder) SetLogger(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLogger", reflect.TypeOf((*MockClient)(nil).SetLogger), arg0) -} - -// ABCIInfo mocks base method -func (m *MockClient) ABCIInfo() (*types.ResultABCIInfo, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ABCIInfo") - ret0, _ := ret[0].(*types.ResultABCIInfo) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ABCIInfo indicates an expected call of ABCIInfo -func (mr *MockClientMockRecorder) ABCIInfo() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ABCIInfo", reflect.TypeOf((*MockClient)(nil).ABCIInfo)) -} - -// ABCIQuery mocks base method -func (m *MockClient) ABCIQuery(path string, data bytes.HexBytes) (*types.ResultABCIQuery, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ABCIQuery", path, data) - ret0, _ := ret[0].(*types.ResultABCIQuery) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ABCIQuery indicates an expected call of ABCIQuery -func (mr *MockClientMockRecorder) ABCIQuery(path, data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ABCIQuery", reflect.TypeOf((*MockClient)(nil).ABCIQuery), path, data) -} - -// ABCIQueryWithOptions mocks base method -func (m *MockClient) ABCIQueryWithOptions(path string, data bytes.HexBytes, opts client.ABCIQueryOptions) (*types.ResultABCIQuery, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ABCIQueryWithOptions", path, data, opts) - ret0, _ := ret[0].(*types.ResultABCIQuery) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ABCIQueryWithOptions indicates an expected call of ABCIQueryWithOptions -func (mr *MockClientMockRecorder) ABCIQueryWithOptions(path, data, opts interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ABCIQueryWithOptions", reflect.TypeOf((*MockClient)(nil).ABCIQueryWithOptions), path, data, opts) -} - -// BroadcastTxCommit mocks base method -func (m *MockClient) BroadcastTxCommit(tx types0.Tx) (*types.ResultBroadcastTxCommit, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastTxCommit", tx) - ret0, _ := ret[0].(*types.ResultBroadcastTxCommit) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastTxCommit indicates an expected call of BroadcastTxCommit -func (mr *MockClientMockRecorder) BroadcastTxCommit(tx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastTxCommit", reflect.TypeOf((*MockClient)(nil).BroadcastTxCommit), tx) -} - -// BroadcastTxAsync mocks base method -func (m *MockClient) BroadcastTxAsync(tx types0.Tx) (*types.ResultBroadcastTx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastTxAsync", tx) - ret0, _ := ret[0].(*types.ResultBroadcastTx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastTxAsync indicates an expected call of BroadcastTxAsync -func (mr *MockClientMockRecorder) BroadcastTxAsync(tx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastTxAsync", reflect.TypeOf((*MockClient)(nil).BroadcastTxAsync), tx) -} - -// BroadcastTxSync mocks base method -func (m *MockClient) BroadcastTxSync(tx types0.Tx) (*types.ResultBroadcastTx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastTxSync", tx) - ret0, _ := ret[0].(*types.ResultBroadcastTx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastTxSync indicates an expected call of BroadcastTxSync -func (mr *MockClientMockRecorder) BroadcastTxSync(tx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastTxSync", reflect.TypeOf((*MockClient)(nil).BroadcastTxSync), tx) -} - -// Subscribe mocks base method -func (m *MockClient) Subscribe(ctx context.Context, subscriber, query string, outCapacity ...int) (<-chan types.ResultEvent, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, subscriber, query} - for _, a := range outCapacity { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "Subscribe", varargs...) - ret0, _ := ret[0].(<-chan types.ResultEvent) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Subscribe indicates an expected call of Subscribe -func (mr *MockClientMockRecorder) Subscribe(ctx, subscriber, query interface{}, outCapacity ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, subscriber, query}, outCapacity...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Subscribe", reflect.TypeOf((*MockClient)(nil).Subscribe), varargs...) -} - -// Unsubscribe mocks base method -func (m *MockClient) Unsubscribe(ctx context.Context, subscriber, query string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Unsubscribe", ctx, subscriber, query) - ret0, _ := ret[0].(error) - return ret0 -} - -// Unsubscribe indicates an expected call of Unsubscribe -func (mr *MockClientMockRecorder) Unsubscribe(ctx, subscriber, query interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unsubscribe", reflect.TypeOf((*MockClient)(nil).Unsubscribe), ctx, subscriber, query) -} - -// UnsubscribeAll mocks base method -func (m *MockClient) UnsubscribeAll(ctx context.Context, subscriber string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UnsubscribeAll", ctx, subscriber) - ret0, _ := ret[0].(error) - return ret0 -} - -// UnsubscribeAll indicates an expected call of UnsubscribeAll -func (mr *MockClientMockRecorder) UnsubscribeAll(ctx, subscriber interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnsubscribeAll", reflect.TypeOf((*MockClient)(nil).UnsubscribeAll), ctx, subscriber) -} - -// Genesis mocks base method -func (m *MockClient) Genesis() (*types.ResultGenesis, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Genesis") - ret0, _ := ret[0].(*types.ResultGenesis) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Genesis indicates an expected call of Genesis -func (mr *MockClientMockRecorder) Genesis() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Genesis", reflect.TypeOf((*MockClient)(nil).Genesis)) -} - -// BlockchainInfo mocks base method -func (m *MockClient) BlockchainInfo(minHeight, maxHeight int64) (*types.ResultBlockchainInfo, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BlockchainInfo", minHeight, maxHeight) - ret0, _ := ret[0].(*types.ResultBlockchainInfo) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BlockchainInfo indicates an expected call of BlockchainInfo -func (mr *MockClientMockRecorder) BlockchainInfo(minHeight, maxHeight interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockchainInfo", reflect.TypeOf((*MockClient)(nil).BlockchainInfo), minHeight, maxHeight) -} - -// NetInfo mocks base method -func (m *MockClient) NetInfo() (*types.ResultNetInfo, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NetInfo") - ret0, _ := ret[0].(*types.ResultNetInfo) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// NetInfo indicates an expected call of NetInfo -func (mr *MockClientMockRecorder) NetInfo() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetInfo", reflect.TypeOf((*MockClient)(nil).NetInfo)) -} - -// DumpConsensusState mocks base method -func (m *MockClient) DumpConsensusState() (*types.ResultDumpConsensusState, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DumpConsensusState") - ret0, _ := ret[0].(*types.ResultDumpConsensusState) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DumpConsensusState indicates an expected call of DumpConsensusState -func (mr *MockClientMockRecorder) DumpConsensusState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DumpConsensusState", reflect.TypeOf((*MockClient)(nil).DumpConsensusState)) -} - -// ConsensusState mocks base method -func (m *MockClient) ConsensusState() (*types.ResultConsensusState, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConsensusState") - ret0, _ := ret[0].(*types.ResultConsensusState) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ConsensusState indicates an expected call of ConsensusState -func (mr *MockClientMockRecorder) ConsensusState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsensusState", reflect.TypeOf((*MockClient)(nil).ConsensusState)) -} - -// ConsensusParams mocks base method -func (m *MockClient) ConsensusParams(height *int64) (*types.ResultConsensusParams, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConsensusParams", height) - ret0, _ := ret[0].(*types.ResultConsensusParams) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ConsensusParams indicates an expected call of ConsensusParams -func (mr *MockClientMockRecorder) ConsensusParams(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsensusParams", reflect.TypeOf((*MockClient)(nil).ConsensusParams), height) -} - -// Health mocks base method -func (m *MockClient) Health() (*types.ResultHealth, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Health") - ret0, _ := ret[0].(*types.ResultHealth) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Health indicates an expected call of Health -func (mr *MockClientMockRecorder) Health() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Health", reflect.TypeOf((*MockClient)(nil).Health)) -} - -// Block mocks base method -func (m *MockClient) Block(height *int64) (*types.ResultBlock, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Block", height) - ret0, _ := ret[0].(*types.ResultBlock) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Block indicates an expected call of Block -func (mr *MockClientMockRecorder) Block(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Block", reflect.TypeOf((*MockClient)(nil).Block), height) -} - -// BlockResults mocks base method -func (m *MockClient) BlockResults(height *int64) (*types.ResultBlockResults, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BlockResults", height) - ret0, _ := ret[0].(*types.ResultBlockResults) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BlockResults indicates an expected call of BlockResults -func (mr *MockClientMockRecorder) BlockResults(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockResults", reflect.TypeOf((*MockClient)(nil).BlockResults), height) -} - -// Commit mocks base method -func (m *MockClient) Commit(height *int64) (*types.ResultCommit, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Commit", height) - ret0, _ := ret[0].(*types.ResultCommit) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Commit indicates an expected call of Commit -func (mr *MockClientMockRecorder) Commit(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockClient)(nil).Commit), height) -} - -// Validators mocks base method -func (m *MockClient) Validators(height *int64, page, perPage int) (*types.ResultValidators, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Validators", height, page, perPage) - ret0, _ := ret[0].(*types.ResultValidators) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Validators indicates an expected call of Validators -func (mr *MockClientMockRecorder) Validators(height, page, perPage interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Validators", reflect.TypeOf((*MockClient)(nil).Validators), height, page, perPage) -} - -// Tx mocks base method -func (m *MockClient) Tx(hash []byte, prove bool) (*types.ResultTx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Tx", hash, prove) - ret0, _ := ret[0].(*types.ResultTx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Tx indicates an expected call of Tx -func (mr *MockClientMockRecorder) Tx(hash, prove interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Tx", reflect.TypeOf((*MockClient)(nil).Tx), hash, prove) -} - -// TxSearch mocks base method -func (m *MockClient) TxSearch(query string, prove bool, page, perPage int, orderBy string) (*types.ResultTxSearch, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TxSearch", query, prove, page, perPage, orderBy) - ret0, _ := ret[0].(*types.ResultTxSearch) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TxSearch indicates an expected call of TxSearch -func (mr *MockClientMockRecorder) TxSearch(query, prove, page, perPage, orderBy interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TxSearch", reflect.TypeOf((*MockClient)(nil).TxSearch), query, prove, page, perPage, orderBy) -} - -// Status mocks base method -func (m *MockClient) Status() (*types.ResultStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Status") - ret0, _ := ret[0].(*types.ResultStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Status indicates an expected call of Status -func (mr *MockClientMockRecorder) Status() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockClient)(nil).Status)) -} - -// BroadcastEvidence mocks base method -func (m *MockClient) BroadcastEvidence(ev types0.Evidence) (*types.ResultBroadcastEvidence, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastEvidence", ev) - ret0, _ := ret[0].(*types.ResultBroadcastEvidence) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastEvidence indicates an expected call of BroadcastEvidence -func (mr *MockClientMockRecorder) BroadcastEvidence(ev interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastEvidence", reflect.TypeOf((*MockClient)(nil).BroadcastEvidence), ev) -} - -// UnconfirmedTxs mocks base method -func (m *MockClient) UnconfirmedTxs(limit int) (*types.ResultUnconfirmedTxs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UnconfirmedTxs", limit) - ret0, _ := ret[0].(*types.ResultUnconfirmedTxs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UnconfirmedTxs indicates an expected call of UnconfirmedTxs -func (mr *MockClientMockRecorder) UnconfirmedTxs(limit interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnconfirmedTxs", reflect.TypeOf((*MockClient)(nil).UnconfirmedTxs), limit) -} - -// NumUnconfirmedTxs mocks base method -func (m *MockClient) NumUnconfirmedTxs() (*types.ResultUnconfirmedTxs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NumUnconfirmedTxs") - ret0, _ := ret[0].(*types.ResultUnconfirmedTxs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// NumUnconfirmedTxs indicates an expected call of NumUnconfirmedTxs -func (mr *MockClientMockRecorder) NumUnconfirmedTxs() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NumUnconfirmedTxs", reflect.TypeOf((*MockClient)(nil).NumUnconfirmedTxs)) -} - -// MockABCIClient is a mock of ABCIClient interface -type MockABCIClient struct { - ctrl *gomock.Controller - recorder *MockABCIClientMockRecorder -} - -// MockABCIClientMockRecorder is the mock recorder for MockABCIClient -type MockABCIClientMockRecorder struct { - mock *MockABCIClient -} - -// NewMockABCIClient creates a new mock instance -func NewMockABCIClient(ctrl *gomock.Controller) *MockABCIClient { - mock := &MockABCIClient{ctrl: ctrl} - mock.recorder = &MockABCIClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockABCIClient) EXPECT() *MockABCIClientMockRecorder { - return m.recorder -} - -// ABCIInfo mocks base method -func (m *MockABCIClient) ABCIInfo() (*types.ResultABCIInfo, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ABCIInfo") - ret0, _ := ret[0].(*types.ResultABCIInfo) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ABCIInfo indicates an expected call of ABCIInfo -func (mr *MockABCIClientMockRecorder) ABCIInfo() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ABCIInfo", reflect.TypeOf((*MockABCIClient)(nil).ABCIInfo)) -} - -// ABCIQuery mocks base method -func (m *MockABCIClient) ABCIQuery(path string, data bytes.HexBytes) (*types.ResultABCIQuery, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ABCIQuery", path, data) - ret0, _ := ret[0].(*types.ResultABCIQuery) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ABCIQuery indicates an expected call of ABCIQuery -func (mr *MockABCIClientMockRecorder) ABCIQuery(path, data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ABCIQuery", reflect.TypeOf((*MockABCIClient)(nil).ABCIQuery), path, data) -} - -// ABCIQueryWithOptions mocks base method -func (m *MockABCIClient) ABCIQueryWithOptions(path string, data bytes.HexBytes, opts client.ABCIQueryOptions) (*types.ResultABCIQuery, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ABCIQueryWithOptions", path, data, opts) - ret0, _ := ret[0].(*types.ResultABCIQuery) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ABCIQueryWithOptions indicates an expected call of ABCIQueryWithOptions -func (mr *MockABCIClientMockRecorder) ABCIQueryWithOptions(path, data, opts interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ABCIQueryWithOptions", reflect.TypeOf((*MockABCIClient)(nil).ABCIQueryWithOptions), path, data, opts) -} - -// BroadcastTxCommit mocks base method -func (m *MockABCIClient) BroadcastTxCommit(tx types0.Tx) (*types.ResultBroadcastTxCommit, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastTxCommit", tx) - ret0, _ := ret[0].(*types.ResultBroadcastTxCommit) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastTxCommit indicates an expected call of BroadcastTxCommit -func (mr *MockABCIClientMockRecorder) BroadcastTxCommit(tx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastTxCommit", reflect.TypeOf((*MockABCIClient)(nil).BroadcastTxCommit), tx) -} - -// BroadcastTxAsync mocks base method -func (m *MockABCIClient) BroadcastTxAsync(tx types0.Tx) (*types.ResultBroadcastTx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastTxAsync", tx) - ret0, _ := ret[0].(*types.ResultBroadcastTx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastTxAsync indicates an expected call of BroadcastTxAsync -func (mr *MockABCIClientMockRecorder) BroadcastTxAsync(tx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastTxAsync", reflect.TypeOf((*MockABCIClient)(nil).BroadcastTxAsync), tx) -} - -// BroadcastTxSync mocks base method -func (m *MockABCIClient) BroadcastTxSync(tx types0.Tx) (*types.ResultBroadcastTx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastTxSync", tx) - ret0, _ := ret[0].(*types.ResultBroadcastTx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastTxSync indicates an expected call of BroadcastTxSync -func (mr *MockABCIClientMockRecorder) BroadcastTxSync(tx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastTxSync", reflect.TypeOf((*MockABCIClient)(nil).BroadcastTxSync), tx) -} - -// MockSignClient is a mock of SignClient interface -type MockSignClient struct { - ctrl *gomock.Controller - recorder *MockSignClientMockRecorder -} - -// MockSignClientMockRecorder is the mock recorder for MockSignClient -type MockSignClientMockRecorder struct { - mock *MockSignClient -} - -// NewMockSignClient creates a new mock instance -func NewMockSignClient(ctrl *gomock.Controller) *MockSignClient { - mock := &MockSignClient{ctrl: ctrl} - mock.recorder = &MockSignClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockSignClient) EXPECT() *MockSignClientMockRecorder { - return m.recorder -} - -// Block mocks base method -func (m *MockSignClient) Block(height *int64) (*types.ResultBlock, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Block", height) - ret0, _ := ret[0].(*types.ResultBlock) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Block indicates an expected call of Block -func (mr *MockSignClientMockRecorder) Block(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Block", reflect.TypeOf((*MockSignClient)(nil).Block), height) -} - -// BlockResults mocks base method -func (m *MockSignClient) BlockResults(height *int64) (*types.ResultBlockResults, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BlockResults", height) - ret0, _ := ret[0].(*types.ResultBlockResults) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BlockResults indicates an expected call of BlockResults -func (mr *MockSignClientMockRecorder) BlockResults(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockResults", reflect.TypeOf((*MockSignClient)(nil).BlockResults), height) -} - -// Commit mocks base method -func (m *MockSignClient) Commit(height *int64) (*types.ResultCommit, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Commit", height) - ret0, _ := ret[0].(*types.ResultCommit) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Commit indicates an expected call of Commit -func (mr *MockSignClientMockRecorder) Commit(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockSignClient)(nil).Commit), height) -} - -// Validators mocks base method -func (m *MockSignClient) Validators(height *int64, page, perPage int) (*types.ResultValidators, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Validators", height, page, perPage) - ret0, _ := ret[0].(*types.ResultValidators) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Validators indicates an expected call of Validators -func (mr *MockSignClientMockRecorder) Validators(height, page, perPage interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Validators", reflect.TypeOf((*MockSignClient)(nil).Validators), height, page, perPage) -} - -// Tx mocks base method -func (m *MockSignClient) Tx(hash []byte, prove bool) (*types.ResultTx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Tx", hash, prove) - ret0, _ := ret[0].(*types.ResultTx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Tx indicates an expected call of Tx -func (mr *MockSignClientMockRecorder) Tx(hash, prove interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Tx", reflect.TypeOf((*MockSignClient)(nil).Tx), hash, prove) -} - -// TxSearch mocks base method -func (m *MockSignClient) TxSearch(query string, prove bool, page, perPage int, orderBy string) (*types.ResultTxSearch, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TxSearch", query, prove, page, perPage, orderBy) - ret0, _ := ret[0].(*types.ResultTxSearch) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TxSearch indicates an expected call of TxSearch -func (mr *MockSignClientMockRecorder) TxSearch(query, prove, page, perPage, orderBy interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TxSearch", reflect.TypeOf((*MockSignClient)(nil).TxSearch), query, prove, page, perPage, orderBy) -} - -// MockHistoryClient is a mock of HistoryClient interface -type MockHistoryClient struct { - ctrl *gomock.Controller - recorder *MockHistoryClientMockRecorder -} - -// MockHistoryClientMockRecorder is the mock recorder for MockHistoryClient -type MockHistoryClientMockRecorder struct { - mock *MockHistoryClient -} - -// NewMockHistoryClient creates a new mock instance -func NewMockHistoryClient(ctrl *gomock.Controller) *MockHistoryClient { - mock := &MockHistoryClient{ctrl: ctrl} - mock.recorder = &MockHistoryClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockHistoryClient) EXPECT() *MockHistoryClientMockRecorder { - return m.recorder -} - -// Genesis mocks base method -func (m *MockHistoryClient) Genesis() (*types.ResultGenesis, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Genesis") - ret0, _ := ret[0].(*types.ResultGenesis) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Genesis indicates an expected call of Genesis -func (mr *MockHistoryClientMockRecorder) Genesis() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Genesis", reflect.TypeOf((*MockHistoryClient)(nil).Genesis)) -} - -// BlockchainInfo mocks base method -func (m *MockHistoryClient) BlockchainInfo(minHeight, maxHeight int64) (*types.ResultBlockchainInfo, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BlockchainInfo", minHeight, maxHeight) - ret0, _ := ret[0].(*types.ResultBlockchainInfo) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BlockchainInfo indicates an expected call of BlockchainInfo -func (mr *MockHistoryClientMockRecorder) BlockchainInfo(minHeight, maxHeight interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockchainInfo", reflect.TypeOf((*MockHistoryClient)(nil).BlockchainInfo), minHeight, maxHeight) -} - -// MockStatusClient is a mock of StatusClient interface -type MockStatusClient struct { - ctrl *gomock.Controller - recorder *MockStatusClientMockRecorder -} - -// MockStatusClientMockRecorder is the mock recorder for MockStatusClient -type MockStatusClientMockRecorder struct { - mock *MockStatusClient -} - -// NewMockStatusClient creates a new mock instance -func NewMockStatusClient(ctrl *gomock.Controller) *MockStatusClient { - mock := &MockStatusClient{ctrl: ctrl} - mock.recorder = &MockStatusClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockStatusClient) EXPECT() *MockStatusClientMockRecorder { - return m.recorder -} - -// Status mocks base method -func (m *MockStatusClient) Status() (*types.ResultStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Status") - ret0, _ := ret[0].(*types.ResultStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Status indicates an expected call of Status -func (mr *MockStatusClientMockRecorder) Status() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockStatusClient)(nil).Status)) -} - -// MockNetworkClient is a mock of NetworkClient interface -type MockNetworkClient struct { - ctrl *gomock.Controller - recorder *MockNetworkClientMockRecorder -} - -// MockNetworkClientMockRecorder is the mock recorder for MockNetworkClient -type MockNetworkClientMockRecorder struct { - mock *MockNetworkClient -} - -// NewMockNetworkClient creates a new mock instance -func NewMockNetworkClient(ctrl *gomock.Controller) *MockNetworkClient { - mock := &MockNetworkClient{ctrl: ctrl} - mock.recorder = &MockNetworkClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockNetworkClient) EXPECT() *MockNetworkClientMockRecorder { - return m.recorder -} - -// NetInfo mocks base method -func (m *MockNetworkClient) NetInfo() (*types.ResultNetInfo, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NetInfo") - ret0, _ := ret[0].(*types.ResultNetInfo) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// NetInfo indicates an expected call of NetInfo -func (mr *MockNetworkClientMockRecorder) NetInfo() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetInfo", reflect.TypeOf((*MockNetworkClient)(nil).NetInfo)) -} - -// DumpConsensusState mocks base method -func (m *MockNetworkClient) DumpConsensusState() (*types.ResultDumpConsensusState, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DumpConsensusState") - ret0, _ := ret[0].(*types.ResultDumpConsensusState) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DumpConsensusState indicates an expected call of DumpConsensusState -func (mr *MockNetworkClientMockRecorder) DumpConsensusState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DumpConsensusState", reflect.TypeOf((*MockNetworkClient)(nil).DumpConsensusState)) -} - -// ConsensusState mocks base method -func (m *MockNetworkClient) ConsensusState() (*types.ResultConsensusState, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConsensusState") - ret0, _ := ret[0].(*types.ResultConsensusState) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ConsensusState indicates an expected call of ConsensusState -func (mr *MockNetworkClientMockRecorder) ConsensusState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsensusState", reflect.TypeOf((*MockNetworkClient)(nil).ConsensusState)) -} - -// ConsensusParams mocks base method -func (m *MockNetworkClient) ConsensusParams(height *int64) (*types.ResultConsensusParams, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConsensusParams", height) - ret0, _ := ret[0].(*types.ResultConsensusParams) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ConsensusParams indicates an expected call of ConsensusParams -func (mr *MockNetworkClientMockRecorder) ConsensusParams(height interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsensusParams", reflect.TypeOf((*MockNetworkClient)(nil).ConsensusParams), height) -} - -// Health mocks base method -func (m *MockNetworkClient) Health() (*types.ResultHealth, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Health") - ret0, _ := ret[0].(*types.ResultHealth) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Health indicates an expected call of Health -func (mr *MockNetworkClientMockRecorder) Health() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Health", reflect.TypeOf((*MockNetworkClient)(nil).Health)) -} - -// MockEventsClient is a mock of EventsClient interface -type MockEventsClient struct { - ctrl *gomock.Controller - recorder *MockEventsClientMockRecorder -} - -// MockEventsClientMockRecorder is the mock recorder for MockEventsClient -type MockEventsClientMockRecorder struct { - mock *MockEventsClient -} - -// NewMockEventsClient creates a new mock instance -func NewMockEventsClient(ctrl *gomock.Controller) *MockEventsClient { - mock := &MockEventsClient{ctrl: ctrl} - mock.recorder = &MockEventsClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockEventsClient) EXPECT() *MockEventsClientMockRecorder { - return m.recorder -} - -// Subscribe mocks base method -func (m *MockEventsClient) Subscribe(ctx context.Context, subscriber, query string, outCapacity ...int) (<-chan types.ResultEvent, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, subscriber, query} - for _, a := range outCapacity { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "Subscribe", varargs...) - ret0, _ := ret[0].(<-chan types.ResultEvent) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Subscribe indicates an expected call of Subscribe -func (mr *MockEventsClientMockRecorder) Subscribe(ctx, subscriber, query interface{}, outCapacity ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, subscriber, query}, outCapacity...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Subscribe", reflect.TypeOf((*MockEventsClient)(nil).Subscribe), varargs...) -} - -// Unsubscribe mocks base method -func (m *MockEventsClient) Unsubscribe(ctx context.Context, subscriber, query string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Unsubscribe", ctx, subscriber, query) - ret0, _ := ret[0].(error) - return ret0 -} - -// Unsubscribe indicates an expected call of Unsubscribe -func (mr *MockEventsClientMockRecorder) Unsubscribe(ctx, subscriber, query interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unsubscribe", reflect.TypeOf((*MockEventsClient)(nil).Unsubscribe), ctx, subscriber, query) -} - -// UnsubscribeAll mocks base method -func (m *MockEventsClient) UnsubscribeAll(ctx context.Context, subscriber string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UnsubscribeAll", ctx, subscriber) - ret0, _ := ret[0].(error) - return ret0 -} - -// UnsubscribeAll indicates an expected call of UnsubscribeAll -func (mr *MockEventsClientMockRecorder) UnsubscribeAll(ctx, subscriber interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnsubscribeAll", reflect.TypeOf((*MockEventsClient)(nil).UnsubscribeAll), ctx, subscriber) -} - -// MockMempoolClient is a mock of MempoolClient interface -type MockMempoolClient struct { - ctrl *gomock.Controller - recorder *MockMempoolClientMockRecorder -} - -// MockMempoolClientMockRecorder is the mock recorder for MockMempoolClient -type MockMempoolClientMockRecorder struct { - mock *MockMempoolClient -} - -// NewMockMempoolClient creates a new mock instance -func NewMockMempoolClient(ctrl *gomock.Controller) *MockMempoolClient { - mock := &MockMempoolClient{ctrl: ctrl} - mock.recorder = &MockMempoolClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockMempoolClient) EXPECT() *MockMempoolClientMockRecorder { - return m.recorder -} - -// UnconfirmedTxs mocks base method -func (m *MockMempoolClient) UnconfirmedTxs(limit int) (*types.ResultUnconfirmedTxs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UnconfirmedTxs", limit) - ret0, _ := ret[0].(*types.ResultUnconfirmedTxs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UnconfirmedTxs indicates an expected call of UnconfirmedTxs -func (mr *MockMempoolClientMockRecorder) UnconfirmedTxs(limit interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnconfirmedTxs", reflect.TypeOf((*MockMempoolClient)(nil).UnconfirmedTxs), limit) -} - -// NumUnconfirmedTxs mocks base method -func (m *MockMempoolClient) NumUnconfirmedTxs() (*types.ResultUnconfirmedTxs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NumUnconfirmedTxs") - ret0, _ := ret[0].(*types.ResultUnconfirmedTxs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// NumUnconfirmedTxs indicates an expected call of NumUnconfirmedTxs -func (mr *MockMempoolClientMockRecorder) NumUnconfirmedTxs() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NumUnconfirmedTxs", reflect.TypeOf((*MockMempoolClient)(nil).NumUnconfirmedTxs)) -} - -// MockEvidenceClient is a mock of EvidenceClient interface -type MockEvidenceClient struct { - ctrl *gomock.Controller - recorder *MockEvidenceClientMockRecorder -} - -// MockEvidenceClientMockRecorder is the mock recorder for MockEvidenceClient -type MockEvidenceClientMockRecorder struct { - mock *MockEvidenceClient -} - -// NewMockEvidenceClient creates a new mock instance -func NewMockEvidenceClient(ctrl *gomock.Controller) *MockEvidenceClient { - mock := &MockEvidenceClient{ctrl: ctrl} - mock.recorder = &MockEvidenceClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockEvidenceClient) EXPECT() *MockEvidenceClientMockRecorder { - return m.recorder -} - -// BroadcastEvidence mocks base method -func (m *MockEvidenceClient) BroadcastEvidence(ev types0.Evidence) (*types.ResultBroadcastEvidence, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastEvidence", ev) - ret0, _ := ret[0].(*types.ResultBroadcastEvidence) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BroadcastEvidence indicates an expected call of BroadcastEvidence -func (mr *MockEvidenceClientMockRecorder) BroadcastEvidence(ev interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastEvidence", reflect.TypeOf((*MockEvidenceClient)(nil).BroadcastEvidence), ev) -} diff --git a/x/account/client/utils/query.go b/x/account/client/utils/query.go deleted file mode 100644 index eb64cc6f34..0000000000 --- a/x/account/client/utils/query.go +++ /dev/null @@ -1,359 +0,0 @@ -package utils - -import ( - "encoding/hex" - "errors" - "fmt" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - ctypes "github.com/tendermint/tendermint/rpc/core/types" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - cutils "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/cosmos/cosmos-sdk/x/auth/types" - gtypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - - local "github.com/line/lbm-sdk/v2/x/account/client/types" -) - -const MaxPerPage = 100 - -// QueryTxsByEvents performs a search for transactions for a given set of events -// via the Tendermint RPC. An event takes the form of: -// "{eventAttribute}.{attributeKey} = '{attributeValue}'". Each event is -// concatenated with an 'AND' operand. It returns a slice of Info object -// containing txs and metadata. An error is returned if the query fails. -func QueryTxsByEvents(cliCtx context.CLIContext, events []string, page, limit int) (*local.SearchTxsResult, error) { - if len(events) == 0 { - return nil, errors.New("must declare at least one event to search") - } - - if page <= 0 { - return nil, errors.New("page must greater than 0") - } - - if limit <= 0 { - return nil, errors.New("limit must greater than 0") - } - - // XXX: implement ANY - query := strings.Join(events, " AND ") - - node, err := cliCtx.GetNode() - if err != nil { - return nil, err - } - - prove := !cliCtx.TrustNode - - resTxs, err := node.TxSearch(query, prove, page, limit, "") - if err != nil { - return nil, err - } - - if prove { - for _, tx := range resTxs.Txs { - err := cutils.ValidateTxResult(cliCtx, tx) - if err != nil { - return nil, err - } - } - } - - resBlocks, err := getBlocksForTxResults(cliCtx, resTxs.Txs) - if err != nil { - return nil, err - } - - txs, err := formatTxResults(cliCtx.Codec, resTxs.Txs, resBlocks) - if err != nil { - return nil, err - } - - result := local.NewSearchTxsResult(resTxs.TotalCount, len(txs), page, limit, txs) - - return &result, nil -} - -// QueryTx queries for a single transaction by a hash string in hex format. An -// error is returned if the transaction does not exist or cannot be queried. -func QueryTx(cliCtx context.CLIContext, hashHexStr string) (local.TxResponse, error) { - hash, err := hex.DecodeString(hashHexStr) - if err != nil { - return local.TxResponse{}, err - } - - node, err := cliCtx.GetNode() - if err != nil { - return local.TxResponse{}, err - } - - resTx, err := node.Tx(hash, !cliCtx.TrustNode) - if err != nil { - return local.TxResponse{}, err - } - - if !cliCtx.TrustNode { - if err = cutils.ValidateTxResult(cliCtx, resTx); err != nil { - return local.TxResponse{}, err - } - } - - resBlocks, err := getBlocksForTxResults(cliCtx, []*ctypes.ResultTx{resTx}) - if err != nil { - return local.TxResponse{}, err - } - - out, err := formatTxResult(cliCtx.Codec, resTx, resBlocks[resTx.Height]) - if err != nil { - return out, err - } - - return out, nil -} - -func QueryGenesisTx(cliCtx context.CLIContext) ([]sdk.Tx, error) { - node, err := cliCtx.GetNode() - if err != nil { - return []sdk.Tx{}, nil - } - - resultGenesis, err := node.Genesis() - if err != nil { - return []sdk.Tx{}, err - } - - appState, err := gtypes.GenesisStateFromGenDoc(cliCtx.Codec, *resultGenesis.Genesis) - if err != nil { - return []sdk.Tx{}, err - } - - genState := gtypes.GetGenesisStateFromAppState(cliCtx.Codec, appState) - genTxs := make([]sdk.Tx, len(genState.GenTxs)) - for i, tx := range genState.GenTxs { - err := cliCtx.Codec.UnmarshalJSON(tx, &genTxs[i]) - if err != nil { - return []sdk.Tx{}, err - } - } - return genTxs, nil -} - -func QueryGenesisAccount(cliCtx context.CLIContext, page, perPage int) (local.SearchGenesisAccountResult, error) { - node, err := cliCtx.GetNode() - if err != nil { - return local.SearchGenesisAccountResult{}, err - } - - resultGenesis, err := node.Genesis() - if err != nil { - return local.SearchGenesisAccountResult{}, err - } - - appState, err := gtypes.GenesisStateFromGenDoc(cliCtx.Codec, *resultGenesis.Genesis) - if err != nil { - return local.SearchGenesisAccountResult{}, err - } - - genAccounts := types.GetGenesisStateFromAppState(cliCtx.Codec, appState).Accounts - totalCount := len(genAccounts) - - perPage, err = validatePerPage(perPage) - if err != nil { - return local.SearchGenesisAccountResult{}, err - } - - page, err = validatePage(page, perPage, totalCount) - if err != nil { - return local.SearchGenesisAccountResult{}, err - } - start, end := getCountIndexRange(page, perPage, totalCount) - resultAccounts := genAccounts[start:end] - - return local.NewSearchGenesisAccountResult(totalCount, len(resultAccounts), page, perPage, resultAccounts), nil -} - -func validatePage(page, perPage, totalCount int) (int, error) { - if page < 1 { - return 1, fmt.Errorf("the page must greater than 0") - } - - pages := ((totalCount - 1) / perPage) + 1 - if pages == 0 { - pages = 1 - } - if page < 0 || page > pages { - return 1, fmt.Errorf("the page should be within [1, %d] range, given %d", pages, page) - } - - return page, nil -} - -func validatePerPage(perPage int) (int, error) { - if perPage < 1 { - return 1, fmt.Errorf("the limit must greater than 0") - } - - if perPage > MaxPerPage { - return MaxPerPage, nil - } - return perPage, nil -} - -func getCountIndexRange(page, perPage, totalCount int) (int, int) { - start := (page - 1) * perPage - end := start + perPage - if start < 0 { - return 0, end - } - if end > totalCount { - end = totalCount - } - - return start, end -} - -// formatTxResults parses the indexed txs into a slice of TxResponse objects. -func formatTxResults(cdc *codec.Codec, resTxs []*ctypes.ResultTx, resBlocks map[int64]*ctypes.ResultBlock) ([]local.TxResponse, error) { - var err error - out := make([]local.TxResponse, len(resTxs)) - for i := range resTxs { - out[i], err = formatTxResult(cdc, resTxs[i], resBlocks[resTxs[i].Height]) - if err != nil { - return nil, err - } - } - - return out, nil -} - -func getBlocksForTxResults(cliCtx context.CLIContext, resTxs []*ctypes.ResultTx) (map[int64]*ctypes.ResultBlock, error) { - node, err := cliCtx.GetNode() - if err != nil { - return nil, err - } - - resBlocks := make(map[int64]*ctypes.ResultBlock) - - for _, resTx := range resTxs { - if _, ok := resBlocks[resTx.Height]; !ok { - resBlock, err := node.Block(&resTx.Height) - if err != nil { - return nil, err - } - - resBlocks[resTx.Height] = resBlock - } - } - - return resBlocks, nil -} - -func formatTxResult(cdc *codec.Codec, resTx *ctypes.ResultTx, resBlock *ctypes.ResultBlock) (local.TxResponse, error) { - tx, err := parseTx(cdc, resTx.Tx) - if err != nil { - return local.TxResponse{}, err - } - - return local.NewResponseResultTx(resTx, tx, resBlock.Block.Time.Format(time.RFC3339)), nil -} - -func parseTx(cdc *codec.Codec, txBytes []byte) (sdk.Tx, error) { - var tx types.StdTx - - err := cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx) - if err != nil { - return nil, err - } - - return tx, nil -} - -// ParseHTTPArgs parses the request's URL and returns a slice containing all -// arguments pairs. It separates page and limit used for pagination. -func ParseHTTPArgs(r *http.Request) (tags []string, page, limit int, err error) { - tags = make([]string, 0, len(r.Form)) - for key, values := range r.Form { - if key == "page" || key == "limit" || key == "height.from" || key == "height.to" { - continue - } - - var value string - value, err = url.QueryUnescape(values[0]) - if err != nil { - return tags, page, limit, err - } - - var tag string - if key == tmtypes.TxHeightKey { - tag = fmt.Sprintf("%s=%s", key, value) - } else { - tag = fmt.Sprintf("%s='%s'", key, value) - } - tags = append(tags, tag) - } - - heightFromStr := r.FormValue("height.from") - if heightFromStr != "" { - heightFrom, err := strconv.ParseInt(heightFromStr, 10, 64) - switch { - case err != nil: - return tags, page, limit, err - case heightFrom <= 0: - return tags, page, limit, errors.New("height.from must greater than 0") - default: - tags = append(tags, fmt.Sprintf("%s>=%d", tmtypes.TxHeightKey, heightFrom)) - } - } - - heightToStr := r.FormValue("height.to") - if heightToStr != "" { - heightTo, err := strconv.ParseInt(heightToStr, 10, 64) - switch { - case err != nil: - return tags, page, limit, err - case heightTo <= 0: - return tags, page, limit, errors.New("height.to must greater than 0") - default: - tags = append(tags, fmt.Sprintf("%s<=%d", tmtypes.TxHeightKey, heightTo)) - } - } - - if len(tags) == 0 { - return tags, page, limit, errors.New("must declare at least one event to search") - } - - pageStr := r.FormValue("page") - if pageStr == "" { - page = rest.DefaultPage - } else { - page, err = strconv.Atoi(pageStr) - if err != nil { - return tags, page, limit, err - } else if page <= 0 { - return tags, page, limit, errors.New("page must greater than 0") - } - } - - limitStr := r.FormValue("limit") - if limitStr == "" { - limit = rest.DefaultLimit - } else { - limit, err = strconv.Atoi(limitStr) - if err != nil { - return tags, page, limit, err - } else if limit <= 0 { - return tags, page, limit, errors.New("limit must greater than 0") - } - } - - return tags, page, limit, nil -} diff --git a/x/account/client/utils/query_test.go b/x/account/client/utils/query_test.go deleted file mode 100644 index f544bf946b..0000000000 --- a/x/account/client/utils/query_test.go +++ /dev/null @@ -1,407 +0,0 @@ -package utils - -import ( - "encoding/hex" - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/golang/mock/gomock" - "github.com/line/lbm-sdk/v2/x/account/client/utils/mock" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth" - - atypes "github.com/line/lbm-sdk/v2/x/account/client/types" -) - -type mockNodeResponses struct { - resTx *ctypes.ResultTx - resBlock *ctypes.ResultBlock - resTxSearch *ctypes.ResultTxSearch -} - -// nolint:unparam -func setupMockNodeResponses( - t *testing.T, - cdc *codec.Codec, - hashString string, - height int64, - index uint32, - code uint32, - codespace string, -) mockNodeResponses { - hash, err := hex.DecodeString(hashString) - assert.NoError(t, err) - - stdTx := &auth.StdTx{ - Memo: "empty tx", - } - - bz, err := cdc.MarshalBinaryLengthPrefixed(stdTx) - assert.NoError(t, err) - resTx := &ctypes.ResultTx{ - Hash: hash, - Height: height, - Index: index, - TxResult: abci.ResponseDeliverTx{ - Code: code, - Codespace: codespace, - Log: "[]", - }, - Tx: bz, - } - resBlock := &ctypes.ResultBlock{ - Block: &tmtypes.Block{ - Header: tmtypes.Header{ - Height: height, - Time: time.Time{}, - }, - }, - } - resTxSearch := &ctypes.ResultTxSearch{ - Txs: []*ctypes.ResultTx{resTx}, - TotalCount: 1, - } - - return mockNodeResponses{ - resTx: resTx, - resBlock: resBlock, - resTxSearch: resTxSearch, - } -} - -func setupCodec() *codec.Codec { - cdc := codec.New() - auth.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - sdk.RegisterCodec(cdc) - return cdc -} - -func TestQueryTxsByEventsResponseContainsIndexCodeCodespace(t *testing.T) { - // nolint:goconst - hashString := "15E23C9F72602046D86BC9F0ECAE53E43A8206C113A29D94454476B9887AAB7F" - height := int64(100) - index := uint32(10) - code := uint32(0) - // nolint:goconst - codespace := "codespace" - - cdc := setupCodec() - nodeResponses := setupMockNodeResponses(t, cdc, hashString, height, index, code, codespace) - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - mockClient.EXPECT().TxSearch("tx.height=0", !cliCtx.TrustNode, 1, 30, "").Return(nodeResponses.resTxSearch, nil) - - mockClient.EXPECT().Block(&nodeResponses.resTx.Height).Return(nodeResponses.resBlock, nil) - - res, err := QueryTxsByEvents(cliCtx, []string{"tx.height=0"}, 1, 30) - assert.NoError(t, err) - assert.Equal(t, 1, res.Count) - assertTxResponse(t, hashString, height, index, code, codespace, res.Txs[0]) -} - -func TestQueryTxResponseContainsIndexCodeCodespace(t *testing.T) { - hashString := "15E23C9F72602046D86BC9F0ECAE53E43A8206C113A29D94454476B9887AAB7F" - height := int64(100) - index := uint32(10) - code := uint32(0) - codespace := "codespace" - - cdc := setupCodec() - nodeResponses := setupMockNodeResponses(t, cdc, hashString, height, index, code, codespace) - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - - hash, err := hex.DecodeString(hashString) - assert.NoError(t, err) - mockClient.EXPECT().Tx(hash, !cliCtx.TrustNode).Return(nodeResponses.resTx, nil) - mockClient.EXPECT().Block(&nodeResponses.resTx.Height).Return(nodeResponses.resBlock, nil) - - res, err := QueryTx(cliCtx, hashString) - assert.NoError(t, err) - assertTxResponse(t, hashString, height, index, code, codespace, res) -} - -func assertTxResponse( - t *testing.T, - hashString string, - height int64, - index, code uint32, - codespace string, - res atypes.TxResponse, -) { - assert.Equal(t, height, res.Height) - assert.Equal(t, index, res.Index) - assert.Equal(t, hashString, res.TxHash) - assert.Equal(t, code, res.Code) - assert.Equal(t, codespace, res.Codespace) -} - -// nolint:dupl -func TestQueryTxMarshalledResponseContainsIndexCodeCodespace(t *testing.T) { - hashString := "15E23C9F72602046D86BC9F0ECAE53E43A8206C113A29D94454476B9887AAB7F" - height := int64(100) - index := uint32(10) - code := uint32(1) - codespace := "codespace" - - cdc := setupCodec() - nodeResponses := setupMockNodeResponses(t, cdc, hashString, height, index, code, codespace) - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - - hash, err := hex.DecodeString(hashString) - assert.NoError(t, err) - mockClient.EXPECT().Tx(hash, !cliCtx.TrustNode).Return(nodeResponses.resTx, nil) - mockClient.EXPECT().Block(&nodeResponses.resTx.Height).Return(nodeResponses.resBlock, nil) - - res, err := QueryTx(cliCtx, hashString) - assert.NoError(t, err) - - out, err := cdc.MarshalJSONIndent(res, "", " ") - assert.NoError(t, err) - - var m map[string]interface{} - err = json.Unmarshal(out, &m) - assert.NoError(t, err) - - assert.Contains(t, m, "index") - assert.Contains(t, m, "code") - assert.Contains(t, m, "codespace") -} - -// nolint:dupl -func TestQueryTxMarshalledResponseEmptyIndexCodeCodespace(t *testing.T) { - hashString := "15E23C9F72602046D86BC9F0ECAE53E43A8206C113A29D94454476B9887AAB7F" - height := int64(100) - index := uint32(0) - code := uint32(0) - codespace := "" - - cdc := setupCodec() - nodeResponses := setupMockNodeResponses(t, cdc, hashString, height, index, code, codespace) - - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - - hash, err := hex.DecodeString(hashString) - assert.NoError(t, err) - mockClient.EXPECT().Tx(hash, !cliCtx.TrustNode).Return(nodeResponses.resTx, nil) - mockClient.EXPECT().Block(&nodeResponses.resTx.Height).Return(nodeResponses.resBlock, nil) - - res, err := QueryTx(cliCtx, hashString) - assert.NoError(t, err) - - out, err := cdc.MarshalJSONIndent(res, "", " ") - assert.NoError(t, err) - - var m map[string]interface{} - err = json.Unmarshal(out, &m) - assert.NoError(t, err) - - assert.Contains(t, m, "index") - assert.NotContains(t, m, "code") - assert.NotContains(t, m, "codespace") -} - -func TestQueryGenesisTxs(t *testing.T) { - cdc := setupCodec() - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - - // exist genesis tx - genesisDoc := tmtypes.GenesisDoc{ - AppState: json.RawMessage(`{"genutil":{"gentxs":[{"type":"cosmos-sdk/StdTx","value":{"memo":"test_genesis"}}]}}`), - } - genesisResult := ctypes.ResultGenesis{ - Genesis: &genesisDoc, - } - mockClient.EXPECT().Genesis().Return(&genesisResult, nil) - - genesisTxs, err := QueryGenesisTx(cliCtx) - assert.NoError(t, err) - assert.NotEmpty(t, genesisTxs) - - // not exist genesis tx - genesisDoc = tmtypes.GenesisDoc{ - AppState: json.RawMessage(`{"genutil":{"gentxs":[]}`), - } - genesisResult = ctypes.ResultGenesis{ - Genesis: &genesisDoc, - } - mockClient.EXPECT().Genesis().Return(&genesisResult, nil) - genesisTxs, err = QueryGenesisTx(cliCtx) - assert.Empty(t, genesisTxs) - assert.Error(t, err) -} - -func TestQueryGenesisAccount(t *testing.T) { - testQueryGenesisAccount(t, "link") - testQueryGenesisAccount(t, "tlink") -} - -func testQueryGenesisAccount(t *testing.T, prefix string) { - config := sdk.GetConfig() - config.SetBech32PrefixForAccount(prefix, prefix+sdk.PrefixPublic) - - cdc := setupCodec() - mockClient := mock.NewMockClient(gomock.NewController(t)) - cliCtx := context.CLIContext{ - Client: mockClient, - TrustNode: true, - Codec: cdc, - } - - // exist genesis account - var addr string - if config.GetBech32AccountAddrPrefix() == "tlink" { - addr = "tlink19rqsvml8ldr0yrhaewgv9smcdvrew5panjryj3" - } else { - addr = "link19rqsvml8ldr0yrhaewgv9smcdvrew5pah9j5t5" - } - genesisDoc := tmtypes.GenesisDoc{ - AppState: json.RawMessage(`{"auth":{"accounts":[{"type":"cosmos-sdk/Account","value":{"address":"` + addr + `","coins":[]}}]}}`), - } - genesisResult := ctypes.ResultGenesis{ - Genesis: &genesisDoc, - } - mockClient.EXPECT().Genesis().Return(&genesisResult, nil).AnyTimes() - res, err := QueryGenesisAccount(cliCtx, 1, 2) - assert.NoError(t, err) - assert.Equal(t, 1, len(res.Accounts)) - - // no exist page - res, err = QueryGenesisAccount(cliCtx, 2, 1) - assert.Error(t, err) - assert.Equal(t, 0, len(res.Accounts)) - - // page=0 - res, err = QueryGenesisAccount(cliCtx, 0, 1) - assert.Error(t, err) - assert.Equal(t, 0, len(res.Accounts)) - - // page=-1 - res, err = QueryGenesisAccount(cliCtx, -1, 1) - assert.Error(t, err) - assert.Equal(t, 0, len(res.Accounts)) - - // limit=-1 - res, err = QueryGenesisAccount(cliCtx, 1, -1) - assert.Error(t, err) - assert.Equal(t, 0, len(res.Accounts)) -} - -func TestParseHTTPArgs(t *testing.T) { - reqE0 := mustNewGetRequest(t, "/") - - req0 := mustNewGetRequest(t, "/?foo=faa") - - req1 := mustNewGetRequest(t, "/?foo=faa&limit=5") - req2 := mustNewGetRequest(t, "/?foo=faa&page=5") - req3 := mustNewGetRequest(t, "/?foo=faa&page=5&limit=5") - - reqE1 := mustNewGetRequest(t, "/?foo=faa&page=-1") - reqE2 := mustNewGetRequest(t, "/?foo=faa&limit=-1") - reqE3 := mustNewGetRequest(t, "/?page=5&limit=5") - - req4 := mustNewGetRequest(t, "/?foo=faa&height.from=1") - req5 := mustNewGetRequest(t, "/?foo=faa&height.to=1") - - reqE4 := mustNewGetRequest(t, "/?foo=faa&height.from=-1") - reqE5 := mustNewGetRequest(t, "/?foo=faa&height.to=-1") - - defaultPage := rest.DefaultPage - defaultLimit := rest.DefaultLimit - - tests := []struct { - name string - req *http.Request - w http.ResponseWriter - tags []string - page int - limit int - err bool - }{ - {"no params", reqE0, httptest.NewRecorder(), []string{}, defaultPage, defaultLimit, true}, - - {"tags", req0, httptest.NewRecorder(), []string{"foo='faa'"}, defaultPage, defaultLimit, false}, - - {"limit", req1, httptest.NewRecorder(), []string{"foo='faa'"}, defaultPage, 5, false}, - {"page", req2, httptest.NewRecorder(), []string{"foo='faa'"}, 5, defaultLimit, false}, - {"page and limit", req3, httptest.NewRecorder(), []string{"foo='faa'"}, 5, 5, false}, - - {"error page 0", reqE1, httptest.NewRecorder(), []string{}, defaultPage, defaultLimit, true}, - {"error limit 0", reqE2, httptest.NewRecorder(), []string{}, defaultPage, defaultLimit, true}, - {"no tags", reqE3, httptest.NewRecorder(), []string{}, defaultPage, defaultLimit, true}, - - {"height from", req4, httptest.NewRecorder(), []string{"foo='faa'", "tx.height>=1"}, defaultPage, defaultLimit, false}, - {"height to", req5, httptest.NewRecorder(), []string{"foo='faa'", "tx.height<=1"}, defaultPage, defaultLimit, false}, - - {"error height from", reqE4, httptest.NewRecorder(), []string{}, defaultPage, defaultLimit, true}, - {"error height to", reqE5, httptest.NewRecorder(), []string{}, defaultPage, defaultLimit, true}, - } - - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - tags, page, limit, err := ParseHTTPArgs(tt.req) - if tt.err { - require.NotNil(t, err) - } else { - require.Nil(t, err) - require.Equal(t, tt.tags, tags) - require.Equal(t, tt.page, page) - require.Equal(t, tt.limit, limit) - } - }) - } -} - -func mustNewRequest(t *testing.T, method, url string, body io.Reader) *http.Request { - req, err := http.NewRequest(method, url, body) - require.NoError(t, err) - err = req.ParseForm() - require.NoError(t, err) - return req -} - -func mustNewGetRequest(t *testing.T, url string) *http.Request { - return mustNewRequest(t, "GET", url, nil) -} diff --git a/x/account/handler.go b/x/account/handler.go deleted file mode 100644 index 86be7b3458..0000000000 --- a/x/account/handler.go +++ /dev/null @@ -1,61 +0,0 @@ -package account - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/line/lbm-sdk/v2/x/account/internal/types" -) - -// NewHandler returns a handler for "account" type messages. -func NewHandler(k auth.AccountKeeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - switch msg := msg.(type) { - case types.MsgCreateAccount: - return handleMsgCreateAccount(ctx, k, msg) - case types.MsgEmpty: - return handleMsgEmpty(ctx, msg) - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized account message type: %T", msg) - } - } -} - -func handleMsgCreateAccount(ctx sdk.Context, keeper auth.AccountKeeper, msg types.MsgCreateAccount) (*sdk.Result, error) { - if keeper.GetAccount(ctx, msg.Target) != nil { - return nil, types.ErrAccountAlreadyExist - } - - acc := keeper.NewAccountWithAddress(ctx, msg.Target) - - keeper.SetAccount(ctx, acc) - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventCreateAccount, - sdk.NewAttribute(types.AttributeKeyCreateAccountFrom, msg.From.String()), - sdk.NewAttribute(types.AttributeKeyCreateAccountTarget, msg.Target.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - sdk.NewAttribute(sdk.AttributeKeyAction, types.EventCreateAccount), - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgEmpty(ctx sdk.Context, msg types.MsgEmpty) (*sdk.Result, error) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeyAction, types.EventEmpty), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/account/handler_test.go b/x/account/handler_test.go deleted file mode 100644 index 0554e50133..0000000000 --- a/x/account/handler_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package account - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/line/lbm-sdk/v2/x/account/internal/types" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/secp256k1" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" -) - -var ( - priv1 = secp256k1.GenPrivKey() - addr1 = sdk.AccAddress(priv1.PubKey().Address()) - priv2 = secp256k1.GenPrivKey() - addr2 = sdk.AccAddress(priv2.PubKey().Address()) -) - -type TestInput struct { - Cdc *codec.Codec - Ctx sdk.Context - Ak auth.AccountKeeper -} - -func newTestCodec() *codec.Codec { - cdc := codec.New() - auth.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - return cdc -} - -func setupTestInput(t *testing.T) TestInput { - keyAuth := sdk.NewKVStoreKey(auth.StoreKey) - keyParams := sdk.NewKVStoreKey(params.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) - - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyAuth, sdk.StoreTypeIAVL, db) - err := ms.LoadLatestVersion() - require.NoError(t, err) - - cdc := newTestCodec() - - // init params keeper and subspaces - paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams) - authSubspace := paramsKeeper.Subspace(auth.DefaultParamspace) - - ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) - - // add keepers - accountKeeper := auth.NewAccountKeeper(cdc, keyAuth, authSubspace, auth.ProtoBaseAccount) - accountKeeper.NewAccountWithAddress(ctx, addr1) - - return TestInput{Cdc: cdc, Ctx: ctx, Ak: accountKeeper} -} - -func TestHandlerCreateAccount(t *testing.T) { - input := setupTestInput(t) - ctx, keeper := input.Ctx, input.Ak - - h := NewHandler(keeper) - - // creating the account addr2 succeeds at first - { - msg := types.NewMsgCreateAccount(addr1, addr2) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - // creating the account addr2 twice fails - { - msg := types.NewMsgCreateAccount(addr1, addr2) - _, err := h(ctx, msg) - require.Error(t, err) - } -} - -func TestHandlerEmpty(t *testing.T) { - input := setupTestInput(t) - ctx, keeper := input.Ctx, input.Ak - - h := NewHandler(keeper) - - // message test - { - msg := types.MsgEmpty{From: addr1} - _, err := h(ctx, msg) - require.NoError(t, err) - } - - // invalid message - { - msg := types.MsgEmpty{From: nil} - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing signer address").Error()) - } -} diff --git a/x/account/internal/types/codec.go b/x/account/internal/types/codec.go deleted file mode 100644 index 0ba95936d6..0000000000 --- a/x/account/internal/types/codec.go +++ /dev/null @@ -1,19 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -var ModuleCdc *codec.Codec - -func init() { - ModuleCdc = codec.New() - RegisterCodec(ModuleCdc) - ModuleCdc.Seal() -} - -// Register concrete types on codec -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgCreateAccount{}, "account/MsgCreateAccount", nil) - cdc.RegisterConcrete(MsgEmpty{}, "account/MsgEmpty", nil) -} diff --git a/x/account/internal/types/errors.go b/x/account/internal/types/errors.go deleted file mode 100644 index d77d5d8ec7..0000000000 --- a/x/account/internal/types/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package types - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -var ( - ErrAccountAlreadyExist = sdkerrors.Register(ModuleName, 1, "Target account already exists") -) diff --git a/x/account/internal/types/events.go b/x/account/internal/types/events.go deleted file mode 100644 index 387b6bb57b..0000000000 --- a/x/account/internal/types/events.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -var ( - EventCreateAccount = "create_account" - EventEmpty = "empty" - - MsgTypeCreateAccount = EventCreateAccount - MsgTypeEmpty = EventEmpty - - AttributeKeyCreateAccountFrom = "create_account_from" - AttributeKeyCreateAccountTarget = "create_account_target" - - AttributeKeyFrom = "from" - - AttributeValueCategory = ModuleName -) diff --git a/x/account/internal/types/key.go b/x/account/internal/types/key.go deleted file mode 100644 index e567b6f820..0000000000 --- a/x/account/internal/types/key.go +++ /dev/null @@ -1,7 +0,0 @@ -package types - -const ( - ModuleName = "account" - - RouterKey = ModuleName -) diff --git a/x/account/internal/types/msgs.go b/x/account/internal/types/msgs.go deleted file mode 100644 index 0d8cb7e884..0000000000 --- a/x/account/internal/types/msgs.go +++ /dev/null @@ -1,81 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -type MsgEmpty struct { - From sdk.AccAddress `json:"from"` -} - -var _ sdk.Msg = MsgEmpty{} - -// NewMsgCreateAccount - construct create account msg. -func NewMsgEmpty(from sdk.AccAddress) MsgEmpty { - return MsgEmpty{From: from} -} - -// Route Implements Msg. -func (msg MsgEmpty) Route() string { return RouterKey } - -// Type Implements Msg. -func (msg MsgEmpty) Type() string { return MsgTypeEmpty } - -// ValidateBasic Implements Msg. -func (msg MsgEmpty) ValidateBasic() error { - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing signer address") - } - return nil -} - -// GetSignBytes Implements Msg. -func (msg MsgEmpty) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners Implements Msg. -func (msg MsgEmpty) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -// MsgCreateAccount - create account transaction of the account module -type MsgCreateAccount struct { - From sdk.AccAddress `json:"from"` - Target sdk.AccAddress `json:"target"` -} - -var _ sdk.Msg = MsgCreateAccount{} - -// NewMsgCreateAccount - construct create account msg. -func NewMsgCreateAccount(fromAddr, targetAddr sdk.AccAddress) MsgCreateAccount { - return MsgCreateAccount{From: fromAddr, Target: targetAddr} -} - -// Route Implements Msg. -func (msg MsgCreateAccount) Route() string { return RouterKey } - -// Type Implements Msg. -func (msg MsgCreateAccount) Type() string { return MsgTypeCreateAccount } - -// ValidateBasic Implements Msg. -func (msg MsgCreateAccount) ValidateBasic() error { - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing signer address") - } - if msg.Target.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing target address to be created") - } - return nil -} - -// GetSignBytes Implements Msg. -func (msg MsgCreateAccount) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners Implements Msg. -func (msg MsgCreateAccount) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} diff --git a/x/account/module.go b/x/account/module.go deleted file mode 100644 index da5d5f56bb..0000000000 --- a/x/account/module.go +++ /dev/null @@ -1,100 +0,0 @@ -package account - -import ( - "encoding/json" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/gorilla/mux" - "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// app module basics object -type AppModuleBasic struct{} - -// module name -func (AppModuleBasic) Name() string { - return ModuleName -} - -// register module codec -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - -// default genesis state -func (AppModuleBasic) DefaultGenesis() json.RawMessage { return nil } - -// module validate genesis -func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil } - -// register rest routes -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { -} - -// get the root tx command of this module -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { - return nil -} - -// get the root query command of this module -func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return nil } - -// ___________________________ -// app module -type AppModule struct { - AppModuleBasic - keeper auth.AccountKeeper -} - -func NewAppModule(keeper auth.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// module name -func (AppModule) Name() string { return ModuleName } - -// register invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// module message route name -func (AppModule) Route() string { return RouterKey } - -// module handler -func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } - -// module querier route name -func (AppModule) QuerierRoute() string { return RouterKey } - -// module querier -func (am AppModule) NewQuerierHandler() sdk.Querier { - return auth.NewQuerier(am.keeper) -} - -func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - return ModuleCdc.MustMarshalJSON(nil) -} - -// module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/account/spec/01_concept.md b/x/account/spec/01_concept.md deleted file mode 100644 index bee5c528cf..0000000000 --- a/x/account/spec/01_concept.md +++ /dev/null @@ -1,2 +0,0 @@ -# Concept -TBD diff --git a/x/account/spec/02_keepers.md b/x/account/spec/02_keepers.md deleted file mode 100644 index bddc31f1af..0000000000 --- a/x/account/spec/02_keepers.md +++ /dev/null @@ -1,2 +0,0 @@ -# Keepers -TBD diff --git a/x/account/spec/03_messages.md b/x/account/spec/03_messages.md deleted file mode 100644 index bc6d8f9dd1..0000000000 --- a/x/account/spec/03_messages.md +++ /dev/null @@ -1,36 +0,0 @@ -# Messages - -## MsgEmpty - -```golang -type MsgEmpty struct { - From string `json:"name"` -} -``` - -**Do nothing** -- This message does nothing -- Signer(`From`) of this message is required -- You can pay the fee for any other message with this message - -### MsgCreateAccount - -```golang -type MsgCreateAccount struct { - From sdk.AccAddress `json:"from"` - Target sdk.AccAddress `json:"target"` -} -``` - -**Create an account** -- Signer(`FromAddress`) of this message must already been registered before -- `TargetAddress` must never been registered before - -# Syntax -| Message/Attributes | Tag | Type | -| ---- | ---- | ---- | -| Message | account/MsgCreateAccount | github.com/line/link/x/account/internal/types.MsgCreateAccount | - | Attributes | from | []uint8 | - | Attributes | target | []uint8 | -| Message | account/MsgEmpty | github.com/line/link/x/account/internal/types.MsgEmpty | - | Attributes | from | []uint8 | diff --git a/x/account/spec/04_events.md b/x/account/spec/04_events.md deleted file mode 100644 index a521bf0e42..0000000000 --- a/x/account/spec/04_events.md +++ /dev/null @@ -1,20 +0,0 @@ -# Events -**Not fully documented yet** -The account module emits the following events: - - -### MsgCreateAccount -| Type | Attribute Key | Attribute Value | -|-----------------|-----------------------|-------------------| -| message | module | account | -| message | sender | {fromAddress} | -| message | action | create_account | -| create_account | create_account_from | {fromAddress} | -| create_account | create_account_target | {targetAddress} | - -### MsgEmpty -| Type | Attribute Key | Attribute Value | -|-----------------|---------------------|---------------------| -| message | module | account | -| message | sender | {from} | -| message | action | empty | diff --git a/x/account/spec/README.md b/x/account/spec/README.md deleted file mode 100644 index 72345b3dc8..0000000000 --- a/x/account/spec/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Account module specification - - - -## Abstract - -This document specifies the account module of the Link Network. - -## Contents - -1. **[Concept](01_concept.md)** -2. **[Keepers](02_keepers.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** diff --git a/x/coin/alias.go b/x/coin/alias.go deleted file mode 100644 index 8d51bab8ab..0000000000 --- a/x/coin/alias.go +++ /dev/null @@ -1,31 +0,0 @@ -package coin - -import ( - "github.com/line/lbm-sdk/v2/x/coin/client/cli" - "github.com/line/lbm-sdk/v2/x/coin/internal/keeper" - "github.com/line/lbm-sdk/v2/x/coin/internal/types" -) - -const ( - ModuleName = types.ModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey -) - -type ( - Keeper = keeper.Keeper - - MsgSend = types.MsgSend - MsgMultiSend = types.MsgMultiSend - - Input = types.Input - Output = types.Output -) - -var ( - SendTxCmd = cli.SendTxCmd - NewMsgSend = types.NewMsgSend - NewKeeper = keeper.NewKeeper - ActionTransferTo = types.ActionTransferTo - ErrCanNotTransferToBlacklisted = types.ErrCanNotTransferToBlacklisted -) diff --git a/x/coin/client/cli/tx.go b/x/coin/client/cli/tx.go deleted file mode 100644 index c4bc067246..0000000000 --- a/x/coin/client/cli/tx.go +++ /dev/null @@ -1,64 +0,0 @@ -package cli - -import ( - "bufio" - - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *codec.Codec) *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Coin transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - txCmd.AddCommand( - SendTxCmd(cdc), - ) - return txCmd -} - -// SendTxCmd will create a send tx and sign it with the given key. -func SendTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "send [from_key_or_address] [to_address] [amount]", - Short: "Create and sign a send tx", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - to, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - // parse coins trying to be sent - coins, err := sdk.ParseCoins(args[2]) - if err != nil { - return err - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgSend(cliCtx.GetFromAddress(), to, coins) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - cmd = flags.PostCommands(cmd)[0] - - return cmd -} diff --git a/x/coin/client/rest/query.go b/x/coin/client/rest/query.go deleted file mode 100644 index 7a2bee8680..0000000000 --- a/x/coin/client/rest/query.go +++ /dev/null @@ -1,85 +0,0 @@ -package rest - -import ( - "fmt" - "net/http" - "strings" - - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" -) - -// query accountREST Handler -func QueryBalancesRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - bech32addr := vars["address"] - denom := vars["denom"] // "" if the key is not exists - - arrBech32addrs := strings.Split(bech32addr, ",") - if len(arrBech32addrs) > 1 { - addrs := make([]sdk.AccAddress, len(arrBech32addrs)) - - for i, bech32addr := range arrBech32addrs { - addr, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - addrs[i] = addr - } - - params := types.NewQueryBulkBalanceParams(addrs) - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - queryBalancesRequest(w, r, cliCtx, bz, "bulk_balances") - } else { - addr, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - params := types.NewQueryBalanceParams(addr, denom) - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - queryBalancesRequest(w, r, cliCtx, bz, "balances") - } - } -} - -func queryBalancesRequest(w http.ResponseWriter, r *http.Request, cliCtx context.CLIContext, bz []byte, path string) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/coin/%s", path), bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - // the query will return empty if there is no data for this account - if len(res) == 0 { - rest.PostProcessResponse(w, cliCtx, sdk.Coins{}) - return - } - - rest.PostProcessResponse(w, cliCtx, res) -} diff --git a/x/coin/client/rest/tx.go b/x/coin/client/rest/tx.go deleted file mode 100644 index 5d6f0bc029..0000000000 --- a/x/coin/client/rest/tx.go +++ /dev/null @@ -1,60 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/coin/accounts/{address}/transfers", SendRequestHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/coin/balances/{address}", QueryBalancesRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/coin/balances/{address}/{denom}", QueryBalancesRequestHandlerFn(cliCtx)).Methods("GET") -} - -// SendReq defines the properties of a send request's body. -type SendReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} - -// SendRequestHandlerFn - http request handler to send coins to a address. -func SendRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - bech32Addr := vars["address"] - - toAddr, err := sdk.AccAddressFromBech32(bech32Addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - var req SendReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - msg := types.NewMsgSend(fromAddr, toAddr, req.Amount) - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) - } -} diff --git a/x/coin/handler.go b/x/coin/handler.go deleted file mode 100644 index 38c74a6a29..0000000000 --- a/x/coin/handler.go +++ /dev/null @@ -1,69 +0,0 @@ -package coin - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/coin/internal/keeper" - "github.com/line/lbm-sdk/v2/x/coin/internal/types" -) - -func NewHandler(k keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - switch msg := msg.(type) { - case types.MsgSend: - return handleMsgSend(ctx, k, msg) - - case types.MsgMultiSend: - return handleMsgMultiSend(ctx, k, msg) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized coin message type: %T", msg) - } - } -} - -// Handle MsgSend. -func handleMsgSend(ctx sdk.Context, k keeper.Keeper, msg types.MsgSend) (*sdk.Result, error) { - err := k.SendCoins(ctx, msg.From, msg.To, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(types.AttributeKeySender, msg.From.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -// Handle MsgMultiSend. -func handleMsgMultiSend(ctx sdk.Context, k keeper.Keeper, msg types.MsgMultiSend) (*sdk.Result, error) { - err := k.InputOutputCoins(ctx, msg.Inputs, msg.Outputs) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - ) - - for _, in := range msg.Inputs { - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(types.AttributeKeySender, in.Address.String()), - ), - ) - } - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/coin/handler_test.go b/x/coin/handler_test.go deleted file mode 100644 index 54fbfd01f1..0000000000 --- a/x/coin/handler_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package coin - -import ( - "strings" - "testing" - - "github.com/line/lbm-sdk/v2/x/coin/internal/keeper" - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/stretchr/testify/require" -) - -func TestInvalidMsg(t *testing.T) { - h := NewHandler(keeper.Keeper{}) - - _, err := h(sdk.NewContext(nil, abci.Header{}, false, nil), sdk.NewTestMsg()) - require.Error(t, err) - require.True(t, strings.Contains(err.Error(), "unrecognized coin message type")) -} - -func TestHandlerSend(t *testing.T) { - input := keeper.SetupTestInput() - ctx, _, ak := input.Ctx, input.K, input.Ak - - h := NewHandler(input.K) - - const ( - length3Denom = "foo" - length5Denom = "f2345" - length6Denom = "f23456" - length5Denom2 = "f2346" - ) - - addr1 := sdk.AccAddress([]byte("addr1")) - addr2 := sdk.AccAddress([]byte("addr1")) - - acc := ak.NewAccountWithAddress(ctx, addr1) - - err := acc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 100), sdk.NewInt64Coin(length5Denom, 100))) - require.NoError(t, err) - ak.SetAccount(ctx, acc) - - { - coins := sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 10)) - msg := types.NewMsgSend(addr1, addr2, coins) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - { - coins := sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 10)) - msg := types.NewMsgSend(addr1, addr2, coins) - _, err := h(ctx, msg) - require.Error(t, err) - } - - { - inputs := []Input{ - types.NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 4), sdk.NewInt64Coin(length5Denom, 2))), - types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 3))), - } - - outputs := []Output{ - types.NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 7))), - types.NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length5Denom, 2))), - } - msg := types.NewMsgMultiSend(inputs, outputs) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - { - inputs := []Input{ - types.NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 4), sdk.NewInt64Coin(length5Denom, 2))), - types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 3))), - } - - outputs := []Output{ - types.NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 7))), - types.NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length5Denom2, 2))), - } - msg := types.NewMsgMultiSend(inputs, outputs) - require.Panics(t, func() { h(ctx, msg) }) // nolint - } -} - -func TestHandlerSendRestricted(t *testing.T) { - input := keeper.SetupTestInput() - ctx, _, ak := input.Ctx, input.K, input.Ak - - h := NewHandler(input.K) - - const ( - length3Denom = "foo" - length8Denom = "f2345678" - ) - - addr1 := sdk.AccAddress([]byte("addr1")) - addr2 := sdk.AccAddress([]byte("addr1")) - - acc := ak.NewAccountWithAddress(ctx, addr1) - - err := acc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 100), sdk.NewInt64Coin(length8Denom, 100))) - require.NoError(t, err) - ak.SetAccount(ctx, acc) - - { - coins := sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 10)) - msg := types.NewMsgSend(addr1, addr2, coins) - require.NoError(t, msg.ValidateBasic()) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - { - coins := sdk.NewCoins(sdk.NewInt64Coin(length8Denom, 10)) - msg := types.NewMsgSend(addr1, addr2, coins) - require.Error(t, msg.ValidateBasic()) - } - - { - inputs := []Input{ - types.NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 4), sdk.NewInt64Coin(length8Denom, 2))), - types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 3))), - } - - outputs := []Output{ - types.NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 7))), - types.NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length8Denom, 2))), - } - msg := types.NewMsgMultiSend(inputs, outputs) - _, err := h(ctx, msg) - require.Error(t, err) - } -} diff --git a/x/coin/internal/keeper/blacklist.go b/x/coin/internal/keeper/blacklist.go deleted file mode 100644 index 3c9cffc5cd..0000000000 --- a/x/coin/internal/keeper/blacklist.go +++ /dev/null @@ -1,19 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/coin/internal/types" -) - -func (keeper Keeper) BlacklistAccountAction(ctx sdk.Context, addr sdk.AccAddress, action string) { - store := ctx.KVStore(keeper.storeKey) - - // value is just a key w/o the module prefix - v := addr.String() + ":" + action - store.Set(types.BlacklistKey(addr, action), []byte(v)) -} - -func (keeper Keeper) IsBlacklistedAccountAction(ctx sdk.Context, addr sdk.AccAddress, action string) bool { - store := ctx.KVStore(keeper.storeKey) - return store.Has(types.BlacklistKey(addr, action)) -} diff --git a/x/coin/internal/keeper/hooks.go b/x/coin/internal/keeper/hooks.go deleted file mode 100644 index 8c3db2e774..0000000000 --- a/x/coin/internal/keeper/hooks.go +++ /dev/null @@ -1,11 +0,0 @@ -package keeper - -// Hooks wrapper struct for safety box keeper -type Hooks struct { - keeper Keeper -} - -// Return the wrapper struct -func (keeper Keeper) Hooks() *Hooks { - return &Hooks{keeper} -} diff --git a/x/coin/internal/keeper/keeper.go b/x/coin/internal/keeper/keeper.go deleted file mode 100644 index 1d73bb9409..0000000000 --- a/x/coin/internal/keeper/keeper.go +++ /dev/null @@ -1,104 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/coin/internal/types" -) - -type Keeper struct { - bk types.BankKeeper - storeKey sdk.StoreKey -} - -func NewKeeper(bk types.BankKeeper, storeKey sdk.StoreKey) Keeper { - return Keeper{ - bk: bk, - storeKey: storeKey, - } -} - -// SendCoins moves coins from one account to another -func (keeper Keeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error { - // reject if to address is blacklisted (safety box addresses) - if keeper.IsBlacklistedAccountAction(ctx, toAddr, types.ActionTransferTo) { - return sdkerrors.Wrapf(types.ErrCanNotTransferToBlacklisted, "Addr: %s", toAddr.String()) - } - - _, err := keeper.bk.SubtractCoins(ctx, fromAddr, amt) - if err != nil { - return err - } - - _, err = keeper.bk.AddCoins(ctx, toAddr, amt) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransfer, - sdk.NewAttribute(types.AttributeKeySender, fromAddr.String()), - sdk.NewAttribute(types.AttributeKeyRecipient, toAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amt.String()), - ), - }) - - return nil -} - -// InputOutputCoins handles a list of inputs and outputs -func (keeper Keeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) error { - if err := types.ValidateInputsOutputs(inputs, outputs); err != nil { - return err - } - - for _, in := range inputs { - _, err := keeper.bk.SubtractCoins(ctx, in.Address, in.Coins) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeTransfer, - sdk.NewAttribute(types.AttributeKeySender, in.Address.String()), - ), - ) - } - - for _, out := range outputs { - // reject if to address is blacklisted (safety box addresses) - if keeper.IsBlacklistedAccountAction(ctx, out.Address, types.ActionTransferTo) { - return sdkerrors.Wrapf(types.ErrCanNotTransferToBlacklisted, "Addr: %s", out.Address.String()) - } - - _, err := keeper.bk.AddCoins(ctx, out.Address, out.Coins) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeTransfer, - sdk.NewAttribute(types.AttributeKeyRecipient, out.Address.String()), - ), - ) - } - - return nil -} - -// GetCoins returns the coins at the addr. -func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - return keeper.bk.GetCoins(ctx, addr) -} - -// HasCoins returns whether or not an account has at least amt coins. -func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool { - return keeper.GetCoins(ctx, addr).IsAllGTE(amt) -} - -func (keeper Keeper) BlacklistedAddr(creator sdk.AccAddress) bool { - return keeper.bk.BlacklistedAddr(creator) -} diff --git a/x/coin/internal/keeper/keeper_test.go b/x/coin/internal/keeper/keeper_test.go deleted file mode 100644 index 33f34158e5..0000000000 --- a/x/coin/internal/keeper/keeper_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper(t *testing.T) { - input := SetupTestInput() - ctx := input.Ctx - - addr1 := sdk.AccAddress([]byte("addr1")) - addr2 := sdk.AccAddress([]byte("addr2")) - addr3 := sdk.AccAddress([]byte("addr3")) - acc := input.Ak.NewAccountWithAddress(ctx, addr1) - - // Test GetCoins/SetCoins - input.Ak.SetAccount(ctx, acc) - require.True(t, input.K.GetCoins(ctx, addr1).IsEqual(sdk.NewCoins())) - - acc = input.Ak.GetAccount(ctx, acc.GetAddress()) - err := acc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("fooc", 15))) - require.NoError(t, err) - input.Ak.SetAccount(ctx, acc) - require.True(t, input.K.GetCoins(ctx, addr1).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 15)))) - - // Test HasCoins - require.True(t, input.K.HasCoins(ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("fooc", 15)))) - require.True(t, input.K.HasCoins(ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("fooc", 5)))) - require.False(t, input.K.HasCoins(ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("fooc", 20)))) - require.False(t, input.K.HasCoins(ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("barc", 5)))) - - // Test SendCoins - err = input.K.SendCoins(ctx, addr1, addr2, sdk.NewCoins(sdk.NewInt64Coin("fooc", 5))) - require.NoError(t, err) - require.True(t, input.K.GetCoins(ctx, addr1).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 10)))) - require.True(t, input.K.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 5)))) - - err = input.K.SendCoins(ctx, addr1, addr2, sdk.NewCoins(sdk.NewInt64Coin("fooc", 50))) - require.Error(t, err) - require.True(t, input.K.GetCoins(ctx, addr1).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 10)))) - require.True(t, input.K.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 5)))) - - // Test InputOutputCoins - input1 := types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("fooc", 2))) - output1 := types.NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin("fooc", 2))) - err = input.K.InputOutputCoins(ctx, []types.Input{input1}, []types.Output{output1}) - require.NoError(t, err) - require.True(t, input.K.GetCoins(ctx, addr1).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 12)))) - require.True(t, input.K.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 3)))) - - acc = input.Ak.GetAccount(ctx, acc.GetAddress()) - coins := acc.GetCoins().Add(sdk.NewCoins(sdk.NewInt64Coin("barc", 15))...) - err = acc.SetCoins(coins) - require.NoError(t, err) - input.Ak.SetAccount(ctx, acc) - require.True(t, input.K.GetCoins(ctx, addr1).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 12), sdk.NewInt64Coin("barc", 15)))) - require.True(t, input.K.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("fooc", 3)))) - - inputs := []types.Input{ - types.NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin("barc", 4), sdk.NewInt64Coin("fooc", 2))), - types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("fooc", 3))), - } - - outputs := []types.Output{ - types.NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin("barc", 1))), - types.NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin("barc", 1))), - types.NewOutput(addr3, sdk.NewCoins(sdk.NewInt64Coin("barc", 2), sdk.NewInt64Coin("fooc", 5))), - } - err = input.K.InputOutputCoins(ctx, inputs, outputs) - require.NoError(t, err) - require.True(t, input.K.GetCoins(ctx, addr1).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barc", 12), sdk.NewInt64Coin("fooc", 10)))) - require.True(t, input.K.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barc", 1)))) - require.True(t, input.K.GetCoins(ctx, addr3).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barc", 2), sdk.NewInt64Coin("fooc", 5)))) -} diff --git a/x/coin/internal/keeper/querier.go b/x/coin/internal/keeper/querier.go deleted file mode 100644 index fa36a62a79..0000000000 --- a/x/coin/internal/keeper/querier.go +++ /dev/null @@ -1,81 +0,0 @@ -package keeper - -import ( - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - // query balance path - QueryBalance = "balances" - QueryBulkBalances = "bulk_balances" -) - -// NewQuerier returns a new sdk.Keeper instance. -func NewQuerier(k Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case QueryBalance: - return queryBalance(ctx, req, k) - case QueryBulkBalances: - return queryBulkBalances(ctx, req, k) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} - -// queryBalance fetch an account's balance for the supplied height. -// Height and account address are passed as first and second path components respectively. -func queryBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, error) { - var params types.QueryBalanceParams - - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - if len(params.Denom) == 0 { - bz, err := codec.MarshalJSONIndent(types.ModuleCdc, k.GetCoins(ctx, params.Address)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil - } - bz, err := codec.MarshalJSONIndent(types.ModuleCdc, k.GetCoins(ctx, params.Address).AmountOf(params.Denom)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryBulkBalances(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, error) { - var params types.QueryBulkBalancesParams - - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - if len(params.Addresses) > types.RequestGetsLimit { - return nil, sdkerrors.Wrapf(types.ErrRequestGetsLimit, "Limit: %d", types.RequestGetsLimit) - } - - res := make([]types.QueryBulkBalancesResult, len(params.Addresses)) - for idx, addr := range params.Addresses { - res[idx] = types.NewQueryBulkBalancesResult(addr, k.GetCoins(ctx, addr)) - } - - bz, err := codec.MarshalJSONIndent(types.ModuleCdc, res) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} diff --git a/x/coin/internal/keeper/querier_test.go b/x/coin/internal/keeper/querier_test.go deleted file mode 100644 index 7d5386d1fe..0000000000 --- a/x/coin/internal/keeper/querier_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package keeper - -import ( - "fmt" - "testing" - - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestBalances(t *testing.T) { - input := SetupTestInput() - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/coin/%s", QueryBalance), - Data: []byte{}, - } - - querier := NewQuerier(input.K) - - res, err := querier(input.Ctx, []string{"balances"}, req) - require.NotNil(t, err) - require.Nil(t, res) - - _, _, addr := authtypes.KeyTestPubAddr() - req.Data = input.Cdc.MustMarshalJSON(types.NewQueryBalanceParams(addr, "")) - res, err = querier(input.Ctx, []string{"balances"}, req) - require.Nil(t, err) // the account does not exist, no error returned anyway - require.NotNil(t, res) - - var coins sdk.Coins - require.NoError(t, input.Cdc.UnmarshalJSON(res, &coins)) - require.True(t, coins.IsZero()) - - acc := input.Ak.NewAccountWithAddress(input.Ctx, addr) - require.NoError(t, acc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("foo", 10)))) - input.Ak.SetAccount(input.Ctx, acc) - res, err = querier(input.Ctx, []string{"balances"}, req) - require.Nil(t, err) - require.NotNil(t, res) - require.NoError(t, input.Cdc.UnmarshalJSON(res, &coins)) - require.True(t, coins.AmountOf("foo").Equal(sdk.NewInt(10))) - - // Query with denomination - var amount sdk.Int - req.Data = input.Cdc.MustMarshalJSON(types.NewQueryBalanceParams(addr, "foo")) - res, err = querier(input.Ctx, []string{"balances"}, req) - require.Nil(t, err) // the account does not exist, no error returned anyway - require.NotNil(t, res) - - require.NoError(t, input.Cdc.UnmarshalJSON(res, &amount)) - require.True(t, amount.Equal(sdk.NewInt(10))) -} - -func TestQuerierRouteNotFound(t *testing.T) { - input := SetupTestInput() - req := abci.RequestQuery{ - Path: "custom/coin/notfound", - Data: []byte{}, - } - - querier := NewQuerier(input.K) - _, err := querier(input.Ctx, []string{"notfound"}, req) - require.Error(t, err) -} - -func TestBulkBalances(t *testing.T) { - input := SetupTestInput() - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/coin/%s", QueryBulkBalances), - Data: []byte{}, - } - - querier := NewQuerier(input.K) - - res, err := querier(input.Ctx, []string{"bulk_balances"}, req) - require.NotNil(t, err) - require.Nil(t, res) - - addrs := make([]sdk.AccAddress, 0, 101) - _, _, addr := authtypes.KeyTestPubAddr() - addrs = append(addrs, addr) - req.Data = input.Cdc.MustMarshalJSON(types.NewQueryBulkBalanceParams(addrs)) - res, err = querier(input.Ctx, []string{"bulk_balances"}, req) - require.Nil(t, err) - require.NotNil(t, res) - - for i := 0; i < 99; i++ { - _, _, addr = authtypes.KeyTestPubAddr() - addrs = append(addrs, addr) - } - - req.Data = input.Cdc.MustMarshalJSON(types.NewQueryBulkBalanceParams(addrs)) - res, err = querier(input.Ctx, []string{"bulk_balances"}, req) - require.Nil(t, err) - require.NotNil(t, res) - - _, _, addr = authtypes.KeyTestPubAddr() - addrs = append(addrs, addr) - - req.Data = input.Cdc.MustMarshalJSON(types.NewQueryBulkBalanceParams(addrs)) - res, err = querier(input.Ctx, []string{"bulk_balances"}, req) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrRequestGetsLimit, "Limit: %d", types.RequestGetsLimit).Error()) - require.Nil(t, res) -} diff --git a/x/coin/internal/keeper/test_common.go b/x/coin/internal/keeper/test_common.go deleted file mode 100644 index e09f7b7a44..0000000000 --- a/x/coin/internal/keeper/test_common.go +++ /dev/null @@ -1,67 +0,0 @@ -package keeper - -// DONTCOVER - -import ( - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/params" -) - -type TestInput struct { - Cdc *codec.Codec - Ctx sdk.Context - K Keeper - Ak auth.AccountKeeper - Pk params.Keeper -} - -func SetupTestInput() TestInput { - db := dbm.NewMemDB() - - cdc := codec.New() - auth.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - - authCapKey := sdk.NewKVStoreKey("authCapKey") - keyParams := sdk.NewKVStoreKey("params") - tkeyParams := sdk.NewTransientStoreKey("transient_params") - keyBank := sdk.NewKVStoreKey(types.StoreKey) - - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(authCapKey, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyBank, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) - - if err := ms.LoadLatestVersion(); err != nil { - panic(err) - } - - blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[sdk.AccAddress([]byte("moduleAcc")).String()] = true - - pk := params.NewKeeper(cdc, keyParams, tkeyParams) - - ak := auth.NewAccountKeeper( - cdc, authCapKey, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount, - ) - ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) - - ak.SetParams(ctx, auth.DefaultParams()) - - bankKeeper := bank.NewBaseKeeper(ak, pk.Subspace(bank.DefaultParamspace), blacklistedAddrs) - bankKeeper.SetSendEnabled(ctx, true) - - keeper := NewKeeper(bankKeeper, keyBank) - - return TestInput{Cdc: cdc, Ctx: ctx, K: keeper, Ak: ak, Pk: pk} -} diff --git a/x/coin/internal/types/codec.go b/x/coin/internal/types/codec.go deleted file mode 100644 index 172e3ebcff..0000000000 --- a/x/coin/internal/types/codec.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -var ModuleCdc *codec.Codec - -func init() { - ModuleCdc = codec.New() - RegisterCodec(ModuleCdc) - ModuleCdc.Seal() -} - -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgSend{}, "coin/MsgSend", nil) - cdc.RegisterConcrete(MsgMultiSend{}, "coin/MsgMultiSend", nil) -} diff --git a/x/coin/internal/types/errors.go b/x/coin/internal/types/errors.go deleted file mode 100644 index 95259f82cd..0000000000 --- a/x/coin/internal/types/errors.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const Codespace = ModuleName - -var ( - ErrNoInputs = sdkerrors.Register(Codespace, 1, "no inputs to send transaction") - ErrNoOutputs = sdkerrors.Register(Codespace, 2, "no outputs to send transaction") - ErrInputOutputMismatch = sdkerrors.Register(Codespace, 3, "sum inputs != sum outputs") - ErrSendDisabled = sdkerrors.Register(Codespace, 4, "send transactions are disabled") - ErrCanNotTransferToBlacklisted = sdkerrors.Register(Codespace, 5, "Cannot transfer to safety box addresses") - ErrRequestGetsLimit = sdkerrors.Register(Codespace, 6, "the gets should be limited") - ErrInvalidDenom = sdkerrors.Register(Codespace, 7, "invalid denom") -) diff --git a/x/coin/internal/types/events.go b/x/coin/internal/types/events.go deleted file mode 100644 index 5e65f0ed7f..0000000000 --- a/x/coin/internal/types/events.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -// Coin module event types -var ( - EventTypeTransfer = "transfer" - - AttributeKeyRecipient = "recipient" - AttributeKeySender = "sender" - - AttributeValueCategory = ModuleName -) diff --git a/x/coin/internal/types/expected_keepers.go b/x/coin/internal/types/expected_keepers.go deleted file mode 100644 index 2345e5bc38..0000000000 --- a/x/coin/internal/types/expected_keepers.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/exported" -) - -// AccountKeeper defines the account contract that must be fulfilled when -type AccountKeeper interface { - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) exported.Account - - GetAccount(ctx sdk.Context, addr sdk.AccAddress) exported.Account - GetAllAccounts(ctx sdk.Context) []exported.Account - SetAccount(ctx sdk.Context, acc exported.Account) - - IterateAccounts(ctx sdk.Context, process func(exported.Account) bool) -} - -// BankKeeper defines the expected bank keeper (noalias) -type BankKeeper interface { - GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool - SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error) - AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error) - BlacklistedAddr(creator sdk.AccAddress) bool -} diff --git a/x/coin/internal/types/key.go b/x/coin/internal/types/key.go deleted file mode 100644 index 9b88dcd0ce..0000000000 --- a/x/coin/internal/types/key.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -const ( - // module name - ModuleName = "coin" - StoreKey = ModuleName - - ActionTransferTo = "transferTo" -) - -var ( - BlacklistKeyPrefix = []byte{0x00} -) - -func BlacklistKey(addr sdk.AccAddress, action string) []byte { - key := append(BlacklistKeyPrefix, addr...) - key = append(key, []byte(":"+action)...) - return key -} diff --git a/x/coin/internal/types/msgs.go b/x/coin/internal/types/msgs.go deleted file mode 100644 index 643bde96d6..0000000000 --- a/x/coin/internal/types/msgs.go +++ /dev/null @@ -1,202 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const RouterKey = ModuleName - -// MsgSend - high level transaction of the coin module -type MsgSend struct { - From sdk.AccAddress `json:"from"` - To sdk.AccAddress `json:"to"` - Amount sdk.Coins `json:"amount"` -} - -var _ sdk.Msg = MsgSend{} - -// NewMsgSend - construct arbitrary multi-in, multi-out send msg. -func NewMsgSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) MsgSend { - return MsgSend{From: fromAddr, To: toAddr, Amount: amount} -} - -// Route Implements Msg. -func (msg MsgSend) Route() string { return RouterKey } - -// Type Implements Msg. -func (msg MsgSend) Type() string { return "send" } - -// ValidateBasic Implements Msg. -func (msg MsgSend) ValidateBasic() error { - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing sender address") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing recipient address") - } - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - if !msg.Amount.IsAllPositive() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - if err := validateDenomination(msg.Amount); err != nil { - return err - } - return nil -} - -// GetSignBytes Implements Msg. -func (msg MsgSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners Implements Msg. -func (msg MsgSend) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -// MsgMultiSend - high level transaction of the coin module -type MsgMultiSend struct { - Inputs []Input `json:"inputs" yaml:"inputs"` - Outputs []Output `json:"outputs" yaml:"outputs"` -} - -var _ sdk.Msg = MsgMultiSend{} - -// NewMsgMultiSend - construct arbitrary multi-in, multi-out send msg. -func NewMsgMultiSend(in []Input, out []Output) MsgMultiSend { - return MsgMultiSend{Inputs: in, Outputs: out} -} - -// Route Implements Msg -func (msg MsgMultiSend) Route() string { return RouterKey } - -// Type Implements Msg -func (msg MsgMultiSend) Type() string { return "multisend" } - -// ValidateBasic Implements Msg. -func (msg MsgMultiSend) ValidateBasic() error { - // this just makes sure all the inputs and outputs are properly formatted, - // not that they actually have the money inside - if len(msg.Inputs) == 0 { - return ErrNoInputs - } - if len(msg.Outputs) == 0 { - return ErrNoOutputs - } - - return ValidateInputsOutputs(msg.Inputs, msg.Outputs) -} - -// GetSignBytes Implements Msg. -func (msg MsgMultiSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners Implements Msg. -func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { - addrs := make([]sdk.AccAddress, len(msg.Inputs)) - for i, in := range msg.Inputs { - addrs[i] = in.Address - } - return addrs -} - -// Input models transaction input -type Input struct { - Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins" yaml:"coins"` -} - -// ValidateBasic - validate transaction input -func (in Input) ValidateBasic() error { - if len(in.Address) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "input address missing") - } - if !in.Coins.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) - } - if !in.Coins.IsAllPositive() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) - } - if err := validateDenomination(in.Coins); err != nil { - return err - } - return nil -} - -// NewInput - create a transaction input, used with MsgMultiSend -func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { - return Input{ - Address: addr, - Coins: coins, - } -} - -// Output models transaction outputs -type Output struct { - Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins" yaml:"coins"` -} - -// ValidateBasic - validate transaction output -func (out Output) ValidateBasic() error { - if len(out.Address) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "output address missing") - } - if !out.Coins.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) - } - if !out.Coins.IsAllPositive() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) - } - if err := validateDenomination(out.Coins); err != nil { - return err - } - return nil -} - -// NewOutput - create a transaction output, used with MsgMultiSend -func NewOutput(addr sdk.AccAddress, coins sdk.Coins) Output { - return Output{ - Address: addr, - Coins: coins, - } -} - -// ValidateInputsOutputs validates that each respective input and output is -// valid and that the sum of inputs is equal to the sum of outputs. -func ValidateInputsOutputs(inputs []Input, outputs []Output) error { - var totalIn, totalOut sdk.Coins - - for _, in := range inputs { - if err := in.ValidateBasic(); err != nil { - return err - } - totalIn = totalIn.Add(in.Coins...) - } - - for _, out := range outputs { - if err := out.ValidateBasic(); err != nil { - return err - } - totalOut = totalOut.Add(out.Coins...) - } - - // make sure inputs and outputs match - if !totalIn.IsEqual(totalOut) { - return ErrInputOutputMismatch - } - - return nil -} -func validateDenomination(coins sdk.Coins) error { - for _, coin := range coins { - if err := ValidateSymbolReserved(coin.Denom); err != nil { - return sdkerrors.Wrapf(ErrInvalidDenom, "invalid denom [%s] send message supports 3~5 length denom only", coin.Denom) - } - } - return nil -} diff --git a/x/coin/internal/types/msgs_test.go b/x/coin/internal/types/msgs_test.go deleted file mode 100644 index 816df651c1..0000000000 --- a/x/coin/internal/types/msgs_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestMsgs(t *testing.T) { - const ( - length3Denom = "foo" - length5Denom = "f2345" - length6Denom = "f23456" - length8Denom = "f2345678" - ) - - addr1 := sdk.AccAddress([]byte("addr1")) - addr2 := sdk.AccAddress([]byte("addr1")) - - { - coins := sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 10)) - msg := NewMsgSend(addr1, addr2, coins) - require.NoError(t, msg.ValidateBasic()) - require.Equal(t, addr1.String(), msg.GetSigners()[0].String()) - } - { - coins := sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 10)) - msg := NewMsgSend(addr1, nil, coins) - require.Error(t, msg.ValidateBasic()) - } - { - coins := sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 10)) - msg := NewMsgSend(addr1, addr2, coins) - require.Error(t, msg.ValidateBasic()) - } - - { - inputs := []Input{ - NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 4), sdk.NewInt64Coin(length5Denom, 2))), - NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 3))), - } - - outputs := []Output{ - NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 7))), - NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length5Denom, 2))), - } - msg := NewMsgMultiSend(inputs, outputs) - require.NoError(t, msg.ValidateBasic()) - require.Equal(t, addr1.String(), msg.GetSigners()[0].String()) - require.Equal(t, addr2.String(), msg.GetSigners()[1].String()) - } - // InputOutputMismatch - { - inputs := []Input{ - NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 4), sdk.NewInt64Coin(length5Denom, 2))), - NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 3))), - } - - outputs := []Output{ - NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length3Denom, 7))), - NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length5Denom, 1))), - } - msg := NewMsgMultiSend(inputs, outputs) - require.Error(t, msg.ValidateBasic()) - } - // Validate Denom - { - inputs := []Input{ - NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 4), sdk.NewInt64Coin(length8Denom, 2))), - NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 3))), - } - - outputs := []Output{ - NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 7))), - NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length8Denom, 2))), - } - msg := NewMsgMultiSend(inputs, outputs) - require.Error(t, msg.ValidateBasic()) - } - // NoInput or NoOutput - { - inputs := []Input{ - NewInput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 4), sdk.NewInt64Coin(length8Denom, 2))), - NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 3))), - } - - outputs := []Output{ - NewOutput(addr1, sdk.NewCoins(sdk.NewInt64Coin(length6Denom, 7))), - NewOutput(addr2, sdk.NewCoins(sdk.NewInt64Coin(length8Denom, 2))), - } - msg := NewMsgMultiSend([]Input{}, outputs) - require.Error(t, msg.ValidateBasic()) - msg = NewMsgMultiSend(inputs, []Output{}) - require.Error(t, msg.ValidateBasic()) - } -} diff --git a/x/coin/internal/types/querier.go b/x/coin/internal/types/querier.go deleted file mode 100644 index 2e33b895a0..0000000000 --- a/x/coin/internal/types/querier.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const RequestGetsLimit = 100 - -// QueryBalanceOfParams defines the params for querying an account balance. -type QueryBalanceParams struct { - Address sdk.AccAddress - Denom string -} - -type QueryBulkBalancesParams struct { - Addresses []sdk.AccAddress `json:"addresses"` -} - -type QueryBulkBalancesResult struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -// NewQueryBalanceOfParams creates a new instance of QueryBalanceParams. -func NewQueryBalanceParams(addr sdk.AccAddress, denom string) QueryBalanceParams { - return QueryBalanceParams{Address: addr, Denom: denom} -} - -func NewQueryBulkBalanceParams(addrs []sdk.AccAddress) QueryBulkBalancesParams { - return QueryBulkBalancesParams{Addresses: addrs} -} - -func NewQueryBulkBalancesResult(address sdk.AccAddress, coins sdk.Coins) QueryBulkBalancesResult { - return QueryBulkBalancesResult{Address: address, Coins: coins} -} diff --git a/x/coin/internal/types/symbol.go b/x/coin/internal/types/symbol.go deleted file mode 100644 index 961e275413..0000000000 --- a/x/coin/internal/types/symbol.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - "fmt" - "regexp" -) - -const ( - /* #nosec */ - reSymbolStringReserved = `[a-z][a-z0-9]{2,4}` -) - -var ( - reSymbolReserved = regexp.MustCompile(fmt.Sprintf(`^%s$`, reSymbolStringReserved)) -) - -func ValidateReg(symbol string, reg *regexp.Regexp) error { - if !reg.MatchString(symbol) { - return fmt.Errorf("symbol [%s] mismatched to [%s]", symbol, reg.String()) - } - return nil -} - -func ValidateSymbolReserved(symbol string) error { return ValidateReg(symbol, reSymbolReserved) } diff --git a/x/coin/module.go b/x/coin/module.go deleted file mode 100644 index ee8c62c2a3..0000000000 --- a/x/coin/module.go +++ /dev/null @@ -1,106 +0,0 @@ -package coin - -import ( - "encoding/json" - - "github.com/line/lbm-sdk/v2/x/coin/client/cli" - "github.com/line/lbm-sdk/v2/x/coin/client/rest" - "github.com/line/lbm-sdk/v2/x/coin/internal/keeper" - "github.com/line/lbm-sdk/v2/x/coin/internal/types" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// app module basics object -type AppModuleBasic struct{} - -// module name -func (AppModuleBasic) Name() string { return types.ModuleName } - -// register module codec -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { types.RegisterCodec(cdc) } - -// default genesis state -func (AppModuleBasic) DefaultGenesis() json.RawMessage { return nil } - -// module validate genesis -func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil } - -// register rest routes -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr) -} - -// get the root tx command of this module -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetTxCmd(cdc) -} - -// get the root query command of this module -func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } - -// ___________________________ -// app module -type AppModule struct { - AppModuleBasic - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// module name -func (AppModule) Name() string { return types.ModuleName } - -// register invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// module message route name -func (AppModule) Route() string { return types.RouterKey } - -// module handler -func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } - -// module querier route name -func (AppModule) QuerierRoute() string { return types.RouterKey } - -// module querier -func (am AppModule) NewQuerierHandler() sdk.Querier { - return keeper.NewQuerier(am.keeper) -} - -// module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - // TODO: fill the init - return []abci.ValidatorUpdate{} -} - -// module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - // TODO: fill the export - return types.ModuleCdc.MustMarshalJSON(nil) -} - -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/coin/spec/01_state.md b/x/coin/spec/01_state.md deleted file mode 100644 index 639c27fc05..0000000000 --- a/x/coin/spec/01_state.md +++ /dev/null @@ -1,3 +0,0 @@ -# State -TBD - diff --git a/x/coin/spec/02_keepers.md b/x/coin/spec/02_keepers.md deleted file mode 100644 index 3ec8b7c59c..0000000000 --- a/x/coin/spec/02_keepers.md +++ /dev/null @@ -1,3 +0,0 @@ -# Keepers -TBD - diff --git a/x/coin/spec/03_messages.md b/x/coin/spec/03_messages.md deleted file mode 100644 index 07bdbb0833..0000000000 --- a/x/coin/spec/03_messages.md +++ /dev/null @@ -1,57 +0,0 @@ -# Messages - -## MsgSend - -```golang -type MsgSend struct { - From sdk.AccAddress `json:"from"` - To sdk.AccAddress `json:"to"` - Amount sdk.Coins `json:"amount"` -} -``` - -## MsgMultiSend -```golang -type MsgMultiSend struct { - Inputs []Input `json:"inputs"` - Outputs []Output `json:"outputs"` -} -``` - -```golang -type Input struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} -``` -```golang -type Output struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} -``` - -``` -handleMsgSend(msg MsgSend) - inputSum = 0 - for input in inputs - inputSum += input.Amount - outputSum = 0 - for output in outputs - outputSum += output.Amount - if inputSum != outputSum: - fail with "input/output amount mismatch" - - return inputOutputCoins(msg.Inputs, msg.Outputs) -``` - -# Syntax -| Message/Attributes | Tag | Type | -| ---- | ---- | ---- | -| Message | coin/MsgSend | github.com/line/link/x/coin/internal/types.MsgSend | - | Attributes | from | []uint8 | - | Attributes | to | []uint8 | - | Attributes | amount | []github.com/cosmos/cosmos-sdk/types.Coin | -| Message | coin/MsgMultiSend | github.com/line/link/x/coin/internal/types.MsgMultiSend | - | Attributes | inputs | []github.com/line/link/x/coin/internal/types.Input | - | Attributes | outputs | []github.com/line/link/x/coin/internal/types.Output | \ No newline at end of file diff --git a/x/coin/spec/04_events.md b/x/coin/spec/04_events.md deleted file mode 100644 index dd0285544b..0000000000 --- a/x/coin/spec/04_events.md +++ /dev/null @@ -1,24 +0,0 @@ -# Events - -The coin module emits the following events: - -## Handlers - -### MsgSend - -| Type | Attribute Key | Attribute Value | -|----------|---------------|--------------------| -| message | module | coin | -| message | action | send | -| message | sender | {senderAddress} | -| transfer | recipient | {recipientAddress} | -| transfer | amount | {amount} | - -### MsgMultiSend - -| Type | Attribute Key | Attribute Value | -|----------|---------------|--------------------| -| message | module | coin | -| message | action | multisend | -| message | sender | {senderAddress} | -| transfer | recipient | {recipientAddress} | diff --git a/x/coin/spec/README.md b/x/coin/spec/README.md deleted file mode 100644 index dca7df25be..0000000000 --- a/x/coin/spec/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Coin module specification - -## Abstract - -This document specifies the coin module of the LINK - -## Contents - -1. **[State](01_state.md)** -2. **[Keepers](02_keepers.md)** - - [Common Types](02_keepers.md#common-types) - - [BaseKeeper](02_keepers.md#basekeeper) - - [SendKeeper](02_keepers.md#sendkeeper) - - [ViewKeeper](02_keepers.md#viewkeeper) -3. **[Messages](03_messages.md)** - - [MsgSend](03_messages.md#msgsend) -4. **[Events](04_events.md)** - - [Handlers](04_events.md#handlers) diff --git a/x/collection/alias.go b/x/collection/alias.go deleted file mode 100644 index 9fc88067ab..0000000000 --- a/x/collection/alias.go +++ /dev/null @@ -1,107 +0,0 @@ -package collection - -import ( - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/querier" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -const ( - ModuleName = types.ModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - DefaultParamspace = types.DefaultParamspace - EncodeRouterKey = types.EncodeRouterKey -) - -type ( - Token = types.Token - Tokens = types.Tokens - Coins = types.Coins - FT = types.FT - NFT = types.NFT - - TokenType = types.TokenType - - Collection = types.BaseCollection - - MsgCreateCollection = types.MsgCreateCollection - MsgIssueFT = types.MsgIssueFT - MsgIssueNFT = types.MsgIssueNFT - MsgMintNFT = types.MsgMintNFT - MsgBurnNFT = types.MsgBurnNFT - MsgBurnNFTFrom = types.MsgBurnNFTFrom - MsgMintFT = types.MsgMintFT - MsgBurnFT = types.MsgBurnFT - MsgBurnFTFrom = types.MsgBurnFTFrom - - MsgGrantPermission = types.MsgGrantPermission - MsgRevokePermission = types.MsgRevokePermission - - MsgModify = types.MsgModify - - MsgTransferFT = types.MsgTransferFT - MsgTransferNFT = types.MsgTransferNFT - - MsgTransferFTFrom = types.MsgTransferFTFrom - MsgTransferNFTFrom = types.MsgTransferNFTFrom - - MsgAttach = types.MsgAttach - MsgDetach = types.MsgDetach - - MsgAttachFrom = types.MsgAttachFrom - MsgDetachFrom = types.MsgDetachFrom - - MsgApproveCollection = types.MsgApprove - MsgDisapproveCollection = types.MsgDisapprove - - Permissions = types.Permissions - Permission = types.Permission - - MintNFTParam = types.MintNFTParam - - Keeper = keeper.Keeper -) - -var ( - NewMsgCreateCollection = types.NewMsgCreateCollection - NewMsgIssueFT = types.NewMsgIssueFT - NewMsgIssueNFT = types.NewMsgIssueNFT - NewMsgMintNFT = types.NewMsgMintNFT - NewMsgBurnNFT = types.NewMsgBurnNFT - NewMsgBurnNFTFrom = types.NewMsgBurnNFTFrom - NewMsgBurnFTFrom = types.NewMsgBurnFTFrom - NewMsgMintFT = types.NewMsgMintFT - NewMsgBurnFT = types.NewMsgBurnFT - NewMsgGrantPermission = types.NewMsgGrantPermission - NewMsgRevokePermission = types.NewMsgRevokePermission - NewMsgModify = types.NewMsgModify - NewChangesWithMap = types.NewChangesWithMap - NewMsgTransferFT = types.NewMsgTransferFT - NewMsgTransferNFT = types.NewMsgTransferNFT - NewMsgTransferFTFrom = types.NewMsgTransferFTFrom - NewMsgTransferNFTFrom = types.NewMsgTransferNFTFrom - NewMsgAttach = types.NewMsgAttach - NewMsgDetach = types.NewMsgDetach - NewMsgAttachFrom = types.NewMsgAttachFrom - NewMsgDetachFrom = types.NewMsgDetachFrom - NewMsgApprove = types.NewMsgApprove - NewMsgDisapprove = types.NewMsgDisapprove - NewMintNFTParam = types.NewMintNFTParam - NewCoin = types.NewCoin - NewPermissions = types.NewPermissions - - NewMintPermission = types.NewMintPermission - NewBurnPermission = types.NewBurnPermission - NewIssuePermission = types.NewIssuePermission - NewModifyPermission = types.NewModifyPermission - - ModuleCdc = types.ModuleCdc - RegisterCodec = types.RegisterCodec - - NewKeeper = keeper.NewKeeper - NewQuerier = querier.NewQuerier - - // NewMsgEncodeHandler = keeper.NewMsgEncodeHandler - // NewQueryEncoder = querier.NewQueryEncoder -) diff --git a/x/collection/client/cli/query.go b/x/collection/client/cli/query.go deleted file mode 100644 index 1b2877c4c0..0000000000 --- a/x/collection/client/cli/query.go +++ /dev/null @@ -1,465 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/line/lbm-sdk/v2/x/collection/client/internal/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -func GetQueryCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the collection module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - GetBalanceCmd(cdc), - GetBalancesCmd(cdc), - GetTokenCmd(cdc), - GetTokensCmd(cdc), - GetTokenTypeCmd(cdc), - GetTokenTypesCmd(cdc), - GetCollectionCmd(cdc), - GetTokenTotalCmd(cdc), - GetTokenCountCmd(cdc), - GetPermsCmd(cdc), - GetParentCmd(cdc), - GetRootCmd(cdc), - GetChildrenCmd(cdc), - GetApproversCmd(cdc), - GetIsApprovedCmd(cdc), - ) - - return cmd -} - -func GetBalanceCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "balance [contract_id] [token_id] [addr]", - Short: "Query balance of the account", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - tokenID := args[1] - addr, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - supply, height, err := retriever.GetAccountBalance(cliCtx, contractID, tokenID, addr) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(supply) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetBalancesCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "balances [contract_id] [addr]", - Short: "Query balances of the account for each token_id", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - addr, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - coins, height, err := retriever.GetAccountBalances(cliCtx, contractID, addr) - if err != nil { - return err - } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(coins) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetCollectionCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "collection [contract_id]", - Short: "Query collection", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - collection, height, err := retriever.GetCollection(cliCtx, contractID) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(collection) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetTokenTypeCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "tokentype [contract_id] [token-type]", - Short: "Query collection token-type with collection contract_id and token-type", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - tokenTypeID := args[1] - tokenType, height, err := retriever.GetTokenType(cliCtx, contractID, tokenTypeID) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - - return cliCtx.PrintOutput(tokenType) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetTokenTypesCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "tokentypes [contract_id]", - Short: "Query all collection token-types with collection contract_id", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - - tokenTypes, height, err := retriever.GetTokenTypes(cliCtx, contractID) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(tokenTypes) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetTokenCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "token [contract_id] [token_id]", - Short: "Query collection token with collection contractID and token's token_id", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - tokenID := args[1] - token, height, err := retriever.GetToken(cliCtx, contractID, tokenID) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - - return cliCtx.PrintOutput(token) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetTokensCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "tokens [contract_id]", - Short: "Query all collection tokens with collection contractID", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - var tokens types.Tokens - var height int64 - var err error - - tokenType := viper.GetString(flagTokenType) - if len(tokenType) > 0 { - tokens, height, err = retriever.GetTokensWithTokenType(cliCtx, contractID, tokenType) - } else { - tokens, height, err = retriever.GetTokens(cliCtx, contractID) - } - - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(tokens) - }, - } - cmd.Flags().String(flagTokenType, DefaultTokenType, "get tokens belong to the token-type") - - return flags.GetCommands(cmd)[0] -} - -func GetTokenTotalCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "total [supply|mint|burn] [contract_id] [token_id]", - Short: "Query supply/mint/burn of collection token with contract-id and tokens's token_id.", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - target := args[0] - contractID := args[1] - tokenID := args[2] - - supply, height, err := retriever.GetTotal(cliCtx, contractID, tokenID, target) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(supply) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetTokenCountCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "count [total|mint|burn] [contract_id] [token_type]", - Short: "Query count of collection tokens with collection contractID and the type_type.", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - target := args[0] - switch target { - case "total": - target = types.QueryNFTCount - case "mint": - target = types.QueryNFTMint - case "burn": - target = types.QueryNFTBurn - default: - return fmt.Errorf("argument is not total, mint, or burn %s", target) - } - - contractID := args[1] - tokenType := args[2] - - supply, height, err := retriever.GetCollectionNFTCount(cliCtx, contractID, tokenType, target) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(supply) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetPermsCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "perm [addr] [contract_id]", - Short: "Get Permission of the Account", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - contractID := args[1] - pms, height, err := retriever.GetAccountPermission(cliCtx, contractID, addr) - if err != nil { - return err - } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(pms) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetParentCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "parent [contract_id] [token-id]", - Short: "Query parent token with contractID and token-id", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - tokenGetter := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - tokenID := args[1] - - if err := tokenGetter.EnsureExists(cliCtx, contractID, tokenID); err != nil { - return err - } - - token, _, err := tokenGetter.GetParent(cliCtx, contractID, tokenID) - if err != nil { - return err - } - - return cliCtx.PrintOutput(token) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetRootCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "root [contract_id] [token-id]", - Short: "Query root token with contractID and token-id", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - tokenGetter := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - tokenID := args[1] - - if err := tokenGetter.EnsureExists(cliCtx, contractID, tokenID); err != nil { - return err - } - - token, _, err := tokenGetter.GetRoot(cliCtx, contractID, tokenID) - if err != nil { - return err - } - - return cliCtx.PrintOutput(token) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetChildrenCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "children [contract_id] [token-id]", - Short: "Query children tokens with contractID and token-id", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - tokenGetter := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - tokenID := args[1] - - if err := tokenGetter.EnsureExists(cliCtx, contractID, tokenID); err != nil { - return err - } - - tokens, _, err := tokenGetter.GetChildren(cliCtx, contractID, tokenID) - if err != nil { - return err - } - - return cliCtx.PrintOutput(tokens) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetApproversCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "approvers [contract_id] [proxy]", - Short: "Query approvers by the proxy", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - - proxy, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - approvers, height, err := retriever.GetApprovers(cliCtx, contractID, proxy) - if err != nil { - return err - } - - return cliCtx.WithHeight(height).PrintOutput(approvers) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetIsApprovedCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "approved [contract_id] [proxy] [approver]", - Short: "Query whether a proxy is approved by approver on a collection", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - - proxy, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - approver, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - approved, height, err := retriever.IsApproved(cliCtx, contractID, proxy, approver) - if err != nil { - return err - } - - return cliCtx.WithHeight(height).PrintOutput(approved) - }, - } - - return flags.GetCommands(cmd)[0] -} diff --git a/x/collection/client/cli/tx.go b/x/collection/client/cli/tx.go deleted file mode 100644 index 659a42eb63..0000000000 --- a/x/collection/client/cli/tx.go +++ /dev/null @@ -1,706 +0,0 @@ -package cli - -import ( - "bufio" - "errors" - "strings" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" -) - -var ( - flagTotalSupply = "total-supply" - flagDecimals = "decimals" - flagMintable = "mintable" - flagTokenType = "token-type" - flagTokenIndex = "token-index" -) - -const ( - DefaultDecimals = 8 - DefaultTotalSupply = 1 - DefaultTokenType = "" - DefaultTokenIndex = "" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *codec.Codec) *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Token transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - txCmd.AddCommand( - CreateCollectionTxCmd(cdc), - IssueFTTxCmd(cdc), - IssueNFTTxCmd(cdc), - MintFTTxCmd(cdc), - MintNFTTxCmd(cdc), - BurnFTTxCmd(cdc), - BurnFTFromTxCmd(cdc), - BurnNFTTxCmd(cdc), - BurnNFTFromTxCmd(cdc), - TransferFTTxCmd(cdc), - TransferFTFromTxCmd(cdc), - TransferNFTTxCmd(cdc), - TransferNFTFromTxCmd(cdc), - AttachTxCmd(cdc), - AttachFromTxCmd(cdc), - DetachTxCmd(cdc), - DetachFromTxCmd(cdc), - ApproveCollectionTxCmd(cdc), - DisapproveCollectionTxCmd(cdc), - GrantPermTxCmd(cdc), - RevokePermTxCmd(cdc), - ModifyCmd(cdc), - ) - return txCmd -} - -func ModifyCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "modify [owner_address] [contract_id] [field] [new_value]", - Short: "Create and sign a modify tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - field := args[2] - newValue := args[3] - tokenType := viper.GetString(flagTokenType) - tokenIndex := viper.GetString(flagTokenIndex) - - msg := types.NewMsgModify(cliCtx.FromAddress, contractID, tokenType, tokenIndex, - types.NewChanges(types.NewChange(field, newValue))) - err := msg.ValidateBasic() - if err != nil { - return err - } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - cmd.Flags().String(flagTokenType, DefaultTokenType, "token type") - cmd.Flags().String(flagTokenIndex, DefaultTokenIndex, "token index") - - return flags.PostCommands(cmd)[0] -} - -func CreateCollectionTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "create [from_key_or_address] [name] [meta] [base_img_uri]", - Short: "Create and sign an create collection tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - owner := cliCtx.FromAddress - name := args[1] - meta := args[2] - baseImgURI := args[3] - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgCreateCollection(owner, name, meta, baseImgURI) - if err := msg.ValidateBasic(); err != nil { - return err - } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func IssueNFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "issue-nft [from_key_or_address] [contract_id] [name] [meta]", - Short: "Create and sign an issue-nft tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - to := cliCtx.FromAddress - contractID := args[1] - name := args[2] - meta := args[3] - - msg := types.NewMsgIssueNFT(to, contractID, name, meta) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - return flags.PostCommands(cmd)[0] -} - -func IssueFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "issue-ft [from_key_or_address] [contract_id] [to] [name] [meta]", - Short: "Create and sign an issue-ft tx", - Long: ` -[Fungible Token] -linkcli tx collection issue-ft [from_key_or_address] [contract_id] [to] [name] [meta] ---decimals=[decimals] ---mintable=[mintable] ---total-supply=[initial amount of the token] -`, - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - owner := cliCtx.FromAddress - contractID := args[1] - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - name := args[3] - meta := args[4] - supply := viper.GetInt64(flagTotalSupply) - decimals := viper.GetInt64(flagDecimals) - mintable := viper.GetBool(flagMintable) - - if decimals < 0 || decimals > 18 { - return errors.New("invalid decimals. 0 <= decimals <= 18") - } - - msg := types.NewMsgIssueFT(owner, to, contractID, name, meta, sdk.NewInt(supply), sdk.NewInt(decimals), mintable) - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - cmd.Flags().Int64(flagTotalSupply, DefaultTotalSupply, "total supply") - cmd.Flags().Int64(flagDecimals, DefaultDecimals, "set decimals") - cmd.Flags().Bool(flagMintable, false, "set mintable") - - return flags.PostCommands(cmd)[0] -} - -func MintNFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "mint-nft [from_key_or_address] [contract_id] [to] [token_type:name:meta][,[token_type:name:meta]]", - Short: "Create and sign an mint-nft tx", - Long: ` -[NonFungible Token] -linkcli tx collection mint-nft [from_key_or_address] [contract_id] [to] [token_type] [name] [meta] -`, - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - from := cliCtx.FromAddress - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - mintNFTParamStrs := strings.Split(args[3], ",") - - mintNFTParams := make([]types.MintNFTParam, len(mintNFTParamStrs)) - for i, mintNFTParamStr := range mintNFTParamStrs { - strs := strings.Split(mintNFTParamStr, ":") - if len(strs) != 3 { - return errors.New("invalid format: ") - } - - mintNFTParams[i] = types.NewMintNFTParam(strs[1], strs[2], strs[0]) - } - - msg := types.NewMsgMintNFT(from, contractID, to, mintNFTParams...) - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - cmd.Flags().String(flagTokenType, "", "token-type for the nft") - - return flags.PostCommands(cmd)[0] -} - -func BurnNFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "burn-nft [from_key_or_address] [contract_id] [token_id]", - Short: "Create and sign an burn-nft tx", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - tokenID := args[2] - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgBurnNFT(cliCtx.GetFromAddress(), contractID, tokenID) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func BurnNFTFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "burn-nft-from [proxy_key_or_address] [contract_id] [from_address] [token_id]", - Short: "Create and sign an burn-nft-from tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - tokenID := args[3] - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgBurnNFTFrom(cliCtx.GetFromAddress(), contractID, from, tokenID) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -// nolint:dupl -func TransferFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer-ft [from_key_or_address] [contract_id] [to_address] [amount]", - Short: "Create and sign a tx transferring non-reserved collective fungible tokens", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - amount, err := types.ParseCoins(args[3]) - if err != nil { - return sdkerrors.Wrap(types.ErrInvalidAmount, args[3]) - } - - msg := types.NewMsgTransferFT(cliCtx.GetFromAddress(), contractID, to, amount...) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - cmd = flags.PostCommands(cmd)[0] - - return cmd -} - -// nolint:dupl -func TransferNFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer-nft [from_key_or_address] [contract_id] [to_address] [token_id][,[token_id]]", - Short: "Create and sign a tx transferring a collective non-fungible token", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - tokenIDs := strings.Split(args[3], ",") - - msg := types.NewMsgTransferNFT(cliCtx.GetFromAddress(), contractID, to, tokenIDs...) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func TransferFTFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer-ft-from [proxy_key_or_address] [contract_id] [from_address] [to_address] [amount]", - Short: "Create and sign a tx transferring non-reserved collective fungible tokens by approved proxy", - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - to, err := sdk.AccAddressFromBech32(args[3]) - if err != nil { - return err - } - - amount, err := types.ParseCoins(args[4]) - if err != nil { - return sdkerrors.Wrap(types.ErrInvalidAmount, args[4]) - } - - msg := types.NewMsgTransferFTFrom(cliCtx.GetFromAddress(), contractID, from, to, amount...) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - cmd = flags.PostCommands(cmd)[0] - - return cmd -} - -// nolint:dupl -func TransferNFTFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer-nft-from [proxy_key_or_address] [contract_id] [from_address] [to_address] [token_id]", - Short: "Create and sign a tx transferring a collective non-fungible token by approved proxy", - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - to, err := sdk.AccAddressFromBech32(args[3]) - if err != nil { - return err - } - - tokenIDs := strings.Split(args[4], ",") - - msg := types.NewMsgTransferNFTFrom(cliCtx.GetFromAddress(), contractID, from, to, tokenIDs...) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func AttachTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "attach [from_key_or_address] [contract_id] [to_token_id] [token_id]", - Short: "Create and sign a tx attaching a token to other", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - msg := types.NewMsgAttach(cliCtx.GetFromAddress(), args[1], args[2], args[3]) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func DetachTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "detach [from_key_or_address] [contract_id] [token_id]", - Short: "Create and sign a tx detaching a token", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - msg := types.NewMsgDetach(cliCtx.GetFromAddress(), args[1], args[2]) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -// nolint:dupl -func MintFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "mint-ft [from_key_or_address] [contract_id] [to] [amount]", - Short: "Create and sign a mint token tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - amount, err := types.ParseCoins(args[3]) - if err != nil { - return sdkerrors.Wrap(types.ErrInvalidAmount, args[3]) - } - - msg := types.NewMsgMintFT(cliCtx.GetFromAddress(), contractID, to, amount...) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func BurnFTTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "burn-ft [from_key_or_address] [contract_id] [token-id] [amount]", - Short: "Create and sign a mint token tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - contractID := args[1] - tokenID := args[2] - if err := types.ValidateDenom(tokenID); err != nil { - return errors.New("invalid tokenID") - } - amount, ok := sdk.NewIntFromString(args[3]) - if !ok { - return errors.New("invalid amount") - } - - msg := types.NewMsgBurnFT(cliCtx.GetFromAddress(), contractID, types.NewCoin(tokenID, amount)) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -// nolint:dupl -func BurnFTFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "burn-ft-from [proxy_key_or_address] [contract_id] [from_address] [token-id] [amount]", - Short: "Create and sign a mint token tx", - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - contractID := args[1] - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - tokenID := args[3] - if err := types.ValidateDenom(tokenID); err != nil { - return errors.New("invalid tokenID") - } - amount, ok := sdk.NewIntFromString(args[4]) - if !ok { - return errors.New("invalid amount") - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgBurnFTFrom(cliCtx.GetFromAddress(), contractID, from, types.NewCoin(tokenID, amount)) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func AttachFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "attach-from [proxy_key_or_address] [contract_id] [from_address] [to_token_id] [token_id]", - Short: "Create and sign a tx attaching a token to other by approved proxy", - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgAttachFrom(cliCtx.GetFromAddress(), contractID, from, args[3], args[4]) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -// nolint:dupl -func DetachFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "detach-from [proxy_key_or_address] [contract_id] [from_address] [token_id]", - Short: "Create and sign a tx detaching a token by approved proxy", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgDetachFrom(cliCtx.GetFromAddress(), contractID, from, args[3]) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -// nolint:dupl -func ApproveCollectionTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "approve [approver_key_or_address] [contract_id] [proxy_address]", - Short: "Create and sign a tx approve all token operations of a collection to a proxy", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - proxy, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgApprove(cliCtx.GetFromAddress(), contractID, proxy) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -// nolint:dupl -func DisapproveCollectionTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "disapprove [approver_key_or_address] [contract_id] [proxy_address]", - Short: "Create and sign a tx disapprove all token operations of a collection to a proxy", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - proxy, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgDisapprove(cliCtx.GetFromAddress(), contractID, proxy) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func GrantPermTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "grant [from_key_or_address] [contract_id] [to] [action]", - Short: "Create and sign a grant permission for token tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - perm := types.Permission(args[3]) - if !perm.Validate() { - return errors.New("permission invalid") - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgGrantPermission(cliCtx.GetFromAddress(), contractID, to, perm) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func RevokePermTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "revoke [from_key_or_address] [contract_id] [action]", - Short: "Create and sign a revoke permission for token tx", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - perm := types.Permission(args[2]) - if !perm.Validate() { - return errors.New("permission invalid") - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgRevokePermission(cliCtx.GetFromAddress(), contractID, perm) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} diff --git a/x/collection/client/internal/types/retriever.go b/x/collection/client/internal/types/retriever.go deleted file mode 100644 index f2e75242f1..0000000000 --- a/x/collection/client/internal/types/retriever.go +++ /dev/null @@ -1,316 +0,0 @@ -package types - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type Retriever struct { - querier types.NodeQuerier -} - -func NewRetriever(querier types.NodeQuerier) Retriever { - return Retriever{querier: querier} -} - -func (r Retriever) query(path, contractID string, data []byte) ([]byte, int64, error) { - return r.querier.QueryWithData(fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, path, contractID), data) -} - -func (r Retriever) GetAccountBalance(ctx context.CLIContext, contractID, tokenID string, addr sdk.AccAddress) (sdk.Int, int64, error) { - var balance sdk.Int - bs, err := ctx.Codec.MarshalJSON(types.NewQueryTokenIDAccAddressParams(tokenID, addr)) - if err != nil { - return balance, 0, err - } - - res, height, err := r.query(types.QueryBalance, contractID, bs) - if err != nil { - return balance, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &balance); err != nil { - return balance, height, err - } - - return balance, height, nil -} - -func (r Retriever) GetAccountBalances(ctx context.CLIContext, contractID string, addr sdk.AccAddress) (types.Coins, int64, error) { - var coins types.Coins - bs, err := ctx.Codec.MarshalJSON(types.NewQueryAccAddressParams(addr)) - if err != nil { - return coins, 0, err - } - - res, height, err := r.query(types.QueryBalances, contractID, bs) - - if err != nil { - return coins, height, err - } - if err := ctx.Codec.UnmarshalJSON(res, &coins); err != nil { - return coins, height, err - } - return coins, height, nil -} - -func (r Retriever) GetAccountPermission(ctx context.CLIContext, contractID string, addr sdk.AccAddress) (types.Permissions, int64, error) { - var pms types.Permissions - bs, err := ctx.Codec.MarshalJSON(types.NewQueryAccAddressParams(addr)) - if err != nil { - return pms, 0, err - } - - res, height, err := r.query(types.QueryPerms, contractID, bs) - if err != nil { - return pms, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &pms); err != nil { - return pms, height, err - } - - return pms, height, nil -} - -func (r Retriever) GetCollection(ctx context.CLIContext, contractID string) (types.BaseCollection, int64, error) { - var collection types.BaseCollection - res, height, err := r.query(types.QueryCollections, contractID, nil) - if err != nil { - return collection, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &collection); err != nil { - return collection, height, err - } - - return collection, height, nil -} - -func (r Retriever) GetCollectionNFTCount(ctx context.CLIContext, contractID, tokenID, target string) (sdk.Int, int64, error) { - var nftcount sdk.Int - bs, err := ctx.Codec.MarshalJSON(types.NewQueryTokenIDParams(tokenID)) - if err != nil { - return nftcount, 0, err - } - if target != types.QueryNFTCount && target != types.QueryNFTMint && target != types.QueryNFTBurn { - return nftcount, 0, fmt.Errorf("invalid target : %s", target) - } - - res, height, err := r.query(target, contractID, bs) - if err != nil { - return nftcount, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &nftcount); err != nil { - return nftcount, height, err - } - - return nftcount, height, nil -} - -func (r Retriever) GetTotal(ctx context.CLIContext, contractID, tokenID, target string) (sdk.Int, int64, error) { - var supply sdk.Int - bs, err := ctx.Codec.MarshalJSON(types.NewQueryTokenIDParams(tokenID)) - if err != nil { - return supply, 0, err - } - - res, height, err := r.query(target, contractID, bs) - if err != nil { - return supply, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &supply); err != nil { - return supply, height, err - } - - return supply, height, nil -} - -func (r Retriever) GetToken(ctx context.CLIContext, contractID, tokenID string) (types.Token, int64, error) { - var token types.Token - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryTokenIDParams(tokenID)) - if err != nil { - return token, 0, err - } - - res, height, err := r.query(types.QueryTokens, contractID, bs) - if err != nil { - return token, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &token); err != nil { - return token, height, err - } - return token, height, nil -} - -func (r Retriever) GetTokens(ctx context.CLIContext, contractID string) (types.Tokens, int64, error) { - var tokens types.Tokens - res, height, err := r.query(types.QueryTokens, contractID, nil) - if err != nil { - return tokens, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &tokens); err != nil { - return tokens, height, err - } - return tokens, height, nil -} - -func (r Retriever) GetTokensWithTokenType(ctx context.CLIContext, contractID string, tokenType string) (types.Tokens, int64, error) { - var tokens types.Tokens - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryTokenTypeParams(tokenType)) - - if err != nil { - return tokens, 0, err - } - if err = types.ValidateTokenType(tokenType); err != nil { - return tokens, 0, err - } - res, height, err := r.query(types.QueryTokensWithTokenType, contractID, bs) - if err != nil { - return tokens, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &tokens); err != nil { - return tokens, height, err - } - return tokens, height, nil -} - -func (r Retriever) GetTokenType(ctx context.CLIContext, contractID, tokenTypeID string) (types.TokenType, int64, error) { - var tokenType types.TokenType - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryTokenIDParams(tokenTypeID)) - if err != nil { - return tokenType, 0, err - } - - res, height, err := r.query(types.QueryTokenTypes, contractID, bs) - if err != nil { - return tokenType, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &tokenType); err != nil { - return tokenType, height, err - } - return tokenType, height, nil -} - -func (r Retriever) GetTokenTypes(ctx context.CLIContext, contractID string) (types.TokenTypes, int64, error) { - var tokenTypes types.TokenTypes - - res, height, err := r.query(types.QueryTokenTypes, contractID, nil) - if err != nil { - return tokenTypes, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &tokenTypes); err != nil { - return tokenTypes, height, err - } - return tokenTypes, height, nil -} - -func (r Retriever) GetApprovers(ctx context.CLIContext, contractID string, proxy sdk.AccAddress) (accAdds []sdk.AccAddress, height int64, err error) { - bs, err := ctx.Codec.MarshalJSON(types.NewQueryApproverParams(proxy)) - if err != nil { - return accAdds, 0, err - } - res, height, err := r.query(types.QueryApprovers, contractID, bs) - if err != nil { - return accAdds, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &accAdds); err != nil { - return accAdds, height, err - } - - return accAdds, height, nil -} - -func (r Retriever) IsApproved(ctx context.CLIContext, contractID string, proxy sdk.AccAddress, approver sdk.AccAddress) (approved bool, height int64, err error) { - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryIsApprovedParams(proxy, approver)) - if err != nil { - return false, 0, err - } - - res, height, err := r.query(types.QueryIsApproved, contractID, bs) - if err != nil { - return false, 0, err - } - - err = ctx.Codec.UnmarshalJSON(res, &approved) - if err != nil { - return false, 0, err - } - - return approved, height, nil -} - -func (r Retriever) EnsureExists(ctx context.CLIContext, contractID, tokenID string) error { - if _, _, err := r.GetToken(ctx, contractID, tokenID); err != nil { - return err - } - return nil -} - -func (r Retriever) GetParent(ctx context.CLIContext, contractID, tokenID string) (types.Token, int64, error) { - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryTokenIDParams(tokenID)) - if err != nil { - return nil, 0, err - } - - res, height, err := r.query(types.QueryParent, contractID, bs) - if res == nil { - return nil, 0, err - } - - var token types.Token - if err := ctx.Codec.UnmarshalJSON(res, &token); err != nil { - return nil, 0, err - } - - return token, height, nil -} - -func (r Retriever) GetRoot(ctx context.CLIContext, contractID, tokenID string) (types.Token, int64, error) { - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryTokenIDParams(tokenID)) - if err != nil { - return nil, 0, err - } - - res, height, err := r.query(types.QueryRoot, contractID, bs) - if res == nil { - return nil, 0, err - } - - var token types.Token - if err := ctx.Codec.UnmarshalJSON(res, &token); err != nil { - return nil, 0, err - } - - return token, height, nil -} - -func (r Retriever) GetChildren(ctx context.CLIContext, contractID, tokenID string) (types.Tokens, int64, error) { - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryTokenIDParams(tokenID)) - if err != nil { - return nil, 0, err - } - - res, height, err := r.query(types.QueryChildren, contractID, bs) - if res == nil { - return nil, 0, err - } - - var tokens types.Tokens - if err := ctx.Codec.UnmarshalJSON(res, &tokens); err != nil { - return nil, 0, err - } - - return tokens, height, nil -} diff --git a/x/collection/client/rest/query.go b/x/collection/client/rest/query.go deleted file mode 100644 index f3269bd5f8..0000000000 --- a/x/collection/client/rest/query.go +++ /dev/null @@ -1,524 +0,0 @@ -package rest - -import ( - "fmt" - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/line/lbm-sdk/v2/x/collection/client/internal/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/types/rest" -) - -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/collection/{contract_id}/fts/{token_id}/supply", QueryTokenTotalRequestHandlerFn(cliCtx, types.QuerySupply)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/fts/{token_id}/mint", QueryTokenTotalRequestHandlerFn(cliCtx, types.QueryMint)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/fts/{token_id}/burn", QueryTokenTotalRequestHandlerFn(cliCtx, types.QueryBurn)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/fts/{token_id}", QueryTokenRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/nfts/{token_id}/parent", QueryParentRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/nfts/{token_id}/root", QueryRootRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/nfts/{token_id}/children", QueryChildrenRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/nfts/{token_id}", QueryTokenRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/tokens", QueryTokensRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/tokentypes/{token_type}/tokens", QueryTokensWithTokenTypeRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/tokentypes/{token_type}/count", QueryCountRequestHandlerFn(cliCtx, types.QueryNFTCount)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/tokentypes/{token_type}/mint", QueryCountRequestHandlerFn(cliCtx, types.QueryNFTMint)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/tokentypes/{token_type}/burn", QueryCountRequestHandlerFn(cliCtx, types.QueryNFTBurn)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/tokentypes/{token_type}", QueryTokenTypeRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/tokentypes", QueryTokenTypesRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/accounts/{address}/permissions", QueryPermRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/accounts/{address}/proxies/{approver}", QueryIsApprovedRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/accounts/{address}/balances", QueryBalancesRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/accounts/{address}/approvers", QueryApproversRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/accounts/{address}/balances/{token_id}", QueryBalanceRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/collection/{contract_id}/collection", QueryCollectionRequestHandlerFn(cliCtx)).Methods("GET") -} - -func QueryBalancesRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - addr, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("addr[%s] cannot parsed: %s", vars["address"], err)) - return - } - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - coins, height, err := retriever.GetAccountBalances(cliCtx, contractID, addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, coins) - } -} - -func QueryBalanceRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenID := vars["token_id"] - addr, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("addr[%s] cannot parsed: %s", vars["address"], err)) - return - } - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - supply, height, err := retriever.GetAccountBalance(cliCtx, contractID, tokenID, addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, supply) - } -} - -func QueryTokenTypeRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenTypeID := vars["token_type"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - tokenType, height, err := retriever.GetTokenType(cliCtx, contractID, tokenTypeID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, tokenType) - } -} - -func QueryTokenTypesRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - tokenTypes, height, err := retriever.GetTokenTypes(cliCtx, contractID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, tokenTypes) - } -} - -func QueryTokenRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenID := vars["token_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - token, height, err := retriever.GetToken(cliCtx, contractID, tokenID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, token) - } -} - -func QueryTokensRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - tokens, height, err := retriever.GetTokens(cliCtx, contractID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, tokens) - } -} -func QueryCollectionRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - collection, height, err := retriever.GetCollection(cliCtx, contractID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, collection) - } -} - -func QueryTokenTotalRequestHandlerFn(cliCtx context.CLIContext, target string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenID := vars["token_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - supply, height, err := retriever.GetTotal(cliCtx, contractID, tokenID, target) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, supply) - } -} - -func QueryTokensWithTokenTypeRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenType := vars["token_type"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - tokens, height, err := retriever.GetTokensWithTokenType(cliCtx, contractID, tokenType) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, tokens) - } -} - -func QueryCountRequestHandlerFn(cliCtx context.CLIContext, target string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenID := vars["token_type"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - nftcount, height, err := retriever.GetCollectionNFTCount(cliCtx, contractID, tokenID, target) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, nftcount) - } -} - -func QueryPermRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - addr, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("address cannot parsed: %s", err)) - return - } - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - pms, height, err := retriever.GetAccountPermission(cliCtx, contractID, addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, pms) - } -} - -// nolint:dupl -func QueryParentRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenID := vars["token_id"] - - if len(contractID) == 0 { - rest.WriteErrorResponse(w, http.StatusBadRequest, "contract_id absent") - return - } - - if len(tokenID) == 0 { - rest.WriteErrorResponse(w, http.StatusBadRequest, "token_id absent") - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - tokenGetter := clienttypes.NewRetriever(cliCtx) - - if err := tokenGetter.EnsureExists(cliCtx, contractID, tokenID); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - token, height, err := tokenGetter.GetParent(cliCtx, contractID, tokenID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, token) - } -} - -// nolint:dupl -func QueryRootRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenID := vars["token_id"] - - if len(contractID) == 0 { - rest.WriteErrorResponse(w, http.StatusBadRequest, "contract_id absent") - return - } - - if len(tokenID) == 0 { - rest.WriteErrorResponse(w, http.StatusBadRequest, "token_id absent") - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - tokenGetter := clienttypes.NewRetriever(cliCtx) - - if err := tokenGetter.EnsureExists(cliCtx, contractID, tokenID); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - token, height, err := tokenGetter.GetRoot(cliCtx, contractID, tokenID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, token) - } -} - -// nolint:dupl -func QueryChildrenRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - tokenID := vars["token_id"] - - if len(contractID) == 0 { - rest.WriteErrorResponse(w, http.StatusBadRequest, "contract_id absent") - return - } - - if len(tokenID) == 0 { - rest.WriteErrorResponse(w, http.StatusBadRequest, "token_id absent") - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - tokenGetter := clienttypes.NewRetriever(cliCtx) - - if err := tokenGetter.EnsureExists(cliCtx, contractID, tokenID); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - tokens, height, err := tokenGetter.GetChildren(cliCtx, contractID, tokenID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, tokens) - } -} - -func QueryApproversRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - - proxy, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("approver[%s] cannot parsed: %s", proxy.String(), err)) - return - } - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - approvers, height, err := retriever.GetApprovers(cliCtx, contractID, proxy) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, approvers) - } -} - -func QueryIsApprovedRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - - proxy, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("proxy[%s] cannot parsed: %s", proxy.String(), err)) - return - } - - approver, err := sdk.AccAddressFromBech32(vars["approver"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("approver[%s] cannot parsed: %s", approver.String(), err)) - return - } - - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - approved, height, err := retriever.IsApproved(cliCtx, contractID, proxy, approver) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, approved) - } -} diff --git a/x/collection/genesis.go b/x/collection/genesis.go deleted file mode 100644 index 499bd99852..0000000000 --- a/x/collection/genesis.go +++ /dev/null @@ -1,42 +0,0 @@ -package collection - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type GenesisState struct { - Params types.Params `json:"params"` - Tokens []Token `json:"tokens"` - // TODO: approvals -} - -func NewGenesisState(params types.Params, tokens []Token) GenesisState { - return GenesisState{ - Params: params, - Tokens: tokens, - } -} - -func DefaultGenesisState() GenesisState { - return NewGenesisState(types.DefaultParams(), nil) -} - -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { - // TODO: fill it with permission - keeper.SetParams(ctx, data.Params) -} - -func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { - params := keeper.GetParams(ctx) - return NewGenesisState(params, nil) -} - -func ValidateGenesis(data GenesisState) error { - if err := data.Params.Validate(); err != nil { - return err - } - - return nil -} diff --git a/x/collection/internal/handler/burn.go b/x/collection/internal/handler/burn.go deleted file mode 100644 index 6a664b3136..0000000000 --- a/x/collection/internal/handler/burn.go +++ /dev/null @@ -1,71 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgBurnNFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgBurnNFT) (*sdk.Result, error) { - err := keeper.BurnNFT(ctx, msg.From, msg.TokenIDs...) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgBurnNFTFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgBurnNFTFrom) (*sdk.Result, error) { - err := keeper.BurnNFTFrom(ctx, msg.Proxy, msg.From, msg.TokenIDs...) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgBurnFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgBurnFT) (*sdk.Result, error) { - err := keeper.BurnFT(ctx, msg.From, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgBurnFTFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgBurnFTFrom) (*sdk.Result, error) { - err := keeper.BurnFTFrom(ctx, msg.Proxy, msg.From, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/burn_test.go b/x/collection/internal/handler/burn_test.go deleted file mode 100644 index 9aed6f9ada..0000000000 --- a/x/collection/internal/handler/burn_test.go +++ /dev/null @@ -1,209 +0,0 @@ -package handler - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" -) - -func TestHandleMsgBurnFT(t *testing.T) { - ctx, h, contractID := prepareFT(t) - - { - // invalid user - burnMsg := types.NewMsgBurnFT(addr2, contractID, types.NewCoin("0000000100000000", sdk.NewInt(100))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn non-exist token - burnMsg := types.NewMsgBurnFT(addr1, contractID, types.NewCoin("0000000200000000", sdk.NewInt(100))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn tokens over the being supplied - burnMsg := types.NewMsgBurnFT(addr1, contractID, types.NewCoin("0000000100000000", sdk.NewInt(1001))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn tokens with invalid contractID - burnMsg := types.NewMsgBurnFT(addr1, "abcd11234", types.NewCoin("0000000100000000", sdk.NewInt(1000))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // success case - burnMsg := types.NewMsgBurnFT(addr1, contractID, types.NewCoin("0000000100000000", sdk.NewInt(100))) - res, err := h(ctx, burnMsg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("burn_ft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_ft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("burn_ft", sdk.NewAttribute("amount", types.NewCoins(types.NewCoin("0000000100000000", sdk.NewInt(100))).String())), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleMsgBurnFTFrom(t *testing.T) { - ctx, h, contractID := prepareFT(t) - - sendMsg := types.NewMsgTransferFT(addr1, contractID, addr2, types.NewCoin("0000000100000000", sdk.NewInt(1000))) - _, err := h(ctx, sendMsg) - require.NoError(t, err) - - { - // not approved - burnMsg := types.NewMsgBurnFTFrom(addr1, contractID, addr2, types.NewCoin("0000000100000000", sdk.NewInt(100))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - - approve(t, addr2, addr1, contractID, ctx, h) - { - // invalid user - burnMsg := types.NewMsgBurnFTFrom(addr2, contractID, addr2, types.NewCoin("0000000100000000", sdk.NewInt(100))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn non-exist token - burnMsg := types.NewMsgBurnFTFrom(addr1, contractID, addr2, types.NewCoin("0000000200000000", sdk.NewInt(100))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn tokens over the being supplied - burnMsg := types.NewMsgBurnFTFrom(addr1, contractID, addr2, types.NewCoin("0000000100000000", sdk.NewInt(1001))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn tokens with invalid contractID - burnMsg := types.NewMsgBurnFTFrom(addr1, "abcd11234", addr2, types.NewCoin("0000000100000000", sdk.NewInt(1000))) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // success case - burnMsg := types.NewMsgBurnFTFrom(addr1, contractID, addr2, types.NewCoin("0000000100000000", sdk.NewInt(100))) - res, err := h(ctx, burnMsg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("proxy", addr1.String())), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("amount", types.NewCoins(types.NewCoin("0000000100000000", sdk.NewInt(100))).String())), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleMsgBurnNFT(t *testing.T) { - ctx, h, contractID := prepareNFT(t, addr1) - - { - // invalid user - burnMsg := types.NewMsgBurnNFT(addr2, contractID, "1000000100000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn non-exist token - burnMsg := types.NewMsgBurnNFT(addr1, contractID, "1000000200000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn tokens with invalid contractID - burnMsg := types.NewMsgBurnNFT(addr1, "abcd11234", "1000000100000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // success case - burnMsg := types.NewMsgBurnNFT(addr1, contractID, "1000000100000001") - res, err := h(ctx, burnMsg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("burn_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_nft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("burn_nft", sdk.NewAttribute("token_id", "1000000100000001")), - sdk.NewEvent("operation_burn_nft", sdk.NewAttribute("token_id", "1000000100000001")), - } - verifyEventFunc(t, e, res.Events) - } - { - // burn already burned - burnMsg := types.NewMsgBurnNFT(addr1, contractID, "1000000100000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } -} - -func TestHandleMsgBurnNFTFrom(t *testing.T) { - ctx, h, contractID := prepareNFT(t, addr2) - - { - // not approved - burnMsg := types.NewMsgBurnNFTFrom(addr1, contractID, addr2, "1000000100000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - - approve(t, addr2, addr1, contractID, ctx, h) - { - // invalid user - burnMsg := types.NewMsgBurnNFTFrom(addr2, contractID, addr2, "1000000100000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn non-exist token - burnMsg := types.NewMsgBurnNFTFrom(addr1, contractID, addr2, "1000000200000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // burn tokens with invalid contractID - burnMsg := types.NewMsgBurnNFTFrom(addr1, "abcd11234", addr2, "1000000100000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - { - // success case - burnMsg := types.NewMsgBurnNFTFrom(addr1, contractID, addr2, "1000000100000001") - res, err := h(ctx, burnMsg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("proxy", addr1.String())), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("token_id", "1000000100000001")), - sdk.NewEvent("operation_burn_nft", sdk.NewAttribute("token_id", "1000000100000001")), - } - verifyEventFunc(t, e, res.Events) - } - { - // burn already burned - burnMsg := types.NewMsgBurnNFTFrom(addr1, contractID, addr2, "1000000100000001") - _, err := h(ctx, burnMsg) - require.Error(t, err) - } -} diff --git a/x/collection/internal/handler/composable.go b/x/collection/internal/handler/composable.go deleted file mode 100644 index 43629f55cc..0000000000 --- a/x/collection/internal/handler/composable.go +++ /dev/null @@ -1,75 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgAttach(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgAttach) (*sdk.Result, error) { - err := keeper.Attach(ctx, msg.From, msg.ToTokenID, msg.TokenID) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgDetach(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgDetach) (*sdk.Result, error) { - err := keeper.Detach(ctx, msg.From, msg.TokenID) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgAttachFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgAttachFrom) (*sdk.Result, error) { - err := keeper.AttachFrom(ctx, msg.Proxy, msg.From, msg.ToTokenID, msg.TokenID) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgDetachFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgDetachFrom) (*sdk.Result, error) { - err := keeper.DetachFrom(ctx, msg.Proxy, msg.From, msg.TokenID) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/composable_test.go b/x/collection/internal/handler/composable_test.go deleted file mode 100644 index 84598e6131..0000000000 --- a/x/collection/internal/handler/composable_test.go +++ /dev/null @@ -1,251 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestHandleAttach(t *testing.T) { - ctx, h, contractID := prepareNFT(t, addr1) - - { - msg := types.NewMsgAttach(addr1, contractID, defaultTokenID1, defaultTokenID2) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("attach", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("attach", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("attach", sdk.NewAttribute("to_token_id", defaultTokenID1)), - sdk.NewEvent("attach", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("attach", sdk.NewAttribute("old_root_token_id", defaultTokenID2)), - sdk.NewEvent("attach", sdk.NewAttribute("new_root_token_id", defaultTokenID1)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleAttachFrom(t *testing.T) { - ctx, h, contractID := prepareNFT(t, addr2) - approve(t, addr2, addr1, contractID, ctx, h) - { - msg := types.NewMsgAttachFrom(addr1, contractID, addr2, defaultTokenID1, defaultTokenID2) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("attach_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("attach_from", sdk.NewAttribute("proxy", addr1.String())), - sdk.NewEvent("attach_from", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("attach_from", sdk.NewAttribute("to_token_id", defaultTokenID1)), - sdk.NewEvent("attach_from", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("attach_from", sdk.NewAttribute("old_root_token_id", defaultTokenID2)), - sdk.NewEvent("attach_from", sdk.NewAttribute("new_root_token_id", defaultTokenID1)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) - } -} - -func prepareForDetaching(t *testing.T, mintTo sdk.AccAddress) (sdk.Context, sdk.Handler, string) { - ctx, h, contractID := prepareNFT(t, mintTo) - - msg := types.NewMsgAttach(mintTo, contractID, defaultTokenID1, defaultTokenID2) - _, err := h(ctx, msg) - require.NoError(t, err) - return ctx, h, contractID -} - -func TestHandleDetach(t *testing.T) { - ctx, h, contractID := prepareForDetaching(t, addr1) - - { - msg := types.NewMsgDetach(addr1, contractID, defaultTokenID2) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("detach", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("detach", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("detach", sdk.NewAttribute("from_token_id", defaultTokenID1)), - sdk.NewEvent("detach", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("detach", sdk.NewAttribute("old_root_token_id", defaultTokenID1)), - sdk.NewEvent("detach", sdk.NewAttribute("new_root_token_id", defaultTokenID2)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleDetachFrom(t *testing.T) { - ctx, h, contractID := prepareForDetaching(t, addr2) - approve(t, addr2, addr1, contractID, ctx, h) - { - msg := types.NewMsgDetachFrom(addr1, contractID, addr2, defaultTokenID2) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("detach_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("detach_from", sdk.NewAttribute("proxy", addr1.String())), - sdk.NewEvent("detach_from", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("detach_from", sdk.NewAttribute("from_token_id", defaultTokenID1)), - sdk.NewEvent("detach_from", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("detach_from", sdk.NewAttribute("old_root_token_id", defaultTokenID1)), - sdk.NewEvent("detach_from", sdk.NewAttribute("new_root_token_id", defaultTokenID2)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) - } -} - -func attach(t *testing.T, ctx sdk.Context, h sdk.Handler, contractID string) { - msg := types.NewMsgAttach(addr1, contractID, defaultTokenID1, defaultTokenID2) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("attach", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("attach", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("attach", sdk.NewAttribute("to_token_id", defaultTokenID1)), - sdk.NewEvent("attach", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("attach", sdk.NewAttribute("old_root_token_id", defaultTokenID2)), - sdk.NewEvent("attach", sdk.NewAttribute("new_root_token_id", defaultTokenID1)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) -} - -func TestHandleAttachDetach(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err = h(ctx, msg) - require.NoError(t, err) - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg2 := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg2 = types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - } - - attach(t, ctx, h, contractID) - - { - msg2 := types.NewMsgDetach(addr1, contractID, defaultTokenID2) - res2, err2 := h(ctx, msg2) - require.NoError(t, err2) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("detach", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("detach", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("detach", sdk.NewAttribute("from_token_id", defaultTokenID1)), - sdk.NewEvent("detach", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("detach", sdk.NewAttribute("old_root_token_id", defaultTokenID1)), - sdk.NewEvent("detach", sdk.NewAttribute("new_root_token_id", defaultTokenID2)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res2.Events) - } - - // Attach again - attach(t, ctx, h, contractID) - - // Burn token - { - msg := types.NewMsgBurnNFT(addr1, contractID, defaultTokenID1) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("burn_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_nft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("burn_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("operation_burn_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("operation_burn_nft", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleAttachFromDetachFromScenario(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err = h(ctx, msg) - require.NoError(t, err) - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg2 := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg2 = types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg3 := types.NewMsgApprove(addr1, contractID, addr2) - _, err = h(ctx, msg3) - require.NoError(t, err) - } - - msg := types.NewMsgAttachFrom(addr2, contractID, addr1, defaultTokenID1, defaultTokenID2) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("attach_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("attach_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("attach_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("attach_from", sdk.NewAttribute("to_token_id", defaultTokenID1)), - sdk.NewEvent("attach_from", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("attach_from", sdk.NewAttribute("old_root_token_id", defaultTokenID2)), - sdk.NewEvent("attach_from", sdk.NewAttribute("new_root_token_id", defaultTokenID1)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) - - msg2 := types.NewMsgDetachFrom(addr2, contractID, addr1, defaultTokenID2) - res2, err2 := h(ctx, msg2) - require.NoError(t, err2) - e = sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("detach_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("detach_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("detach_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("detach_from", sdk.NewAttribute("from_token_id", defaultTokenID1)), - sdk.NewEvent("detach_from", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("detach_from", sdk.NewAttribute("old_root_token_id", defaultTokenID1)), - sdk.NewEvent("detach_from", sdk.NewAttribute("new_root_token_id", defaultTokenID2)), - sdk.NewEvent("operation_root_changed", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res2.Events) -} diff --git a/x/collection/internal/handler/create.go b/x/collection/internal/handler/create.go deleted file mode 100644 index 9575256fd0..0000000000 --- a/x/collection/internal/handler/create.go +++ /dev/null @@ -1,29 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" -) - -func handleMsgCreateCollection(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgCreateCollection) (*sdk.Result, error) { - contractI := ctx.Context().Value(contract.CtxKey{}) - if contractI == nil { - panic("contract id does not set") - } - collection := types.NewCollection(contractI.(string), msg.Name, msg.Meta, msg.BaseImgURI) - err := keeper.CreateCollection(ctx, collection, msg.Owner) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/create_test.go b/x/collection/internal/handler/create_test.go deleted file mode 100644 index 6645b033e0..0000000000 --- a/x/collection/internal/handler/create_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - contractID = "9be17165" -) - -func TestHandleMsgCreateCollection(t *testing.T) { - ctx, h := cacheKeeper() - { - msg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("create_collection", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("create_collection", sdk.NewAttribute("name", defaultName)), - sdk.NewEvent("create_collection", sdk.NewAttribute("owner", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "issue")), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "mint")), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "burn")), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "modify")), - } - verifyEventFunc(t, e, res.Events) - } -} diff --git a/x/collection/internal/handler/handler.go b/x/collection/internal/handler/handler.go deleted file mode 100644 index b8b0f991cb..0000000000 --- a/x/collection/internal/handler/handler.go +++ /dev/null @@ -1,86 +0,0 @@ -package handler - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" -) - -func NewHandler(keeper keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - if msg, ok := msg.(contract.Msg); ok { - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, msg.GetContractID())) - err := handleMsgContract(ctx, keeper, msg) - if err != nil { - return nil, err - } - } - - if _, ok := msg.(types.MsgCreateCollection); ok { - contractID := keeper.NewContractID(ctx) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, contractID)) - } - if ctx.Context().Value(contract.CtxKey{}) == nil { - panic("contract id does not set") - } - switch msg := msg.(type) { - case types.MsgCreateCollection: - return handleMsgCreateCollection(ctx, keeper, msg) - case types.MsgIssueFT: - return handleMsgIssueFT(ctx, keeper, msg) - case types.MsgMintNFT: - return handleMsgMintNFT(ctx, keeper, msg) - case types.MsgBurnNFT: - return handleMsgBurnNFT(ctx, keeper, msg) - case types.MsgBurnNFTFrom: - return handleMsgBurnNFTFrom(ctx, keeper, msg) - case types.MsgIssueNFT: - return handleMsgIssueNFT(ctx, keeper, msg) - case types.MsgMintFT: - return handleMsgMintFT(ctx, keeper, msg) - case types.MsgBurnFT: - return handleMsgBurnFT(ctx, keeper, msg) - case types.MsgBurnFTFrom: - return handleMsgBurnFTFrom(ctx, keeper, msg) - case types.MsgGrantPermission: - return handleMsgGrant(ctx, keeper, msg) - case types.MsgRevokePermission: - return handleMsgRevoke(ctx, keeper, msg) - case types.MsgModify: - return handleMsgModify(ctx, keeper, msg) - case types.MsgTransferFT: - return handleMsgTransferFT(ctx, keeper, msg) - case types.MsgTransferNFT: - return handleMsgTransferNFT(ctx, keeper, msg) - case types.MsgTransferFTFrom: - return handleMsgTransferFTFrom(ctx, keeper, msg) - case types.MsgTransferNFTFrom: - return handleMsgTransferNFTFrom(ctx, keeper, msg) - case types.MsgAttach: - return handleMsgAttach(ctx, keeper, msg) - case types.MsgDetach: - return handleMsgDetach(ctx, keeper, msg) - case types.MsgAttachFrom: - return handleMsgAttachFrom(ctx, keeper, msg) - case types.MsgDetachFrom: - return handleMsgDetachFrom(ctx, keeper, msg) - case types.MsgApprove: - return handleMsgApprove(ctx, keeper, msg) - case types.MsgDisapprove: - return handleMsgDisapprove(ctx, keeper, msg) - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized Msg type: %T", msg) - } - } -} -func handleMsgContract(ctx sdk.Context, keeper keeper.Keeper, msg contract.Msg) error { - if !keeper.HasContractID(ctx) { - return sdkerrors.Wrapf(contract.ErrContractNotExist, "contract id: %s", msg.GetContractID()) - } - return nil -} diff --git a/x/collection/internal/handler/handler_test.go b/x/collection/internal/handler/handler_test.go deleted file mode 100644 index 512d169eca..0000000000 --- a/x/collection/internal/handler/handler_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package handler - -import ( - "context" - "os" - "strings" - "testing" - - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - testCommon "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -var ( - ms store.CommitMultiStore - ctx sdk.Context - k testCommon.Keeper -) - -func setup() { - println("setup") - ctx, ms, k = testCommon.TestKeeper() -} - -func TestMain(m *testing.M) { - setup() - ret := m.Run() - os.Exit(ret) -} - -func cacheKeeper() (sdk.Context, sdk.Handler) { - msCache := ms.CacheMultiStore() - ctx = ctx.WithMultiStore(msCache) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID)) - return ctx, NewHandler(k) -} - -var verifyEventFunc = func(t *testing.T, expected sdk.Events, actual sdk.Events) { - require.Equal(t, sdk.StringifyEvents(expected.ToABCIEvents()).String(), sdk.StringifyEvents(actual.ToABCIEvents()).String()) -} - -const ( - defaultContractID = "9be17165" - defaultName = "name" - defaultMeta = "{}" - defaultImgURI = "img-uri" - defaultDecimals = 6 - defaultAmount = 1000 - defaultTokenType = "10000001" - defaultTokenType2 = "10000002" - defaultTokenType3 = "10000003" - defaultTokenIndex = "00000001" - defaultTokenID1 = defaultTokenType + defaultTokenIndex - defaultTokenID2 = defaultTokenType + "00000002" - defaultTokenID3 = defaultTokenType + "00000003" - defaultTokenIDFT = "0000000100000000" -) - -var ( - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) -) - -func GetMadeContractID(events sdk.Events) string { - for _, event := range events.ToABCIEvents() { - for _, attr := range event.Attributes { - if string(attr.Key) == types.AttributeKeyContractID { - return string(attr.Value) - } - } - } - return "" -} - -func TestHandlerUnrecognized(t *testing.T) { - ctx, h := cacheKeeper() - _, err := h(ctx, sdk.NewTestMsg()) - require.Error(t, err) - require.True(t, strings.Contains(err.Error(), "unrecognized Msg type")) -} diff --git a/x/collection/internal/handler/issue.go b/x/collection/internal/handler/issue.go deleted file mode 100644 index 5c52c9f7bc..0000000000 --- a/x/collection/internal/handler/issue.go +++ /dev/null @@ -1,73 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgIssueFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgIssueFT) (*sdk.Result, error) { - _, err := keeper.GetCollection(ctx) - if err != nil { - return nil, err - } - perm := types.NewIssuePermission() - if !keeper.HasPermission(ctx, msg.Owner, perm) { - return nil, sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", msg.Owner.String(), perm.String()) - } - - tokenID, err := keeper.GetNextTokenIDFT(ctx) - if err != nil { - return nil, err - } - - token := types.NewFT(msg.ContractID, tokenID, msg.Name, msg.Meta, msg.Decimals, msg.Mintable) - err = keeper.IssueFT(ctx, msg.Owner, msg.To, token, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()), - ), - }) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgIssueNFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgIssueNFT) (*sdk.Result, error) { - _, err := keeper.GetCollection(ctx) - if err != nil { - return nil, err - } - - perm := types.NewIssuePermission() - if !keeper.HasPermission(ctx, msg.Owner, perm) { - return nil, sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", msg.Owner.String(), perm.String()) - } - - tokenTypeID, err := keeper.GetNextTokenType(ctx) - if err != nil { - return nil, err - } - - tokenType := types.NewBaseTokenType(msg.ContractID, tokenTypeID, msg.Name, msg.Meta) - err = keeper.IssueNFT(ctx, tokenType, msg.Owner) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()), - ), - }) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/issue_test.go b/x/collection/internal/handler/issue_test.go deleted file mode 100644 index 8583c406a9..0000000000 --- a/x/collection/internal/handler/issue_test.go +++ /dev/null @@ -1,382 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func prepareCreateCollection(t *testing.T) (sdk.Context, sdk.Handler, string) { - ctx, h := cacheKeeper() - var contractID string - msg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, msg) - require.NoError(t, err) - - contractID = GetMadeContractID(res.Events) - - return ctx, h, contractID -} - -func prepareFT(t *testing.T) (sdk.Context, sdk.Handler, string) { - ctx, h, contractID := prepareCreateCollection(t) - - msg := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err := h(ctx, msg) - require.NoError(t, err) - - return ctx, h, contractID -} - -func prepareNFT(t *testing.T, mintTo sdk.AccAddress) (sdk.Context, sdk.Handler, string) { - ctx, h, contractID := prepareCreateCollection(t) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err := h(ctx, msg) - require.NoError(t, err) - - param := types.NewMintNFTParam("sword1", defaultMeta, "10000001") - msg2 := types.NewMsgMintNFT(addr1, contractID, mintTo, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - - param = types.NewMintNFTParam("sword2", defaultMeta, "10000001") - types.NewMsgMintNFT(addr1, contractID, mintTo, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - - return ctx, h, contractID -} - -func TestHandleMsgIssueFT(t *testing.T) { - ctx, h, contractID := prepareCreateCollection(t) - - msg := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("issue_ft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("issue_ft", sdk.NewAttribute("name", defaultName)), - sdk.NewEvent("issue_ft", sdk.NewAttribute("token_id", defaultTokenIDFT)), - sdk.NewEvent("issue_ft", sdk.NewAttribute("owner", addr1.String())), - sdk.NewEvent("issue_ft", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("issue_ft", sdk.NewAttribute("amount", "1000")), - sdk.NewEvent("issue_ft", sdk.NewAttribute("mintable", "true")), - sdk.NewEvent("issue_ft", sdk.NewAttribute("decimals", "6")), - } - verifyEventFunc(t, e, res.Events) -} - -func TestHandleMsgIssueNFT(t *testing.T) { - ctx, h, contractID := prepareCreateCollection(t) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("issue_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("issue_nft", sdk.NewAttribute("token_type", defaultTokenType)), - } - verifyEventFunc(t, e, res.Events) -} - -func TestHandlerIssueFT(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - msg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, msg) - contractID = GetMadeContractID(res.Events) - require.NoError(t, err) - } - - { - msg := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgIssueFT(addr2, addr2, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err := h(ctx, msg) - require.Error(t, err) - } - - permission := types.NewIssuePermission() - - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, permission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgIssueFT(addr2, addr2, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgRevokePermission(addr1, contractID, permission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgIssueFT(addr1, addr2, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err := h(ctx, msg) - require.Error(t, err) - } -} - -func TestHandlerIssueNFT(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - msg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, msg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - } - - { - // Expect token type is 1001 - { - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err := h(ctx, msg) - require.NoError(t, err) - } - // Expect token type is 1002 - { - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType2) - msg := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType2) - msg := types.NewMsgMintNFT(addr1, contractID, addr2, param) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - mintPermission := types.NewMintPermission() - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, mintPermission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType2) - msg := types.NewMsgMintNFT(addr2, contractID, addr2, param) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgRevokePermission(addr1, contractID, mintPermission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType2) - msg := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err := h(ctx, msg) - require.Error(t, err) - } - } - } - - permission := types.NewIssuePermission() - - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, permission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - // Expect token type is 1003 - { - msg := types.NewMsgIssueNFT(addr2, contractID, defaultName, defaultMeta) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType3) - msg := types.NewMsgMintNFT(addr2, contractID, addr2, param) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgRevokePermission(addr1, contractID, permission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - { - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err := h(ctx, msg) - require.Error(t, err) - } -} - -func TestEvents(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - msg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("create_collection", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("create_collection", sdk.NewAttribute("name", defaultName)), - sdk.NewEvent("create_collection", sdk.NewAttribute("owner", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "issue")), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "mint")), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "burn")), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "modify")), - } - verifyEventFunc(t, e, res.Events) - } - - { - msg := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("issue_ft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("issue_ft", sdk.NewAttribute("name", defaultName)), - sdk.NewEvent("issue_ft", sdk.NewAttribute("token_id", defaultTokenIDFT)), - sdk.NewEvent("issue_ft", sdk.NewAttribute("owner", addr1.String())), - sdk.NewEvent("issue_ft", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("issue_ft", sdk.NewAttribute("amount", sdk.NewInt(defaultAmount).String())), - sdk.NewEvent("issue_ft", sdk.NewAttribute("mintable", "true")), - sdk.NewEvent("issue_ft", sdk.NewAttribute("decimals", sdk.NewInt(defaultDecimals).String())), - } - verifyEventFunc(t, e, res.Events) - } - - { - msg := types.NewMsgMintFT(addr1, contractID, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("mint_ft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("mint_ft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("mint_ft", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("mint_ft", sdk.NewAttribute("amount", types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)).String())), - } - verifyEventFunc(t, e, res.Events) - } - - { - msg := types.NewMsgBurnFT(addr1, contractID, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("burn_ft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_ft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("burn_ft", sdk.NewAttribute("amount", types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)).String())), - } - verifyEventFunc(t, e, res.Events) - } - - { - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("issue_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("issue_nft", sdk.NewAttribute("token_type", defaultTokenType)), - } - verifyEventFunc(t, e, res.Events) - } - - { - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg := types.NewMsgMintNFT(addr1, contractID, addr1, param) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("mint_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("mint_nft", sdk.NewAttribute("name", defaultName)), - sdk.NewEvent("mint_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("mint_nft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("mint_nft", sdk.NewAttribute("to", addr1.String())), - } - verifyEventFunc(t, e, res.Events) - } - - permission := types.NewIssuePermission() - - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, permission) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", permission.String())), - } - verifyEventFunc(t, e, res.Events) - } - { - msg := types.NewMsgRevokePermission(addr1, contractID, permission) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("perm", permission.String())), - } - verifyEventFunc(t, e, res.Events) - } -} diff --git a/x/collection/internal/handler/mint.go b/x/collection/internal/handler/mint.go deleted file mode 100644 index 3f53065a58..0000000000 --- a/x/collection/internal/handler/mint.go +++ /dev/null @@ -1,52 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgMintNFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgMintNFT) (*sdk.Result, error) { - _, err := keeper.GetCollection(ctx) - if err != nil { - return nil, err - } - - for _, mintNFTParam := range msg.MintNFTParams { - tokenID, err := keeper.GetNextTokenIDNFT(ctx, mintNFTParam.TokenType) - if err != nil { - return nil, err - } - - token := types.NewNFT(msg.ContractID, tokenID, mintNFTParam.Name, mintNFTParam.Meta, msg.To) - err = keeper.MintNFT(ctx, msg.From, token) - if err != nil { - return nil, err - } - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgMintFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgMintFT) (*sdk.Result, error) { - err := keeper.MintFT(ctx, msg.From, msg.To, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/mint_test.go b/x/collection/internal/handler/mint_test.go deleted file mode 100644 index 569bd630ab..0000000000 --- a/x/collection/internal/handler/mint_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package handler - -import ( - "fmt" - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" -) - -func TestHandleMsgMintFT(t *testing.T) { - ctx, h, contractID := prepareFT(t) - - { - burnMsg := types.NewMsgMintFT(addr1, contractID, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(100))) - res, err := h(ctx, burnMsg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("mint_ft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("mint_ft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("mint_ft", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("mint_ft", sdk.NewAttribute("amount", types.NewCoins(types.NewCoin("0000000100000000", sdk.NewInt(100))).String())), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleMsgMintNFT(t *testing.T) { - ctx, h, contractID := prepareNFT(t, addr1) - - { - param := types.NewMintNFTParam("shield", "", "10000001") - msg := types.NewMsgMintNFT(addr1, contractID, addr1, param) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("mint_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("mint_nft", sdk.NewAttribute("name", "shield")), - sdk.NewEvent("mint_nft", sdk.NewAttribute("token_id", defaultTokenID3)), - sdk.NewEvent("mint_nft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("mint_nft", sdk.NewAttribute("to", addr1.String())), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleMsgMintNFTPerformance(t *testing.T) { - ctx, h, contractID := prepareNFT(t, addr1) - var mean int64 - var sum int64 = 0 - { - param := types.NewMintNFTParam("shield", "", "10000001") - msg := types.NewMsgMintNFT(addr1, contractID, addr1, param) - for jdx := 0; jdx < 10; jdx++ { - startTime := time.Now() - for idx := 0; idx < 1000; idx++ { - _, err := h(ctx, msg) - require.NoError(t, err) - } - duration := time.Since(startTime) - sum += duration.Nanoseconds() - } - mean = sum / 10 - } - - ctx, h, contractID = prepareNFT(t, addr1) - { - param := types.NewMintNFTParam("shield", "", "10000001") - msg := types.NewMsgMintNFT(addr1, contractID, addr1, param) - for jdx := 0; jdx < 10; jdx++ { - startTime := time.Now() - for idx := 0; idx < 1000; idx++ { - _, err := h(ctx, msg) - require.NoError(t, err) - } - duration := time.Since(startTime) - t.Log(fmt.Sprintf("MintNFT %s", duration.String())) - require.Less(t, duration.Nanoseconds(), mean*2) - } - } -} diff --git a/x/collection/internal/handler/modify.go b/x/collection/internal/handler/modify.go deleted file mode 100644 index 0b8aec7265..0000000000 --- a/x/collection/internal/handler/modify.go +++ /dev/null @@ -1,22 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgModify(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgModify) (*sdk.Result, error) { - if err := keeper.Modify(ctx, msg.Owner, msg.TokenType, msg.TokenIndex, msg.Changes); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/modify_test.go b/x/collection/internal/handler/modify_test.go deleted file mode 100644 index face4fd7e3..0000000000 --- a/x/collection/internal/handler/modify_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestHandleMsgModifyForCollection(t *testing.T) { - ctx, h := cacheKeeper() - const ( - modifiedName = "modifiedName" - modifiedImgURI = "modifiedImgURI" - modifiedMeta = "modifiedMeta" - ) - - var contractID string - - // Given MsgModify - msg := types.NewMsgModify(addr1, defaultContractID, "", "", types.NewChanges( - types.NewChange("name", modifiedName), - types.NewChange("base_img_uri", modifiedImgURI), - types.NewChange("meta", modifiedMeta), - )) - - t.Log("Test with nonexistent token") - { - // When handle MsgModify - _, err := h(ctx, msg) - - // Then response is error - require.Error(t, err) - } - - t.Log("Test modify token") - { - // Given created collection - res, err := h(ctx, types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI)) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - // When handle MsgModify - msg = types.NewMsgModify(addr1, contractID, "", "", types.NewChanges( - types.NewChange("name", modifiedName), - types.NewChange("base_img_uri", modifiedImgURI), - types.NewChange("meta", modifiedMeta))) - res, err = h(ctx, msg) - - // Then response is success - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - // And events are returned - expectedEvents := sdk.Events{ - sdk.NewEvent(types.EventTypeModifyCollection, sdk.NewAttribute(types.AttributeKeyContractID, contractID)), - sdk.NewEvent(types.EventTypeModifyCollection, sdk.NewAttribute("name", modifiedName)), - sdk.NewEvent(types.EventTypeModifyCollection, sdk.NewAttribute("base_img_uri", modifiedImgURI)), - sdk.NewEvent(types.EventTypeModifyCollection, sdk.NewAttribute("meta", modifiedMeta)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String())), - } - verifyEventFunc(t, expectedEvents, res.Events) - } -} - -func TestHandleMsgModifyForToken(t *testing.T) { - ctx, h := cacheKeeper() - const ( - modifiedTokenName = "modifiedTokenName" - modifiedMeta = "modifiedMeta" - ) - - // created collection - res, err := h(ctx, types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI)) - require.NoError(t, err) - contractID := GetMadeContractID(res.Events) - - // Given MsgModify - msg := types.NewMsgModify(addr1, contractID, defaultTokenType, defaultTokenIndex, types.NewChanges( - types.NewChange("name", modifiedTokenName), - types.NewChange("meta", modifiedMeta), - )) - - t.Log("Test with nonexistent token") - { - // When handle MsgModify - _, err := h(ctx, msg) - - // Then response is error - require.Error(t, err) - } - - t.Log("Test modify token") - { - // Given token - _, err = h(ctx, types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta)) - require.NoError(t, err) - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - _, err = h(ctx, types.NewMsgMintNFT(addr1, contractID, addr1, param)) - require.NoError(t, err) - - // When handle MsgModify - res, err = h(ctx, msg) - - // Then response is success - require.NoError(t, err) - // And events are returned - expectedEvents := sdk.Events{ - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute(types.AttributeKeyContractID, contractID)), - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute(types.AttributeKeyTokenID, defaultTokenID1)), - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute("name", modifiedTokenName)), - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute("meta", modifiedMeta)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String())), - } - verifyEventFunc(t, expectedEvents, res.Events) - } -} - -func TestHandleMsgModifyForTokenType(t *testing.T) { - ctx, h := cacheKeeper() - const ( - modifiedTokenName = "modifiedTokenName" - modifiedMeta = "modifiedMeta" - ) - - // created collection - res, err := h(ctx, types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI)) - require.NoError(t, err) - contractID := GetMadeContractID(res.Events) - - // Given MsgModify - msg := types.NewMsgModify(addr1, contractID, defaultTokenType, "", types.NewChanges( - types.NewChange("name", modifiedTokenName), - types.NewChange("meta", modifiedMeta), - )) - - t.Log("Test with nonexistent token type") - { - // When handle MsgModify - _, err := h(ctx, msg) - - // Then response is error - require.Error(t, err) - } - - t.Log("Test modify token type") - { - // Given token type - _, err = h(ctx, types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta)) - require.NoError(t, err) - - // When handle MsgModify - res, err = h(ctx, msg) - - // Then response is success - require.NoError(t, err) - // And events are returned - expectedEvents := sdk.Events{ - sdk.NewEvent(types.EventTypeModifyTokenType, sdk.NewAttribute(types.AttributeKeyContractID, contractID)), - sdk.NewEvent(types.EventTypeModifyTokenType, sdk.NewAttribute(types.AttributeKeyTokenType, defaultTokenType)), - sdk.NewEvent(types.EventTypeModifyTokenType, sdk.NewAttribute("name", modifiedTokenName)), - sdk.NewEvent(types.EventTypeModifyTokenType, sdk.NewAttribute("meta", modifiedMeta)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String())), - } - verifyEventFunc(t, expectedEvents, res.Events) - } -} diff --git a/x/collection/internal/handler/perm.go b/x/collection/internal/handler/perm.go deleted file mode 100644 index fc139a8dc6..0000000000 --- a/x/collection/internal/handler/perm.go +++ /dev/null @@ -1,39 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgGrant(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgGrantPermission) (*sdk.Result, error) { - err := keeper.GrantPermission(ctx, msg.From, msg.To, msg.Permission) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgRevoke(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgRevokePermission) (*sdk.Result, error) { - err := keeper.RevokePermission(ctx, msg.From, msg.Permission) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/perm_test.go b/x/collection/internal/handler/perm_test.go deleted file mode 100644 index f1c62dcca4..0000000000 --- a/x/collection/internal/handler/perm_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestHandleMsgGrant(t *testing.T) { - ctx, h, contractID := prepareCreateCollection(t) - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewIssuePermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "issue")), - } - verifyEventFunc(t, e, res.Events) - } - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewMintPermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "mint")), - } - verifyEventFunc(t, e, res.Events) - } - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewBurnPermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "burn")), - } - verifyEventFunc(t, e, res.Events) - } - { - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewModifyPermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "modify")), - } - verifyEventFunc(t, e, res.Events) - } - t.Log("Invalid contract id") - { - msg := types.NewMsgGrantPermission(addr1, "1234567890", addr2, types.NewModifyPermission()) - require.Error(t, msg.ValidateBasic()) - } -} - -func TestHandleMsgRevoke(t *testing.T) { - ctx, h, contractID := prepareCreateCollection(t) - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewIssuePermission()) - _, err := h(ctx, msg) - require.NoError(t, err) - - msg = types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewMintPermission()) - _, err = h(ctx, msg) - require.NoError(t, err) - - msg = types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewBurnPermission()) - _, err = h(ctx, msg) - require.NoError(t, err) - - msg = types.NewMsgGrantPermission(addr1, contractID, addr2, types.NewModifyPermission()) - _, err = h(ctx, msg) - require.NoError(t, err) - - { - msg := types.NewMsgRevokePermission(addr2, contractID, types.NewIssuePermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("perm", "issue")), - } - verifyEventFunc(t, e, res.Events) - } - { - msg := types.NewMsgRevokePermission(addr2, contractID, types.NewMintPermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("perm", "mint")), - } - verifyEventFunc(t, e, res.Events) - } - { - msg := types.NewMsgRevokePermission(addr2, contractID, types.NewBurnPermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("perm", "burn")), - } - verifyEventFunc(t, e, res.Events) - } - { - msg := types.NewMsgRevokePermission(addr2, contractID, types.NewModifyPermission()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("from", addr2.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("perm", "modify")), - } - verifyEventFunc(t, e, res.Events) - } - t.Log("Invalid contract id") - { - msg := types.NewMsgRevokePermission(addr1, "1234567890", types.NewModifyPermission()) - require.Error(t, msg.ValidateBasic()) - } -} diff --git a/x/collection/internal/handler/proxy.go b/x/collection/internal/handler/proxy.go deleted file mode 100644 index 4e288cc90e..0000000000 --- a/x/collection/internal/handler/proxy.go +++ /dev/null @@ -1,41 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgApprove(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgApprove) (*sdk.Result, error) { - err := keeper.SetApproved(ctx, msg.Proxy, msg.Approver) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Approver.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgDisapprove(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgDisapprove) (*sdk.Result, error) { - err := keeper.DeleteApproved(ctx, msg.Proxy, msg.Approver) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Approver.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/proxy_test.go b/x/collection/internal/handler/proxy_test.go deleted file mode 100644 index a8b84a3466..0000000000 --- a/x/collection/internal/handler/proxy_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package handler - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" -) - -func approve(t *testing.T, approver, proxy sdk.AccAddress, contractID string, ctx sdk.Context, h sdk.Handler) { - approveMsg := types.NewMsgApprove(approver, contractID, proxy) - _, err := h(ctx, approveMsg) - require.NoError(t, err) -} - -func TestHandleMsgApprove(t *testing.T) { - t.Log("implement me - ", t.Name()) -} -func TestHandleMsgDisapprove(t *testing.T) { - t.Log("implement me - ", t.Name()) -} - -func TestHandleApproveDisapprove(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err = h(ctx, msg) - require.NoError(t, err) - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg2 := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg2 = types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg3 := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err = h(ctx, msg3) - require.NoError(t, err) - msg4 := types.NewMsgMintFT(addr1, contractID, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - _, err = h(ctx, msg4) - require.NoError(t, err) - } - - msg := types.NewMsgTransferNFTFrom(addr2, contractID, addr1, addr2, defaultTokenID1) - _, err := h(ctx, msg) - require.Error(t, err) - - { - msg3 := types.NewMsgApprove(addr1, contractID, addr2) - _, err = h(ctx, msg3) - require.NoError(t, err) - } - - msg = types.NewMsgTransferNFTFrom(addr2, contractID, addr1, addr2, defaultTokenID1) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("operation_transfer_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - } - verifyEventFunc(t, e, res.Events) - - msg2 := types.NewMsgBurnNFTFrom(addr2, contractID, addr1, defaultTokenID2) - _, err = h(ctx, msg2) - require.Error(t, err) // addr2 does not have the burn permission - msg3 := types.NewMsgBurnFTFrom(addr2, contractID, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - _, err = h(ctx, msg3) - require.Error(t, err) // addr2 does not have the burn permission - - { - permission := types.NewBurnPermission() - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, permission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - msg2 = types.NewMsgBurnNFTFrom(addr2, contractID, addr1, defaultTokenID2) - res, err = h(ctx, msg2) - require.NoError(t, err) // addr2 does not have the burn permission - - e = sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("burn_nft_from", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("operation_burn_nft", sdk.NewAttribute("token_id", defaultTokenID2)), - } - verifyEventFunc(t, e, res.Events) - - msg3 = types.NewMsgBurnFTFrom(addr2, contractID, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - _, err = h(ctx, msg3) - require.NoError(t, err) - - { - permission := types.NewBurnPermission() - msg := types.NewMsgGrantPermission(addr1, contractID, addr2, permission) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - msg3 = types.NewMsgBurnFTFrom(addr2, contractID, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - res, err = h(ctx, msg3) - require.NoError(t, err) - e = sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("burn_ft_from", sdk.NewAttribute("amount", types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))).String())), - } - verifyEventFunc(t, e, res.Events) - - { - msg3 := types.NewMsgDisapprove(addr1, contractID, addr2) - _, err = h(ctx, msg3) - require.NoError(t, err) - } - - msg = types.NewMsgTransferNFTFrom(addr2, contractID, addr1, addr2, defaultTokenID1) - _, err = h(ctx, msg) - require.Error(t, err) - - msg2 = types.NewMsgBurnNFTFrom(addr2, contractID, addr1, defaultTokenID1) - _, err = h(ctx, msg2) - require.Error(t, err) - - msg3 = types.NewMsgBurnFTFrom(addr2, contractID, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - _, err = h(ctx, msg3) - require.Error(t, err) -} diff --git a/x/collection/internal/handler/transfer.go b/x/collection/internal/handler/transfer.go deleted file mode 100644 index 51558fdd8b..0000000000 --- a/x/collection/internal/handler/transfer.go +++ /dev/null @@ -1,75 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func handleMsgTransferFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgTransferFT) (*sdk.Result, error) { - err := keeper.TransferFT(ctx, msg.From, msg.To, msg.Amount...) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgTransferNFT(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgTransferNFT) (*sdk.Result, error) { - err := keeper.TransferNFT(ctx, msg.From, msg.To, msg.TokenIDs...) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgTransferFTFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgTransferFTFrom) (*sdk.Result, error) { - err := keeper.TransferFTFrom(ctx, msg.Proxy, msg.From, msg.To, msg.Amount...) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgTransferNFTFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgTransferNFTFrom) (*sdk.Result, error) { - err := keeper.TransferNFTFrom(ctx, msg.Proxy, msg.From, msg.To, msg.TokenIDs...) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/collection/internal/handler/transfer_test.go b/x/collection/internal/handler/transfer_test.go deleted file mode 100644 index 579203887e..0000000000 --- a/x/collection/internal/handler/transfer_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestHandleTransferFT(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err = h(ctx, msg) - require.NoError(t, err) - } - - msg := types.NewMsgTransferFT(addr1, contractID, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("transfer_ft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_ft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_ft", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_ft", sdk.NewAttribute("amount", types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)).String())), - } - verifyEventFunc(t, e, res.Events) -} - -func TestHandleTransferFTFrom(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueFT(addr1, addr1, contractID, defaultName, defaultMeta, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err = h(ctx, msg) - require.NoError(t, err) - msg2 := types.NewMsgApprove(addr1, contractID, addr2) - _, err = h(ctx, msg2) - require.NoError(t, err) - } - - msg := types.NewMsgTransferFTFrom(addr2, contractID, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("transfer_ft_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_ft_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("transfer_ft_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_ft_from", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_ft_from", sdk.NewAttribute("amount", types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)).String())), - } - verifyEventFunc(t, e, res.Events) -} - -func TestHandleTransferNFT(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err = h(ctx, msg) - require.NoError(t, err) - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg2 := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - } - - msg := types.NewMsgTransferNFT(addr1, contractID, addr2, defaultTokenID1) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("operation_transfer_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - } - verifyEventFunc(t, e, res.Events) -} - -func TestHandleTransferNFTFrom(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err = h(ctx, msg) - require.NoError(t, err) - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg2 := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg3 := types.NewMsgApprove(addr1, contractID, addr2) - _, err = h(ctx, msg3) - require.NoError(t, err) - } - - msg := types.NewMsgTransferNFTFrom(addr2, contractID, addr1, addr2, defaultTokenID1) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_nft_from", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("operation_transfer_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - } - verifyEventFunc(t, e, res.Events) -} - -func TestHandleTransferNFTChild(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - createMsg := types.NewMsgCreateCollection(addr1, defaultName, defaultMeta, defaultImgURI) - res, err := h(ctx, createMsg) - require.NoError(t, err) - contractID = GetMadeContractID(res.Events) - - msg := types.NewMsgIssueNFT(addr1, contractID, defaultName, defaultMeta) - _, err = h(ctx, msg) - require.NoError(t, err) - param := types.NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg2 := types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg2 = types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg2 = types.NewMsgMintNFT(addr1, contractID, addr1, param) - _, err = h(ctx, msg2) - require.NoError(t, err) - msg3 := types.NewMsgAttach(addr1, contractID, defaultTokenID1, defaultTokenID2) - _, err = h(ctx, msg3) - require.NoError(t, err) - msg3 = types.NewMsgAttach(addr1, contractID, defaultTokenID2, defaultTokenID3) - _, err = h(ctx, msg3) - require.NoError(t, err) - } - - msg := types.NewMsgTransferNFT(addr1, contractID, addr2, defaultTokenID1) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "collection")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("operation_transfer_nft", sdk.NewAttribute("token_id", defaultTokenID1)), - sdk.NewEvent("operation_transfer_nft", sdk.NewAttribute("token_id", defaultTokenID2)), - sdk.NewEvent("operation_transfer_nft", sdk.NewAttribute("token_id", defaultTokenID3)), - } - verifyEventFunc(t, e, res.Events) -} diff --git a/x/collection/internal/keeper/account.go b/x/collection/internal/keeper/account.go deleted file mode 100644 index f7064f7a37..0000000000 --- a/x/collection/internal/keeper/account.go +++ /dev/null @@ -1,91 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type AccountKeeper interface { - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) - GetOrNewAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) - SetAccount(ctx sdk.Context, acc types.Account) error - UpdateAccount(ctx sdk.Context, acc types.Account) error - GetBalance(ctx sdk.Context, tokenID string, addr sdk.AccAddress) (sdk.Int, error) -} - -var _ AccountKeeper = (*Keeper)(nil) - -func (k Keeper) GetBalance(ctx sdk.Context, tokenID string, addr sdk.AccAddress) (sdk.Int, error) { - acc, err := k.GetAccount(ctx, addr) - if err != nil { - return sdk.ZeroInt(), err - } - return acc.GetCoins().AmountOf(tokenID), nil -} - -func (k Keeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) { - acc = types.NewBaseAccountWithAddress(k.getContractID(ctx), addr) - if err = k.SetAccount(ctx, acc); err != nil { - return nil, err - } - return acc, nil -} - -func (k Keeper) SetAccount(ctx sdk.Context, acc types.Account) error { - store := ctx.KVStore(k.storeKey) - accKey := types.AccountKey(acc.GetContractID(), acc.GetAddress()) - if store.Has(accKey) { - return sdkerrors.Wrap(types.ErrAccountExist, acc.GetAddress().String()) - } - store.Set(accKey, k.cdc.MustMarshalBinaryBare(acc)) - - // Set Account if not exists yet - account := k.accountKeeper.GetAccount(ctx, acc.GetAddress()) - if account == nil { - account = k.accountKeeper.NewAccountWithAddress(ctx, acc.GetAddress()) - k.accountKeeper.SetAccount(ctx, account) - } - - return nil -} - -func (k Keeper) UpdateAccount(ctx sdk.Context, acc types.Account) error { - store := ctx.KVStore(k.storeKey) - accKey := types.AccountKey(acc.GetContractID(), acc.GetAddress()) - if !store.Has(accKey) { - return sdkerrors.Wrap(types.ErrAccountNotExist, acc.GetAddress().String()) - } - store.Set(accKey, k.cdc.MustMarshalBinaryBare(acc)) - return nil -} - -func (k Keeper) GetOrNewAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) { - acc, err = k.GetAccount(ctx, addr) - if err != nil { - acc, err = k.NewAccountWithAddress(ctx, addr) - if err != nil { - return nil, err - } - } - return acc, nil -} - -func (k Keeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) { - store := ctx.KVStore(k.storeKey) - accKey := types.AccountKey(k.getContractID(ctx), addr) - if !store.Has(accKey) { - return nil, sdkerrors.Wrap(types.ErrAccountNotExist, addr.String()) - } - bz := store.Get(accKey) - return k.mustDecodeAccount(bz), nil -} - -func (k Keeper) mustDecodeAccount(bz []byte) (acc types.Account) { - err := k.cdc.UnmarshalBinaryBare(bz, &acc) - if err != nil { - panic(err) - } - return -} diff --git a/x/collection/internal/keeper/account_test.go b/x/collection/internal/keeper/account_test.go deleted file mode 100644 index 39736de1c7..0000000000 --- a/x/collection/internal/keeper/account_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_GetAccountSupply(t *testing.T) { - ctx := cacheKeeper() - t.Log("Balance of addr1. Expect 0") - { - _, err := keeper.GetBalance(ctx, defaultTokenIDFT, addr1) - require.Error(t, err) - } - t.Log("Set tokens to addr1") - { - _, err := keeper.AddCoins(ctx, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)))) - require.NoError(t, err) - } - t.Log("Balance of addr1.") - { - balance, err := keeper.GetBalance(ctx, defaultTokenIDFT, addr1) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount), balance.Int64()) - } -} - -func verifyAccountFunc(t *testing.T, expected types.Account, actual types.Account) { - require.Equal(t, expected.GetContractID(), actual.GetContractID()) - require.Equal(t, expected.GetAddress(), actual.GetAddress()) - require.Equal(t, expected.GetCoins().String(), actual.GetCoins().String()) -} - -func TestKeeper_SetAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - expected := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, expected)) - } - t.Log("Compare Account") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.AccountKey(expected.GetContractID(), addr1)) - actual := keeper.mustDecodeAccount(bz) - verifyAccountFunc(t, expected, actual) - } -} - -func TestKeeper_GetAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Account") - expected := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.AccountKey(expected.GetContractID(), addr1), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Account") - { - actual, err := keeper.GetAccount(ctx, addr1) - require.NoError(t, err) - verifyAccountFunc(t, expected, actual) - } -} - -func TestKeeper_UpdateAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Update Account") - var expected types.Account - expected = types.NewBaseAccountWithAddress(defaultContractID, addr1) - expected = expected.SetCoins(types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.OneInt()))) - { - require.NoError(t, keeper.UpdateAccount(ctx, expected)) - } - t.Log("Compare Account") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.AccountKey(acc.GetContractID(), addr1)) - actual := keeper.mustDecodeAccount(bz) - verifyAccountFunc(t, expected, actual) - } -} - -func TestKeeper_GetOrNewAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Account") - expected := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.AccountKey(expected.GetContractID(), addr1), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Account addr1") - { - actual, err := keeper.GetOrNewAccount(ctx, addr1) - require.NoError(t, err) - verifyAccountFunc(t, expected, actual) - } - - expected = types.NewBaseAccountWithAddress(defaultContractID, addr2) - t.Log("Get Account addr2") - { - actual, err := keeper.GetOrNewAccount(ctx, addr2) - require.NoError(t, err) - verifyAccountFunc(t, expected, actual) - } -} diff --git a/x/collection/internal/keeper/bank.go b/x/collection/internal/keeper/bank.go deleted file mode 100644 index 0a5221be91..0000000000 --- a/x/collection/internal/keeper/bank.go +++ /dev/null @@ -1,99 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -// For the Token module -type BankKeeper interface { - GetCoins(ctx sdk.Context, addr sdk.AccAddress) types.Coins - HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) bool - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt types.Coins) error - SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) (types.Coins, error) - AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) (types.Coins, error) - SetCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) error -} - -var _ BankKeeper = (*Keeper)(nil) - -func (k Keeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) types.Coins { - acc, err := k.GetAccount(ctx, addr) - if err != nil { - return types.NewCoins() - } - return acc.GetCoins() -} - -func (k Keeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) bool { - return k.GetCoins(ctx, addr).IsAllGTE(amt) -} - -func (k Keeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt types.Coins) error { - if !amt.IsValid() { - return sdkerrors.Wrap(types.ErrInvalidCoin, "send amount must be positive") - } - - _, err := k.SubtractCoins(ctx, fromAddr, amt) - if err != nil { - return err - } - - _, err = k.AddCoins(ctx, toAddr, amt) - if err != nil { - return err - } - return nil -} - -func (k Keeper) SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) (types.Coins, error) { - if !amt.IsValid() { - return nil, sdkerrors.Wrap(types.ErrInvalidCoin, "amount must be positive") - } - - acc, err := k.GetAccount(ctx, addr) - if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInsufficientToken, "insufficient account funds[%s]; account has no coin", k.getContractID(ctx)) - } - oldCoins := acc.GetCoins() - - newCoins, hasNeg := oldCoins.SafeSub(amt) - if hasNeg { - return amt, sdkerrors.Wrapf(types.ErrInsufficientToken, "insufficient account funds[%s]; %s < %s", k.getContractID(ctx), oldCoins, amt) - } - - err = k.SetCoins(ctx, addr, newCoins) - - return newCoins, err -} - -func (k Keeper) AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) (types.Coins, error) { - if !amt.IsValid() { - return nil, sdkerrors.Wrap(types.ErrInvalidCoin, "amount must be positive") - } - - oldCoins := k.GetCoins(ctx, addr) - newCoins := oldCoins.Add(amt...) - - err := k.SetCoins(ctx, addr, newCoins) - return newCoins, err -} - -func (k Keeper) SetCoins(ctx sdk.Context, addr sdk.AccAddress, amt types.Coins) error { - if !amt.IsValid() { - return sdkerrors.Wrapf(types.ErrInvalidCoin, "invalid amount: %s", amt.String()) - } - - acc, err := k.GetOrNewAccount(ctx, addr) - if err != nil { - return err - } - - acc = acc.SetCoins(amt) - err = k.UpdateAccount(ctx, acc) - if err != nil { - return err - } - return nil -} diff --git a/x/collection/internal/keeper/bank_test.go b/x/collection/internal/keeper/bank_test.go deleted file mode 100644 index 98ba9256f4..0000000000 --- a/x/collection/internal/keeper/bank_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_SendCoins(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.SendCoins(ctx, addr3, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrap(types.ErrInsufficientToken, "insufficient account funds[abcdef01]; account has no coin").Error()) -} - -func TestKeeper_SetCoins(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - coins := types.Coins{types.Coin{Denom: defaultTokenIDFT, Amount: sdk.NewInt(-1)}} - require.EqualError(t, keeper.SetCoins(ctx, addr1, coins), sdkerrors.Wrapf(types.ErrInvalidCoin, "invalid amount: %s", coins.String()).Error()) -} diff --git a/x/collection/internal/keeper/burn.go b/x/collection/internal/keeper/burn.go deleted file mode 100644 index 00832bb634..0000000000 --- a/x/collection/internal/keeper/burn.go +++ /dev/null @@ -1,235 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type BurnKeeper interface { - BurnFT(ctx sdk.Context, from sdk.AccAddress, amount types.Coins) error - BurnNFT(ctx sdk.Context, from sdk.AccAddress, tokenIDs ...string) error - BurnFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, amount types.Coins) error - BurnNFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, tokenIDs ...string) error -} - -var _ BurnKeeper = (*Keeper)(nil) - -func (k Keeper) BurnFT(ctx sdk.Context, from sdk.AccAddress, amount types.Coins) error { - if err := k.burnFT(ctx, from, from, amount); err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - ), - }) - - return nil -} - -func (k Keeper) BurnFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, amount types.Coins) error { - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - if err := k.burnFT(ctx, proxy, from, amount); err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnFTFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - ), - }) - return nil -} - -func (k Keeper) burnFT(ctx sdk.Context, permissionOwner, tokenOwner sdk.AccAddress, amount types.Coins) error { - if err := k.isBurnable(ctx, permissionOwner, tokenOwner, amount); err != nil { - return err - } - - if err := k.BurnSupply(ctx, tokenOwner, amount); err != nil { - return err - } - return nil -} - -func (k Keeper) isBurnable(ctx sdk.Context, permissionOwner, tokenOwner sdk.AccAddress, amount types.Coins) error { - perm := types.NewBurnPermission() - if !k.HasPermission(ctx, permissionOwner, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", permissionOwner.String(), perm.String()) - } - - if !k.HasCoins(ctx, tokenOwner, amount) { - return sdkerrors.Wrapf(types.ErrInsufficientToken, "%v has not enough coins for %v", tokenOwner.String(), amount) - } - return nil -} - -func (k Keeper) BurnNFT(ctx sdk.Context, from sdk.AccAddress, tokenIDs ...string) error { - for _, tokenID := range tokenIDs { - if err := k.burnNFT(ctx, from, from, tokenID); err != nil { - return err - } - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnNFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - ), - }) - - for _, tokenID := range tokenIDs { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnNFT, - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - ), - }) - } - - return nil -} - -func (k Keeper) BurnNFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, tokenIDs ...string) error { - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - for _, tokenID := range tokenIDs { - if err := k.burnNFT(ctx, proxy, from, tokenID); err != nil { - return err - } - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnNFTFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - ), - }) - for _, tokenID := range tokenIDs { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnNFTFrom, - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - ), - }) - } - return nil -} - -func (k Keeper) burnNFT(ctx sdk.Context, permissionOwner, tokenOwner sdk.AccAddress, tokenID string) error { - token, err := k.GetNFT(ctx, tokenID) - if err != nil { - return err - } - - perm := types.NewBurnPermission() - if !k.HasPermission(ctx, permissionOwner, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", permissionOwner.String(), perm.String()) - } - - if !token.GetOwner().Equals(tokenOwner) { - return sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", tokenID, tokenOwner.String()) - } - - if parent, err := k.ParentOf(ctx, token.GetTokenID()); parent != nil || err != nil { - if err != nil { - return err - } - return sdkerrors.Wrapf(types.ErrBurnNonRootNFT, "TokenID(%s) has a parent", tokenID) - } - - err = k.burnNFTRecursive(ctx, token, tokenOwner) - if err != nil { - return err - } - - return nil -} - -func (k Keeper) burnNFTRecursive(ctx sdk.Context, token types.NFT, from sdk.AccAddress) error { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeOperationBurnNFT, - sdk.NewAttribute(types.AttributeKeyTokenID, token.GetTokenID()), - ), - }) - - children, err := k.ChildrenOf(ctx, token.GetTokenID()) - if err != nil { - return err - } - - for _, child := range children { - err = k.burnNFTRecursive(ctx, child.(types.NFT), from) - if err != nil { - return err - } - } - - parent, err := k.ParentOf(ctx, token.GetTokenID()) - if err != nil { - return err - } - if parent != nil { - _, err = k.detach(ctx, from, token.GetTokenID()) - if err != nil { - return err - } - } - - err = k.burnNFTInternal(ctx, token) - if err != nil { - return nil - } - - return nil -} - -func (k Keeper) burnNFTInternal(ctx sdk.Context, token types.NFT) error { - err := k.DeleteToken(ctx, token.GetTokenID()) - if err != nil { - return err - } - - if !k.HasNFTOwner(ctx, token.GetOwner(), token.GetTokenID()) { - return sdkerrors.Wrapf(types.ErrInsufficientSupply, "insufficient supply for token [%s]", k.getContractID(ctx)) - } - k.DeleteNFTOwner(ctx, token.GetOwner(), token.GetTokenID()) - k.increaseTokenTypeBurnCount(ctx, token.GetTokenType()) - return nil -} - -func (k Keeper) increaseTokenTypeBurnCount(ctx sdk.Context, tokenType string) { - store := ctx.KVStore(k.storeKey) - count := k.getTokenTypeBurnCount(ctx, tokenType) - count = count.Add(sdk.NewInt(1)) - - store.Set(types.TokenTypeBurnCount(k.getContractID(ctx), tokenType), k.cdc.MustMarshalBinaryBare(count)) -} - -func (k Keeper) getTokenTypeBurnCount(ctx sdk.Context, tokenType string) (count sdk.Int) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.TokenTypeBurnCount(k.getContractID(ctx), tokenType)) - if bz == nil { - return sdk.ZeroInt() - } - k.cdc.MustUnmarshalBinaryBare(bz, &count) - return count -} diff --git a/x/collection/internal/keeper/burn_test.go b/x/collection/internal/keeper/burn_test.go deleted file mode 100644 index 12923eb23a..0000000000 --- a/x/collection/internal/keeper/burn_test.go +++ /dev/null @@ -1,277 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func TestKeeper_BurnFT(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.NoError(t, keeper.BurnFT(ctx, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1))))) - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.BurnFT(ctx2, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr1.String(), types.NewBurnPermission().String()).Error()) - require.EqualError(t, keeper.BurnFT(ctx, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2.String(), types.NewBurnPermission().String()).Error()) - require.EqualError(t, keeper.BurnFT(ctx, addr3, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr3.String(), types.NewBurnPermission().String()).Error()) - require.EqualError(t, keeper.BurnFT(ctx, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)))), sdkerrors.Wrapf(types.ErrInsufficientToken, "%v has not enough coins for %v", addr1.String(), types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)).String()).Error()) - - require.NoError(t, keeper.MintFT(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1))))) - require.EqualError(t, keeper.BurnFT(ctx, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2, types.NewBurnPermission()).Error()) - require.EqualError(t, keeper.BurnFT(ctx, addr1, types.NewCoins(types.NewCoin("0000000200000000", sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrInsufficientToken, "%v has not enough coins for %v", addr1.String(), types.NewCoin("0000000200000000", sdk.NewInt(1)).String()).Error()) -} - -func TestKeeper_BurnFTFrom(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - prepareProxy(ctx, t) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.BurnFTFrom(ctx2, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), wrongContractID).Error()) - require.NoError(t, keeper.BurnFTFrom(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))))) - require.EqualError(t, keeper.BurnFTFrom(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrInsufficientToken, "%v has not enough coins for %v", addr2.String(), types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)).String()).Error()) - - require.NoError(t, keeper.MintFT(ctx, addr1, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1))))) - require.EqualError(t, keeper.BurnFTFrom(ctx, addr2, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2, types.NewBurnPermission()).Error()) - require.EqualError(t, keeper.BurnFTFrom(ctx, addr1, addr2, types.NewCoins(types.NewCoin("0000000200000000", sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrInsufficientToken, "%v has not enough coins for %v", addr2.String(), types.NewCoin("0000000200000000", sdk.NewInt(1)).String()).Error()) -} - -func TestKeeper_BurnNFT(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - i, err := keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTCount) - require.NoError(t, err) - require.Equal(t, int64(5), i.Int64()) - i, err = keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTMint) - require.NoError(t, err) - require.Equal(t, int64(5), i.Int64()) - i, err = keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTBurn) - require.NoError(t, err) - require.Equal(t, int64(0), i.Int64()) - - require.NoError(t, keeper.BurnNFT(ctx, addr1, defaultTokenID4)) - require.EqualError(t, keeper.BurnNFT(ctx, addr1, defaultTokenID4), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID4).Error()) - require.EqualError(t, keeper.BurnNFT(ctx, addr2, defaultTokenID4), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID4).Error()) - require.EqualError(t, keeper.BurnNFT(ctx, addr3, defaultTokenID4), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID4).Error()) - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.BurnNFT(ctx2, addr1, defaultTokenID4), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenID4).Error()) - - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - require.NoError(t, keeper.BurnNFT(ctx, addr1, defaultTokenID1)) - - i, err = keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTCount) - require.NoError(t, err) - require.Equal(t, int64(1), i.Int64()) - i, err = keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTMint) - require.NoError(t, err) - require.Equal(t, int64(5), i.Int64()) - i, err = keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTBurn) - require.NoError(t, err) - require.Equal(t, int64(4), i.Int64()) -} - -func TestKeeper_BurnNFTFrom(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - prepareProxy(ctx, t) - - require.NoError(t, keeper.BurnNFTFrom(ctx, addr1, addr2, defaultTokenID4)) - require.EqualError(t, keeper.BurnNFTFrom(ctx, addr1, addr2, defaultTokenID4), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID4).Error()) - require.EqualError(t, keeper.BurnNFTFrom(ctx, addr3, addr2, defaultTokenID4), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr3.String(), addr2.String(), defaultContractID).Error()) - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.BurnNFTFrom(ctx2, addr1, addr2, defaultTokenID4), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), wrongContractID).Error()) - - require.NoError(t, keeper.Attach(ctx, addr2, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr2, defaultTokenID2, defaultTokenID3)) - require.NoError(t, keeper.BurnNFTFrom(ctx, addr1, addr2, defaultTokenID1)) -} - -func TestMintBurn(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - const ( - wrongTokenID = "12345678" - ) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID2)) - require.EqualError(t, keeper.MintNFT(ctx2, addr1, types.NewNFT(defaultContractID2, wrongTokenID, defaultName, defaultMeta, addr1)), sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", defaultContractID2, wrongTokenID[:types.TokenTypeLength]).Error()) - require.EqualError(t, keeper.MintNFT(ctx, addr3, types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1)), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr3.String(), types.NewMintPermission().String()).Error()) - - require.NoError(t, keeper.BurnFT(ctx, addr1, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))))) - require.EqualError(t, keeper.BurnNFT(ctx, addr1, wrongTokenID), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, wrongTokenID).Error()) - require.EqualError(t, keeper.BurnNFT(ctx, addr3, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr3.String(), types.NewBurnPermission().String()).Error()) -} - -func composeNFTs(t *testing.T, ctx sdk.Context) { - prepareCollectionTokens(ctx, t) - - // attach token1 <- token2 (basic case) : success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - // attach token2 <- token3 (attach to a child): success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - // attach token1 <- token4 (attach to a root): success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID4)) -} - -func TestBurnRootComposedNFT(t *testing.T) { - ctx := cacheKeeper() - composeNFTs(t, ctx) - // token1 -+- token2 --- token3 - // +- token4 - - require.NoError(t, keeper.BurnNFT(ctx, addr1, defaultTokenID1)) - - _, err := keeper.GetNFT(ctx, defaultTokenID1) - require.Error(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID2) - require.Error(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID3) - require.Error(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID4) - require.Error(t, err) - - require.False(t, keeper.HasToken(ctx, defaultTokenID1)) - require.False(t, keeper.HasToken(ctx, defaultTokenID2)) - require.False(t, keeper.HasToken(ctx, defaultTokenID3)) - require.False(t, keeper.HasToken(ctx, defaultTokenID4)) -} - -func TestBurnNonRootComposedNFT(t *testing.T) { - // only the root tokens can be burned - ctx := cacheKeeper() - - composeNFTs(t, ctx) - // token1 -+- token2 --- token3 - // +- token4 - - require.Error(t, keeper.BurnNFT(ctx, addr1, defaultTokenID2)) - require.Error(t, keeper.BurnNFT(ctx, addr1, defaultTokenID3)) - require.Error(t, keeper.BurnNFT(ctx, addr1, defaultTokenID4)) - - _, err := keeper.GetNFT(ctx, defaultTokenID1) - require.NoError(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID2) - require.NoError(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID3) - require.NoError(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID4) - require.NoError(t, err) - - require.True(t, keeper.HasToken(ctx, defaultTokenID1)) - require.True(t, keeper.HasToken(ctx, defaultTokenID2)) - require.True(t, keeper.HasToken(ctx, defaultTokenID3)) - require.True(t, keeper.HasToken(ctx, defaultTokenID4)) -} - -func TestBurnNFTFromSuccess(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // success case - // addr1 has: burn permission, approved - // addr2 has: token - - // attach token1 <- token2 (basic case) : success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - // attach token2 <- token3 (attach to a child): success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - // attach token1 <- token4 (attach to a root): success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID4)) - - // transfer tokens to addr2 - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID1)) - require.NoError(t, keeper.TransferFT(ctx, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)))) - - // addr2 approves addr1 for the contractID - require.NoError(t, keeper.SetApproved(ctx, addr1, addr2)) - - // test burnNFTFrom - require.NoError(t, keeper.BurnNFTFrom(ctx, addr1, addr2, defaultTokenID1)) - require.NoError(t, keeper.BurnFTFrom(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))))) - - _, err := keeper.GetNFT(ctx, defaultTokenID1) - require.Error(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID2) - require.Error(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID3) - require.Error(t, err) - _, err = keeper.GetNFT(ctx, defaultTokenID4) - require.Error(t, err) - - balance, err := keeper.GetBalance(ctx, defaultTokenID1, addr1) - require.NoError(t, err) - require.Equal(t, int64(0), balance.Int64()) - balance, err = keeper.GetBalance(ctx, defaultTokenID2, addr1) - require.NoError(t, err) - require.Equal(t, int64(0), balance.Int64()) - balance, err = keeper.GetBalance(ctx, defaultTokenID3, addr1) - require.NoError(t, err) - require.Equal(t, int64(0), balance.Int64()) - balance, err = keeper.GetBalance(ctx, defaultTokenID4, addr1) - require.NoError(t, err) - require.Equal(t, int64(0), balance.Int64()) - balance, err = keeper.GetBalance(ctx, defaultTokenIDFT, addr1) - require.NoError(t, err) - require.Equal(t, int64(0), balance.Int64()) -} - -func TestBurnNFTFromFailure1(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // failure case1 - // addr1 has: burn permission, approved, token - // addr2 has: nothing - - // addr2 approves addr1 for the contractID - require.NoError(t, keeper.SetApproved(ctx, addr1, addr2)) - - // test burnNFTFrom, burnFTFrom fail - require.EqualError(t, keeper.BurnNFTFrom(ctx, addr1, addr2, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID1, addr2.String()).Error()) - require.EqualError(t, keeper.BurnFTFrom(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrInsufficientToken, "%v has not enough coins for %v", addr2.String(), types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)).String()).Error()) -} - -func TestBurnNFTFromFailure2(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // failure case2 - // addr1 has: burn permission (not approved) - // addr2 has: token - - // transfer tokens to addr2 - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID1)) - require.NoError(t, keeper.TransferFT(ctx, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))) - - // test burnNFTFrom fail - require.EqualError(t, keeper.BurnNFTFrom(ctx, addr1, addr2, defaultTokenID1), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), defaultContractID).Error()) - require.EqualError(t, keeper.BurnFTFrom(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), defaultContractID).Error()) -} - -func TestBurnNFTFromFailure3(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // failure case3 - // addr2 has: approved (no permission) - // addr3 has: token - - // transfer tokens to addr2 - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr3, defaultTokenID1)) - require.NoError(t, keeper.TransferFT(ctx, addr1, addr3, types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))) - // addr3 approves addr2 for the contractID - require.NoError(t, keeper.SetApproved(ctx, addr2, addr3)) - - // test burnNFTFrom fail - require.EqualError(t, keeper.BurnNFTFrom(ctx, addr2, addr3, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2.String(), types.NewBurnPermission().String()).Error()) - require.EqualError(t, keeper.BurnFTFrom(ctx, addr2, addr3, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(1)))), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2.String(), types.NewBurnPermission().String()).Error()) -} diff --git a/x/collection/internal/keeper/collection.go b/x/collection/internal/keeper/collection.go deleted file mode 100644 index 64074ca3eb..0000000000 --- a/x/collection/internal/keeper/collection.go +++ /dev/null @@ -1,133 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type CollectionKeeper interface { - CreateCollection(ctx sdk.Context, collection types.Collection, owner sdk.AccAddress) error - ExistCollection(ctx sdk.Context) bool - GetCollection(ctx sdk.Context) (collection types.Collection, err error) - SetCollection(ctx sdk.Context, collection types.Collection) error - UpdateCollection(ctx sdk.Context, collection types.Collection) error -} - -var _ CollectionKeeper = (*Keeper)(nil) - -func (k Keeper) CreateCollection(ctx sdk.Context, collection types.Collection, owner sdk.AccAddress) error { - err := k.SetCollection(ctx, collection) - if err != nil { - return err - } - k.SetSupply(ctx, types.DefaultSupply(collection.GetContractID())) - - perms := types.NewPermissions( - types.NewIssuePermission(), - types.NewMintPermission(), - types.NewBurnPermission(), - types.NewModifyPermission(), - ) - for _, perm := range perms { - k.AddPermission(ctx, owner, perm) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeCreateCollection, - sdk.NewAttribute(types.AttributeKeyContractID, collection.GetContractID()), - sdk.NewAttribute(types.AttributeKeyName, collection.GetName()), - sdk.NewAttribute(types.AttributeKeyOwner, owner.String()), - ), - sdk.NewEvent( - types.EventTypeGrantPermToken, - sdk.NewAttribute(types.AttributeKeyTo, owner.String()), - sdk.NewAttribute(types.AttributeKeyContractID, collection.GetContractID()), - ), - }) - for _, perm := range perms { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeGrantPermToken, - sdk.NewAttribute(types.AttributeKeyPerm, perm.String()), - ), - }) - } - - return nil -} - -func (k Keeper) ExistCollection(ctx sdk.Context) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.CollectionKey(k.getContractID(ctx))) -} - -func (k Keeper) GetCollection(ctx sdk.Context) (collection types.Collection, err error) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.CollectionKey(k.getContractID(ctx))) - if bz == nil { - return collection, sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - - collection = k.mustDecodeCollection(bz) - return collection, nil -} - -func (k Keeper) SetCollection(ctx sdk.Context, collection types.Collection) error { - store := ctx.KVStore(k.storeKey) - if store.Has(types.CollectionKey(collection.GetContractID())) { - return sdkerrors.Wrapf(types.ErrCollectionExist, "ContractID: %s", collection.GetContractID()) - } - - store.Set(types.CollectionKey(collection.GetContractID()), k.cdc.MustMarshalBinaryBare(collection)) - k.setNextTokenTypeFT(ctx, types.ReservedEmpty) - k.setNextTokenTypeNFT(ctx, types.ReservedEmptyNFT) - return nil -} - -func (k Keeper) UpdateCollection(ctx sdk.Context, collection types.Collection) error { - store := ctx.KVStore(k.storeKey) - if !store.Has(types.CollectionKey(collection.GetContractID())) { - return sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", collection.GetContractID()) - } - - store.Set(types.CollectionKey(collection.GetContractID()), k.cdc.MustMarshalBinaryBare(collection)) - return nil -} - -func (k Keeper) GetAllCollections(ctx sdk.Context) types.Collections { - var collections types.Collections - appendCollection := func(collection types.Collection) (stop bool) { - collections = append(collections, collection) - return false - } - k.iterateCollections(ctx, appendCollection) - return collections -} - -func (k Keeper) iterateCollections(ctx sdk.Context, process func(types.Collection) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.CollectionKey("")) - defer iter.Close() - for { - if !iter.Valid() { - return - } - val := iter.Value() - collection := k.mustDecodeCollection(val) - if process(collection) { - return - } - iter.Next() - } -} - -func (k Keeper) mustDecodeCollection(collectionByte []byte) types.Collection { - var collection types.Collection - err := k.cdc.UnmarshalBinaryBare(collectionByte, &collection) - if err != nil { - panic(err) - } - return collection -} diff --git a/x/collection/internal/keeper/collection_test.go b/x/collection/internal/keeper/collection_test.go deleted file mode 100644 index 8f1e8812ea..0000000000 --- a/x/collection/internal/keeper/collection_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" -) - -func TestKeeper_NewContractID(t *testing.T) { - ctx := cacheKeeper() - contractID := keeper.NewContractID(ctx) - require.Equal(t, len(contractID), 8) - contractID2 := keeper.NewContractID(ctx) - require.NotEqual(t, contractID, contractID2) -} - -func TestKeeper_CreateCollection(t *testing.T) { - ctx := cacheKeeper() - contractID := keeper.NewContractID(ctx) - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url"), addr1)) - require.EqualError(t, keeper.CreateCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url"), addr1), sdkerrors.Wrapf(types.ErrCollectionExist, "ContractID: %s", contractID).Error()) -} - -func TestKeeper_ExistCollection(t *testing.T) { - ctx := cacheKeeper() - contractID := keeper.NewContractID(ctx) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, contractID)) - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url"), addr1)) - require.True(t, keeper.ExistCollection(ctx)) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, "abcd1234")) - require.False(t, keeper.ExistCollection(ctx)) -} - -func TestKeeper_GetCollection(t *testing.T) { - ctx := cacheKeeper() - contractID := keeper.NewContractID(ctx) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, contractID)) - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url"), addr1)) - collection, err := keeper.GetCollection(ctx) - require.NoError(t, err) - require.Equal(t, collection.GetContractID(), contractID) - require.Equal(t, collection.GetName(), "MyCollection") - require.Equal(t, collection.GetBaseImgURI(), "base url") - - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, "abcd1234")) - _, err = keeper.GetCollection(ctx) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: abcd1234").Error()) -} - -func TestKeeper_SetCollection(t *testing.T) { - ctx := cacheKeeper() - contractID := keeper.NewContractID(ctx) - - require.NoError(t, keeper.SetCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url"))) - require.EqualError(t, keeper.SetCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url")), sdkerrors.Wrapf(types.ErrCollectionExist, "ContractID: %s", contractID).Error()) -} - -func TestKeeper_UpdateCollection(t *testing.T) { - ctx := cacheKeeper() - contractID := keeper.NewContractID(ctx) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, contractID)) - - require.EqualError(t, keeper.UpdateCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url")), sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", contractID).Error()) - require.NoError(t, keeper.SetCollection(ctx, types.NewCollection(contractID, "MyCollection", "meta", "base url"))) - require.NoError(t, keeper.UpdateCollection(ctx, types.NewCollection(contractID, "MyCollection2", "meta", "base url2"))) - - collection, err := keeper.GetCollection(ctx) - require.NoError(t, err) - require.Equal(t, collection.GetContractID(), contractID) - require.Equal(t, collection.GetName(), "MyCollection2") - require.Equal(t, collection.GetBaseImgURI(), "base url2") -} - -func TestKeeper_GetAllCollections(t *testing.T) { - ctx := cacheKeeper() - contractID1 := keeper.NewContractID(ctx) - contractID2 := keeper.NewContractID(ctx) - contractID3 := keeper.NewContractID(ctx) - - collections := keeper.GetAllCollections(ctx) - require.Equal(t, len(collections), 0) - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(contractID1, "MyCollection1", "meta1", "base url1"), addr1)) - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(contractID2, "MyCollection2", "meta2", "base url2"), addr1)) - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(contractID3, "MyCollection3", "meta3", "base url3"), addr1)) - - collections = keeper.GetAllCollections(ctx) - require.Equal(t, len(collections), 3) - require.Equal(t, collections[2].GetContractID(), contractID1) - require.Equal(t, collections[2].GetName(), "MyCollection1") - require.Equal(t, collections[2].GetMeta(), "meta1") - require.Equal(t, collections[2].GetBaseImgURI(), "base url1") - require.Equal(t, collections[1].GetContractID(), contractID2) - require.Equal(t, collections[1].GetName(), "MyCollection2") - require.Equal(t, collections[1].GetMeta(), "meta2") - require.Equal(t, collections[1].GetBaseImgURI(), "base url2") - require.Equal(t, collections[0].GetContractID(), contractID3) - require.Equal(t, collections[0].GetName(), "MyCollection3") - require.Equal(t, collections[0].GetMeta(), "meta3") - require.Equal(t, collections[0].GetBaseImgURI(), "base url3") -} diff --git a/x/collection/internal/keeper/composable.go b/x/collection/internal/keeper/composable.go deleted file mode 100644 index db7be93fb4..0000000000 --- a/x/collection/internal/keeper/composable.go +++ /dev/null @@ -1,417 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -var ChildExists = []byte{1} - -type ComposeKeeper interface { - Attach(ctx sdk.Context, from sdk.AccAddress, toTokenID string, tokenID string) error - AttachFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, toTokenID string, tokenID string) error - Detach(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, tokenID string) error - DetachFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, to sdk.AccAddress, tokenID string) error - RootOf(ctx sdk.Context, tokenID string) (types.NFT, error) - ParentOf(ctx sdk.Context, tokenID string) (types.NFT, error) - ChildrenOf(ctx sdk.Context, tokenID string) (types.Tokens, error) -} - -func (k Keeper) eventRootChanged(ctx sdk.Context, tokenID string) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeOperationRootChanged, - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - ), - }) - - children := k.getChildren(ctx, tokenID) - for _, child := range children { - k.eventRootChanged(ctx, child.GetTokenID()) - } -} - -func (k Keeper) Attach(ctx sdk.Context, from sdk.AccAddress, toTokenID string, tokenID string) error { - if err := k.attach(ctx, from, toTokenID, tokenID); err != nil { - return err - } - - newRoot, err := k.RootOf(ctx, toTokenID) - if err != nil { - return err - } - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeAttachToken, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyToTokenID, toTokenID), - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - sdk.NewAttribute(types.AttributeKeyOldRoot, tokenID), - sdk.NewAttribute(types.AttributeKeyNewRoot, newRoot.GetTokenID()), - ), - }) - - k.eventRootChanged(ctx, tokenID) - - return nil -} - -func (k Keeper) AttachFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, toTokenID string, tokenID string) error { - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - if err := k.attach(ctx, from, toTokenID, tokenID); err != nil { - return err - } - - newRoot, err := k.RootOf(ctx, toTokenID) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeAttachFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyToTokenID, toTokenID), - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - sdk.NewAttribute(types.AttributeKeyOldRoot, tokenID), - sdk.NewAttribute(types.AttributeKeyNewRoot, newRoot.GetTokenID()), - ), - }) - - k.eventRootChanged(ctx, tokenID) - - return nil -} - -func (k Keeper) attach(ctx sdk.Context, from sdk.AccAddress, parentID string, childID string) error { - store := ctx.KVStore(k.storeKey) - - if parentID == childID { - return sdkerrors.Wrapf(types.ErrCannotAttachToItself, "TokenID: %s", childID) - } - - childToken, err := k.GetNFT(ctx, childID) - if err != nil { - return err - } - - if !from.Equals(childToken.GetOwner()) { - return sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", childID, from.String()) - } - - toToken, err := k.GetNFT(ctx, parentID) - if err != nil { - return err - } - - if !from.Equals(toToken.GetOwner()) { - return sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", parentID, from.String()) - } - - // verify token should be a root - childToParentKey := types.TokenChildToParentKey(k.getContractID(ctx), childID) - if store.Has(childToParentKey) { - return sdkerrors.Wrapf(types.ErrTokenAlreadyAChild, "TokenID: %s", childID) - } - - // verify no circulation(toToken must not be a descendant of token) - rootOfToToken, err := k.RootOf(ctx, parentID) - if err != nil { - return err - } - parentToken, err := k.GetNFT(ctx, parentID) - if err != nil { - return err - } - if rootOfToToken.GetTokenID() == childID { - return sdkerrors.Wrapf(types.ErrCannotAttachToADescendant, "TokenID: %s, ToTokenID: %s", childID, parentID) - } - - if err := k.checkDepthAndWidth(ctx, rootOfToToken.GetTokenID(), parentID, childID); err != nil { - return err - } - - parentToChildKey := types.TokenParentToChildKey(k.getContractID(ctx), parentID, childID) - if store.Has(parentToChildKey) { - panic("token is already a child of some other") - } - - if !from.Equals(parentToken.GetOwner()) { - if err := k.moveNFToken(ctx, from, parentToken.GetOwner(), childToken); err != nil { - return err - } - } - - store.Set(childToParentKey, k.mustEncodeString(parentID)) - store.Set(parentToChildKey, k.mustEncodeString(childID)) - - return nil -} - -func (k Keeper) checkDepthAndWidth(ctx sdk.Context, rootID, parentID, childID string) error { - rootTable := k.GetDepthWidthTable(ctx, rootID) - childTable := k.GetDepthWidthTable(ctx, childID) - - parentDepth := k.GetDepthFromRoot(ctx, parentID) - - // root: token1 - token2 - token3 => depth of token3 is 2 - // child: token4 - token5 => length 2 - // attach result: token1 - token2 - token3 - token4 - token5 => depth 4 - // [depth of token3] + [len([token4,token5])] should be result depth - resultDepth := uint64(parentDepth + len(childTable)) - if resultDepth > k.GetParams(ctx).MaxComposableDepth { - return sdkerrors.Wrapf(types.ErrCompositionTooDeep, "Depth: %d", resultDepth) - } - - // root table: [1, 2, 3, 4, 5, 6, 7, 8] - // child table: [1, 3, 5, 7, 9] - // if the child is attached after depth 3, - // then the merged width table should be [1, 2, 3, 4, 5+1, 6+3, 7+5, 8+7, 9] - maxComposableWidth := k.GetParams(ctx).MaxComposableWidth - for curDepth, idx := parentDepth+1, 0; curDepth < len(rootTable) && idx < len(childTable); { - totalWidth := uint64(rootTable[curDepth] + childTable[idx]) - if totalWidth > maxComposableWidth { - return sdkerrors.Wrapf(types.ErrCompositionTooWide, "Width: %d (at depth %d)", totalWidth, curDepth) - } - curDepth++ - idx++ - } - - return nil -} - -// Gets the depth-width(count) table (array) -// -// lv0(1) lv1(2) lv2(3) lv3(2) lv4(1) -// token1 -+- token2 --- token4 --- token7 -// +- token3 -+- token5 --- token8 --- token9 -// +- token6 -// -// then returns [1, 2, 3, 2, 1] -// and len([1, 2, 3, 2, 1]) - 1 represents the depth of token1's children -func (k Keeper) GetDepthWidthTable(ctx sdk.Context, tokenID string) []int { - table := make([]int, 1) - table[0] = 1 - k.fillDepthWidthTable(ctx, tokenID, &table, 1) - return table -} - -func (k Keeper) fillDepthWidthTable(ctx sdk.Context, tokenID string, table *[]int, index int) { - count := 0 - - k.iterateChildren(ctx, tokenID, func(tokenID string) bool { - k.fillDepthWidthTable(ctx, tokenID, table, index+1) - count++ - return false - }) - - // if count = 0, the current is leaf, so doesn't need to insert a row - if count > 0 { - for len(*table) <= index { - *table = append(*table, 0) - } - // fills the children count of current depth - (*table)[index] += count - } -} - -func (k Keeper) GetDepthFromRoot(ctx sdk.Context, tokenID string) int { - store := ctx.KVStore(k.storeKey) - - depth := 0 - for nextID := tokenID; ; depth++ { - childToParentKey := types.TokenChildToParentKey(k.getContractID(ctx), nextID) - bz := store.Get(childToParentKey) - if bz == nil { - break - } - nextID = k.mustDecodeString(bz) - } - return depth -} - -func (k Keeper) Detach(ctx sdk.Context, from sdk.AccAddress, tokenID string) error { - oldRoot, err := k.RootOf(ctx, tokenID) - if err != nil { - return err - } - - parentTokenID, err := k.detach(ctx, from, tokenID) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeDetachToken, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyFromTokenID, parentTokenID), - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - sdk.NewAttribute(types.AttributeKeyOldRoot, oldRoot.GetTokenID()), - sdk.NewAttribute(types.AttributeKeyNewRoot, tokenID), - ), - }) - - k.eventRootChanged(ctx, tokenID) - - return nil -} - -// nolint:dupl -func (k Keeper) DetachFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, tokenID string) error { - oldRoot, err := k.RootOf(ctx, tokenID) - if err != nil { - return err - } - - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - parentTokenID, err := k.detach(ctx, from, tokenID) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeDetachFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyFromTokenID, parentTokenID), - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - sdk.NewAttribute(types.AttributeKeyOldRoot, oldRoot.GetTokenID()), - sdk.NewAttribute(types.AttributeKeyNewRoot, tokenID), - ), - }) - - k.eventRootChanged(ctx, tokenID) - - return nil -} - -func (k Keeper) detach(ctx sdk.Context, from sdk.AccAddress, childID string) (string, error) { - store := ctx.KVStore(k.storeKey) - - childToken, err := k.GetNFT(ctx, childID) - if err != nil { - return "", err - } - - if !from.Equals(childToken.GetOwner()) { - return "", sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", childID, from.String()) - } - - childToParentKey := types.TokenChildToParentKey(k.getContractID(ctx), childID) - if !store.Has(childToParentKey) { - return "", sdkerrors.Wrapf(types.ErrTokenNotAChild, "TokenID: %s", childID) - } - - bz := store.Get(childToParentKey) - parentID := k.mustDecodeString(bz) - - _, err = k.GetNFT(ctx, parentID) - if err != nil { - return "", err - } - - parentToChildKey := types.TokenParentToChildKey(k.getContractID(ctx), parentID, childID) - if !store.Has(parentToChildKey) { - panic("token is not a child of some other") - } - - store.Delete(childToParentKey) - store.Delete(parentToChildKey) - - return parentID, nil -} - -func (k Keeper) RootOf(ctx sdk.Context, tokenID string) (types.NFT, error) { - store := ctx.KVStore(k.storeKey) - - token, err := k.GetNFT(ctx, tokenID) - if err != nil { - return nil, err - } - - for childToParentKey := types.TokenChildToParentKey(k.getContractID(ctx), token.GetTokenID()); store.Has(childToParentKey); { - bz := store.Get(childToParentKey) - parentTokenID := k.mustDecodeString(bz) - - token, err = k.GetNFT(ctx, parentTokenID) - if err != nil { - return nil, err - } - childToParentKey = types.TokenChildToParentKey(k.getContractID(ctx), token.GetTokenID()) - } - - return token, nil -} - -func (k Keeper) ParentOf(ctx sdk.Context, tokenID string) (types.NFT, error) { - store := ctx.KVStore(k.storeKey) - - token, err := k.GetNFT(ctx, tokenID) - if err != nil { - return nil, err - } - childToParentKey := types.TokenChildToParentKey(k.getContractID(ctx), token.GetTokenID()) - if store.Has(childToParentKey) { - bz := store.Get(childToParentKey) - parentTokenID := k.mustDecodeString(bz) - - return k.GetNFT(ctx, parentTokenID) - } - return nil, nil -} - -func (k Keeper) ChildrenOf(ctx sdk.Context, tokenID string) (types.Tokens, error) { - _, err := k.GetNFT(ctx, tokenID) - if err != nil { - return nil, err - } - tokens := k.getChildren(ctx, tokenID) - - return tokens, nil -} - -func (k Keeper) getChildren(ctx sdk.Context, parentID string) (tokens types.Tokens) { - getToken := func(tokenID string) bool { - token, err := k.GetNFT(ctx, tokenID) - if err != nil { - panic(err) - } - tokens = append(tokens, token) - return false - } - - k.iterateChildren(ctx, parentID, getToken) - - return tokens -} - -func (k Keeper) iterateChildren(ctx sdk.Context, parentID string, process func(string) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.TokenParentToChildSubKey(k.getContractID(ctx), parentID)) - defer iter.Close() - for { - if !iter.Valid() { - return - } - val := iter.Value() - tokenID := k.mustDecodeString(val) - if process(tokenID) { - return - } - iter.Next() - } -} diff --git a/x/collection/internal/keeper/composable_test.go b/x/collection/internal/keeper/composable_test.go deleted file mode 100644 index d5cd57ebd1..0000000000 --- a/x/collection/internal/keeper/composable_test.go +++ /dev/null @@ -1,491 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func TestKeeper_Attach(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID1), sdkerrors.Wrapf(types.ErrCannotAttachToItself, "TokenID: %s", defaultTokenID1).Error()) - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID6), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID6).Error()) - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.Attach(ctx2, addr1, defaultTokenID1, defaultTokenID2), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenID2).Error()) - require.EqualError(t, keeper.Attach(ctx, addr2, defaultTokenID1, defaultTokenID2), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %v", defaultTokenID2, addr2.String()).Error()) - - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID6, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID6).Error()) - require.EqualError(t, keeper.Attach(ctx, addr2, defaultTokenID1, defaultTokenID5), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID1, addr2.String()).Error()) - - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID3, defaultTokenID2), sdkerrors.Wrapf(types.ErrTokenAlreadyAChild, "TokenID: %s", defaultTokenID2).Error()) - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID1), sdkerrors.Wrapf(types.ErrCannotAttachToADescendant, "TokenID: %s, ToTokenID: %s", defaultTokenID1, defaultTokenID2).Error()) -} - -func TestKeeper_AttachFrom(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.AttachFrom(ctx, addr1, addr2, defaultTokenID1, defaultTokenID2), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), defaultContractID).Error()) - prepareProxy(ctx, t) - require.NoError(t, keeper.AttachFrom(ctx, addr1, addr2, defaultTokenID1, defaultTokenID2)) -} - -func TestKeeper_Detach(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.Detach(ctx, addr1, defaultTokenID6), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID6).Error()) - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.Detach(ctx2, addr1, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenID1).Error()) - require.EqualError(t, keeper.Detach(ctx, addr2, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID1, addr2.String()).Error()) - require.EqualError(t, keeper.Detach(ctx, addr1, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotAChild, "TokenID: %s", defaultTokenID1).Error()) - require.EqualError(t, keeper.Detach(ctx, addr1, defaultTokenIDFT), sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", defaultTokenIDFT).Error()) - - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Detach(ctx, addr1, defaultTokenID2)) -} - -func TestKeeper_DetachFrom(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.DetachFrom(ctx, addr1, addr2, defaultTokenID2), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), defaultContractID).Error()) - prepareProxy(ctx, t) - require.NoError(t, keeper.Attach(ctx, addr2, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.DetachFrom(ctx, addr1, addr2, defaultTokenID2)) -} - -func TestKeeper_RootOf(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - _, err := keeper.RootOf(ctx, defaultTokenID6) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID6).Error()) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - _, err = keeper.RootOf(ctx2, defaultTokenID1) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenID1).Error()) - - _, err = keeper.RootOf(ctx, defaultTokenIDFT) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", defaultTokenIDFT).Error()) - - nft, err := keeper.RootOf(ctx, defaultTokenID1) - require.NoError(t, err) - require.Equal(t, nft.GetContractID(), defaultContractID) - require.Equal(t, nft.GetTokenID(), defaultTokenID1) - - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - - nft, err = keeper.RootOf(ctx, defaultTokenID3) - require.NoError(t, err) - require.Equal(t, nft.GetContractID(), defaultContractID) - require.Equal(t, nft.GetTokenID(), defaultTokenID1) -} - -func TestKeeper_ParentOf(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - _, err := keeper.ParentOf(ctx, defaultTokenID6) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID6).Error()) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - _, err = keeper.ParentOf(ctx2, defaultTokenID1) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenID1).Error()) - - _, err = keeper.ParentOf(ctx, defaultTokenIDFT) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", defaultTokenIDFT).Error()) - - nft, err := keeper.ParentOf(ctx, defaultTokenID1) - require.NoError(t, err) - require.Equal(t, nft, nil) - - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - - nft, err = keeper.ParentOf(ctx, defaultTokenID3) - require.NoError(t, err) - require.Equal(t, nft.GetContractID(), defaultContractID) - require.Equal(t, nft.GetTokenID(), defaultTokenID2) -} - -func TestKeeper_ChildrenOf(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - _, err := keeper.ChildrenOf(ctx, defaultTokenID6) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID6).Error()) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - _, err = keeper.ChildrenOf(ctx2, defaultTokenID1) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenID1).Error()) - - _, err = keeper.ChildrenOf(ctx, defaultTokenIDFT) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", defaultTokenIDFT).Error()) - - tokens, err := keeper.ChildrenOf(ctx, defaultTokenID1) - require.NoError(t, err) - require.Equal(t, len(tokens), 0) - - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID4)) - - tokens, err = keeper.ChildrenOf(ctx, defaultTokenID1) - require.NoError(t, err) - require.Equal(t, len(tokens), 2) - require.Equal(t, tokens[0].GetTokenID(), defaultTokenID2) - require.Equal(t, tokens[1].GetTokenID(), defaultTokenID4) - - tokens, err = keeper.ChildrenOf(ctx, defaultTokenID2) - require.NoError(t, err) - require.Equal(t, len(tokens), 1) - require.Equal(t, tokens[0].GetTokenID(), defaultTokenID3) -} - -func TestAttachDetachScenario(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // - // attach success cases - // - - // attach token1 <- token2 (basic case) : success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - - // attach token2 <- token3 (attach to a child): success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - - // attach token1 <- token4 (attach to a root): success - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID4)) - - // verify the relations - - // root of token1 is token1 - rootOfToken1, err1 := keeper.RootOf(ctx, defaultTokenID1) - require.NoError(t, err1) - require.Equal(t, rootOfToken1.GetTokenID(), defaultTokenID1) - - // root of token2 is token1 - rootOfToken2, err2 := keeper.RootOf(ctx, defaultTokenID2) - require.NoError(t, err2) - require.Equal(t, rootOfToken2.GetTokenID(), defaultTokenID1) - - // root of token3 is token1 - rootOfToken3, err3 := keeper.RootOf(ctx, defaultTokenID3) - require.NoError(t, err3) - require.Equal(t, rootOfToken3.GetTokenID(), defaultTokenID1) - - // root of token4 is token1 - rootOfToken4, err4 := keeper.RootOf(ctx, defaultTokenID4) - require.NoError(t, err4) - require.Equal(t, rootOfToken4.GetTokenID(), defaultTokenID1) - - // parent of token1 is nil - parentOfToken1, err5 := keeper.ParentOf(ctx, defaultTokenID1) - require.NoError(t, err5) - require.Nil(t, parentOfToken1) - - // parent of token2 is token1 - parentOfToken2, err6 := keeper.ParentOf(ctx, defaultTokenID2) - require.NoError(t, err6) - require.Equal(t, parentOfToken2.GetTokenID(), defaultTokenID1) - - // parent of token3 is token2 - parentOfToken3, err7 := keeper.ParentOf(ctx, defaultTokenID3) - require.NoError(t, err7) - require.Equal(t, parentOfToken3.GetTokenID(), defaultTokenID2) - - // parent of token4 is token1 - parentOfToken4, err8 := keeper.ParentOf(ctx, defaultTokenID4) - require.NoError(t, err8) - require.Equal(t, parentOfToken4.GetTokenID(), defaultTokenID1) - - // children of token1 are token2, token4 - childrenOfToken1, err9 := keeper.ChildrenOf(ctx, defaultTokenID1) - require.NoError(t, err9) - require.Equal(t, len(childrenOfToken1), 2) - require.True(t, (childrenOfToken1[0].GetTokenID() == defaultTokenID2 && childrenOfToken1[1].GetTokenID() == defaultTokenID4) || (childrenOfToken1[0].GetTokenID() == defaultTokenID4 && childrenOfToken1[1].GetTokenID() == defaultTokenID2)) - - // child of token2 is token3 - childrenOfToken2, err10 := keeper.ChildrenOf(ctx, defaultTokenID2) - require.NoError(t, err10) - require.Equal(t, len(childrenOfToken2), 1) - require.True(t, childrenOfToken2[0].GetTokenID() == defaultTokenID3) - - // child of token3 is empty - childrenOfToken3, err11 := keeper.ChildrenOf(ctx, defaultTokenID3) - require.NoError(t, err11) - require.Equal(t, len(childrenOfToken3), 0) - - // child of token4 is empty - childrenOfToken4, err12 := keeper.ChildrenOf(ctx, defaultTokenID4) - require.NoError(t, err12) - require.Equal(t, len(childrenOfToken4), 0) - - // query failure cases - _, err := keeper.ParentOf(ctx, defaultTokenIDFT) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", defaultTokenIDFT).Error()) - - // - // attach error cases - // - - // attach non-root token : failure - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2), sdkerrors.Wrapf(types.ErrTokenAlreadyAChild, "TokenID: %s", defaultTokenID2).Error()) - - // attach non-exist token : failure - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID8), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID8).Error()) - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID8, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID8).Error()) - - // attach non-mine token : failure - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID5), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID5, addr1.String()).Error()) - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID5, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID5, addr1.String()).Error()) - - // attach to itself : failure - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID1), sdkerrors.Wrapf(types.ErrCannotAttachToItself, "TokenID: %s", defaultTokenID1).Error()) - - // attach to a descendant : failure - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID1), sdkerrors.Wrapf(types.ErrCannotAttachToADescendant, "TokenID: %s, ToTokenID: %s", defaultTokenID1, defaultTokenID2).Error()) - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID3, defaultTokenID1), sdkerrors.Wrapf(types.ErrCannotAttachToADescendant, "TokenID: %s, ToTokenID: %s", defaultTokenID1, defaultTokenID3).Error()) - require.EqualError(t, keeper.Attach(ctx, addr1, defaultTokenID4, defaultTokenID1), sdkerrors.Wrapf(types.ErrCannotAttachToADescendant, "TokenID: %s, ToTokenID: %s", defaultTokenID1, defaultTokenID4).Error()) - - // - // detach error cases - // - - // detach not a child : failure - require.EqualError(t, keeper.Detach(ctx, addr1, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotAChild, "TokenID: %s", defaultTokenID1).Error()) - - // detach non-mine token : failure - require.EqualError(t, keeper.Detach(ctx, addr1, defaultTokenID5), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID5, addr1.String()).Error()) - - // detach non-exist token : failure - require.EqualError(t, keeper.Detach(ctx, addr1, defaultTokenID8), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID8).Error()) - - // - // detach success cases - // - - // detach single child - require.NoError(t, keeper.Detach(ctx, addr1, defaultTokenID4)) - - // detach a child having child - require.NoError(t, keeper.Detach(ctx, addr1, defaultTokenID2)) - - // detach child - require.NoError(t, keeper.Detach(ctx, addr1, defaultTokenID3)) - - // - // verify the relations - // - // parent of token2 is nil - parentOfToken2, err6 = keeper.ParentOf(ctx, defaultTokenID2) - require.NoError(t, err6) - require.Nil(t, parentOfToken2) - - // parent of token3 is nil - parentOfToken3, err7 = keeper.ParentOf(ctx, defaultTokenID3) - require.NoError(t, err7) - require.Nil(t, parentOfToken3) - - // parent of token4 is nil - parentOfToken4, err8 = keeper.ParentOf(ctx, defaultTokenID4) - require.NoError(t, err8) - require.Nil(t, parentOfToken4) - - // children of token1 is empty - childrenOfToken1, err1 = keeper.ChildrenOf(ctx, defaultTokenID1) - require.NoError(t, err1) - require.Equal(t, len(childrenOfToken1), 0) - - // owner of token3 is addr1 - token3, err13 := keeper.GetToken(ctx, defaultTokenID3) - require.NoError(t, err13) - - require.Equal(t, (token3.(types.NFT)).GetOwner(), addr1) -} - -func setupNFTs(t *testing.T, ctx sdk.Context) { - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, "name", "{}", defaultImgURI), addr1)) - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID2, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID3, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID4, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID5, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID6, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID7, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID8, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID9, defaultName, defaultMeta, addr1))) -} - -func TestGetDepthWidthTable(t *testing.T) { - ctx := cacheKeeper() - - setupNFTs(t, ctx) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID3)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID4)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID5)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID6)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID3, defaultTokenID7)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID3, defaultTokenID8)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID7, defaultTokenID9)) - - // +- token4 - // +- token5 - // token1 -+- token2 -+- token6 - // | - // +- token3 -+- token7 --- token9 - // +- token8 - - var table []int - table = keeper.GetDepthWidthTable(ctx, defaultTokenID1) - require.Equal(t, []int{1, 2, 5, 1}, table) - - table = keeper.GetDepthWidthTable(ctx, defaultTokenID2) - require.Equal(t, []int{1, 3}, table) - - table = keeper.GetDepthWidthTable(ctx, defaultTokenID3) - require.Equal(t, []int{1, 2, 1}, table) -} - -func TestGetCurrentDepthFromRoot(t *testing.T) { - ctx := cacheKeeper() - - setupNFTs(t, ctx) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID3)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID4)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID3, defaultTokenID5)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID3, defaultTokenID6)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID4, defaultTokenID7)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID5, defaultTokenID8)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID8, defaultTokenID9)) - - // token1 -+- token2 --- token4 --- token7 - // +- token3 -+- token5 --- token8 --- token9 - // +- token6 - - // the depth of token1 should be 0 - require.Equal(t, 0, keeper.GetDepthFromRoot(ctx, defaultTokenID1)) - - // the depth of token2, token3 should be 1 - require.Equal(t, 1, keeper.GetDepthFromRoot(ctx, defaultTokenID2)) - require.Equal(t, 1, keeper.GetDepthFromRoot(ctx, defaultTokenID3)) - - // the depth of token4, token5, token6 should be - require.Equal(t, 2, keeper.GetDepthFromRoot(ctx, defaultTokenID4)) - require.Equal(t, 2, keeper.GetDepthFromRoot(ctx, defaultTokenID5)) - require.Equal(t, 2, keeper.GetDepthFromRoot(ctx, defaultTokenID6)) - - // the depth of token7, token8 should be 3 - require.Equal(t, 3, keeper.GetDepthFromRoot(ctx, defaultTokenID7)) - require.Equal(t, 3, keeper.GetDepthFromRoot(ctx, defaultTokenID8)) - - // the depth of token9 should be 4 - require.Equal(t, 4, keeper.GetDepthFromRoot(ctx, defaultTokenID9)) -} - -// nolint:dupl -func TestCheckDepth(t *testing.T) { - ctx := cacheKeeper() - keeper.SetParams(ctx, types.NewParams(4, 4)) // Sets the max composable width/depth to 4 - - setupNFTs(t, ctx) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID3, defaultTokenID4)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID5, defaultTokenID6)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID5, defaultTokenID7)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID6, defaultTokenID8)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID8, defaultTokenID9)) - - // Given two composed tokens - // token1 --- token2 --- token3 --- token4 - // - // token5 -+- token6 --- token8 --- token9 - // +- token7 - // - // Sets the max composable width/depth to 4 - - // if token5 is attached to token2 then, - // - // token1 --- token2 -+- token3 --- token4 - // +- token5 -+- token6 --- token8 --- token9 - // +- token7 - // deepest depth is 5 (path: token1-token2-token5-token6-token8-token9) - err := keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID5) - require.Error(t, err) - - // if token5 is attached to token1 then, - // - // token1 -+- token2 --- token3 --- token4 - // +- token5 -+- token6 --- token8 --- token9 - // +- token7 - // deepest depth is 4 (path: token1-token5-token6-token8-token9) - err = keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID5) - require.NoError(t, err) -} - -// nolint:dupl -func TestCheckWidth(t *testing.T) { - ctx := cacheKeeper() - keeper.SetParams(ctx, types.NewParams(4, 4)) // Sets the max composable width/depth to 4 - - setupNFTs(t, ctx) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID4)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID5)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID6, defaultTokenID7)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID6, defaultTokenID8)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID7, defaultTokenID9)) - - // Given two composed tokens - // +- token3 - // +- token4 - // token1 -+- token2 -+- token5 - // - // token6 -+- token7 --- token9 - // +- token8 - // - // Sets the max composable width/depth to 4 - - // if token6 is attached to token1 then, - // - // +- token3 - // +- token4 - // token1 -+- token2 -+- token5 - // | - // +- token6 -+- token7 --- token9 - // +- token8 - // - // widest width is 5 - err := keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID6) - require.Error(t, err) - - // if token6 is attached to token2 then, - // - // +- token3 - // +- token4 - // token1 -+- token2 -+- token5 - // +- token6 -+- token7 --- token9 - // +- token8 - // - // widest width is 4 - err = keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID6) - require.NoError(t, err) -} diff --git a/x/collection/internal/keeper/issue.go b/x/collection/internal/keeper/issue.go deleted file mode 100644 index 671c24b606..0000000000 --- a/x/collection/internal/keeper/issue.go +++ /dev/null @@ -1,71 +0,0 @@ -package keeper - -import ( - "strconv" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type IssueKeeper interface { - IssueFT(ctx sdk.Context, owner sdk.AccAddress, token types.FT, amount sdk.Int) error - IssueNFT(ctx sdk.Context, owner sdk.AccAddress, tokenType string) error -} - -func (k Keeper) IssueFT(ctx sdk.Context, owner, to sdk.AccAddress, token types.FT, amount sdk.Int) error { - if !k.ExistCollection(ctx) { - return sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - err := k.SetToken(ctx, token) - if err != nil { - return err - } - - err = k.MintSupply(ctx, to, types.NewCoins(types.NewCoin(token.GetTokenID(), amount))) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeIssueFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyName, token.GetName()), - sdk.NewAttribute(types.AttributeKeyTokenID, token.GetTokenID()), - sdk.NewAttribute(types.AttributeKeyOwner, owner.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyMintable, strconv.FormatBool(token.GetMintable())), - sdk.NewAttribute(types.AttributeKeyDecimals, token.GetDecimals().String()), - ), - }) - - return nil -} - -func (k Keeper) IssueNFT(ctx sdk.Context, tokenType types.TokenType, owner sdk.AccAddress) error { - if !k.ExistCollection(ctx) { - return sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - - err := k.SetTokenType(ctx, tokenType) - if err != nil { - return err - } - - mintPerm := types.NewMintPermission() - k.AddPermission(ctx, owner, mintPerm) - burnPerm := types.NewBurnPermission() - k.AddPermission(ctx, owner, burnPerm) - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeIssueNFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyTokenType, tokenType.GetTokenType()), - ), - }) - - return nil -} diff --git a/x/collection/internal/keeper/issue_test.go b/x/collection/internal/keeper/issue_test.go deleted file mode 100644 index 4aaa0d1fb3..0000000000 --- a/x/collection/internal/keeper/issue_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" -) - -func TestKeeper_IssueFT(t *testing.T) { - ctx := cacheKeeper() - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, "name", defaultMeta, defaultImgURI), addr1)) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.IssueFT(ctx2, addr1, addr1, types.NewFT(wrongContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(1), true), sdk.NewInt(defaultAmount)), sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", wrongContractID).Error()) - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(1), true), sdk.NewInt(defaultAmount))) - require.EqualError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(1), true), sdk.NewInt(defaultAmount)), sdkerrors.Wrapf(types.ErrTokenExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenIDFT).Error()) -} - -func TestKeeper_IssueNFT(t *testing.T) { - ctx := cacheKeeper() - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, "name", defaultMeta, defaultImgURI), addr1)) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.IssueNFT(ctx2, types.NewBaseTokenType(wrongContractID, defaultTokenType, defaultName, defaultMeta), addr1), sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", wrongContractID).Error()) - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - require.EqualError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1), sdkerrors.Wrapf(types.ErrTokenTypeExist, "ContractID: %s, TokenType: %s", defaultContractID, defaultTokenType).Error()) -} diff --git a/x/collection/internal/keeper/keeper.go b/x/collection/internal/keeper/keeper.go deleted file mode 100644 index cc5255907d..0000000000 --- a/x/collection/internal/keeper/keeper.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params/subspace" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" -) - -type Keeper struct { - accountKeeper types.AccountKeeper - contractKeeper contract.Keeper - storeKey sdk.StoreKey - paramsSpace subspace.Subspace - cdc *codec.Codec -} - -func NewKeeper( - cdc *codec.Codec, - accountKeeper types.AccountKeeper, - contractKeeper contract.Keeper, - paramsSpace subspace.Subspace, - storeKey sdk.StoreKey, -) Keeper { - return Keeper{ - accountKeeper: accountKeeper, - contractKeeper: contractKeeper, - storeKey: storeKey, - paramsSpace: paramsSpace.WithKeyTable(types.ParamKeyTable()), - cdc: cdc, - } -} -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -func (k Keeper) NewContractID(ctx sdk.Context) string { - return k.contractKeeper.NewContractID(ctx) -} - -func (k Keeper) HasContractID(ctx sdk.Context) bool { - return k.contractKeeper.HasContractID(ctx, k.getContractID(ctx)) -} - -func (k Keeper) getContractID(ctx sdk.Context) string { - contractI := ctx.Context().Value(contract.CtxKey{}) - if contractI == nil { - panic("contract id does not set on the context") - } - return contractI.(string) -} - -func (k Keeper) UnmarshalJSON(bz []byte, ptr interface{}) error { - return k.cdc.UnmarshalJSON(bz, ptr) -} - -func (k Keeper) MarshalJSON(o interface{}) ([]byte, error) { - return k.cdc.MarshalJSON(o) -} - -func (k Keeper) MarshalJSONIndent(o interface{}) ([]byte, error) { - return k.cdc.MarshalJSONIndent(o, "", " ") -} - -func (k Keeper) mustEncodeString(str string) []byte { - return k.cdc.MustMarshalBinaryBare(str) -} - -func (k Keeper) mustDecodeString(bz []byte) (str string) { - k.cdc.MustUnmarshalBinaryBare(bz, &str) - return str -} diff --git a/x/collection/internal/keeper/keeper_test.go b/x/collection/internal/keeper/keeper_test.go deleted file mode 100644 index 26b9036e84..0000000000 --- a/x/collection/internal/keeper/keeper_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package keeper - -import ( - "context" - "os" - "testing" - - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - defaultName = "name" - defaultMeta = "{}" - defaultContractID = "abcdef01" - defaultContractID2 = "abcdef02" - wrongContractID = "abcd1234" - defaultImgURI = "img-uri" - defaultDecimals = 6 - defaultAmount = 1000 - defaultTokenType = "10000001" - defaultTokenType2 = "10000002" - defaultTokenType3 = "10000003" - defaultTokenType4 = "10000004" - defaultTokenIndex = "00000001" - defaultTokenID1 = defaultTokenType + defaultTokenIndex - defaultTokenID2 = defaultTokenType + "00000002" - defaultTokenID3 = defaultTokenType + "00000003" - defaultTokenID4 = defaultTokenType + "00000004" - defaultTokenID5 = defaultTokenType + "00000005" - defaultTokenID6 = defaultTokenType + "00000006" - defaultTokenID7 = defaultTokenType + "00000007" - defaultTokenID8 = defaultTokenType + "00000008" - defaultTokenID9 = defaultTokenType + "00000009" - wrongTokenID = defaultTokenType2 + "00000001" - defaultTokenIDFT = "0000000100000000" - defaultTokenIDFT2 = "0000000200000000" - defaultTokenIDFT3 = "0000000300000000" - defaultTokenIDFT4 = "0000000400000000" -) - -var ( - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr3 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) -) - -var ( - ms store.CommitMultiStore - ctx sdk.Context - keeper Keeper -) - -func setup() { - println("setup") - ctx, ms, keeper = TestKeeper() -} - -func TestMain(m *testing.M) { - setup() - ret := m.Run() - os.Exit(ret) -} - -func cacheKeeper() sdk.Context { - msCache := ms.CacheMultiStore() - ctx = ctx.WithMultiStore(msCache) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID)) - return ctx -} - -func TestKeeper_MarshalJSONLogger(t *testing.T) { - ctx := cacheKeeper() - dummy := struct { - Key string - Value string - }{ - Key: "key", - Value: "value", - } - bz, err := keeper.MarshalJSON(dummy) - require.NoError(t, err) - - dummy2 := struct { - Key string - Value string - }{} - - err = keeper.UnmarshalJSON(bz, &dummy2) - require.NoError(t, err) - require.Equal(t, dummy.Key, dummy2.Key) - require.Equal(t, dummy.Value, dummy2.Value) - logger := keeper.Logger(ctx) - logger.Info("test", dummy, dummy2) -} - -func prepareCollectionTokens(ctx sdk.Context, t *testing.T) { - // prepare collection - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, "name", "{}", - defaultImgURI), addr1)) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID2)) - require.NoError(t, keeper.CreateCollection(ctx2, types.NewCollection(defaultContractID2, "name", "{}", - defaultImgURI), addr1)) - - // issue 6 tokens - // token1 = contract1id1 by addr1 - // token2 = contract1id2 by addr1 - // token3 = contract1id3 by addr1 - // token4 = contract1id4 by addr1 - // token5 = contract2id5 by addr1 - // token6 = contract1id6 by addr2 - // token7 = contract1 by addr1 - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - require.NoError(t, keeper.IssueNFT(ctx2, types.NewBaseTokenType(defaultContractID2, defaultTokenType, defaultName, defaultMeta), addr1)) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID2, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID3, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID4, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx2, addr1, types.NewNFT(defaultContractID2, defaultTokenID1, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.GrantPermission(ctx, addr1, addr2, types.NewMintPermission())) - require.NoError(t, keeper.MintNFT(ctx, addr2, types.NewNFT(defaultContractID, defaultTokenID5, defaultName, defaultMeta, addr2))) - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(1), true), sdk.NewInt(defaultAmount))) -} - -func prepareProxy(ctx sdk.Context, t *testing.T) { - require.NoError(t, keeper.SetApproved(ctx, addr1, addr2)) - require.NoError(t, keeper.SetApproved(ctx, addr2, addr1)) - require.NoError(t, keeper.TransferFT(ctx, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount)))) - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID1)) - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID2)) - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID3)) - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID4)) -} - -func verifyTokenFunc(t *testing.T, expected types.Token, actual types.Token) { - switch e := expected.(type) { - case types.FT: - a, ok := actual.(types.FT) - require.True(t, ok) - require.Equal(t, e.GetContractID(), a.GetContractID()) - require.Equal(t, e.GetName(), a.GetName()) - require.Equal(t, e.GetTokenID(), a.GetTokenID()) - require.Equal(t, e.GetTokenType(), a.GetTokenType()) - require.Equal(t, e.GetTokenIndex(), a.GetTokenIndex()) - require.Equal(t, e.GetDecimals(), a.GetDecimals()) - require.Equal(t, e.GetMintable(), a.GetMintable()) - case types.NFT: - a, ok := actual.(types.NFT) - require.True(t, ok) - require.Equal(t, e.GetContractID(), a.GetContractID()) - require.Equal(t, e.GetName(), a.GetName()) - require.Equal(t, e.GetTokenID(), a.GetTokenID()) - require.Equal(t, e.GetTokenType(), a.GetTokenType()) - require.Equal(t, e.GetTokenIndex(), a.GetTokenIndex()) - require.Equal(t, e.GetOwner(), a.GetOwner()) - default: - panic("never happen") - } -} - -func verifyTokenTypeFunc(t *testing.T, expected types.TokenType, actual types.TokenType) { - require.Equal(t, expected.GetName(), actual.GetName()) - require.Equal(t, expected.GetTokenType(), actual.GetTokenType()) -} diff --git a/x/collection/internal/keeper/mint.go b/x/collection/internal/keeper/mint.go deleted file mode 100644 index 5ccc71a1f7..0000000000 --- a/x/collection/internal/keeper/mint.go +++ /dev/null @@ -1,115 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type MintKeeper interface { - MintFT(ctx sdk.Context, from, to sdk.AccAddress, amount types.Coins) error - MintNFT(ctx sdk.Context, from sdk.AccAddress, token types.NFT) error -} - -func (k Keeper) MintFT(ctx sdk.Context, from, to sdk.AccAddress, amount types.Coins) error { - for _, coin := range amount { - token, err := k.GetToken(ctx, coin.Denom) - if err != nil { - return err - } - if err := k.isMintable(ctx, token, from); err != nil { - return err - } - } - err := k.MintSupply(ctx, to, amount) - if err != nil { - return err - } - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeMintFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - ), - }) - return nil -} - -func (k Keeper) MintNFT(ctx sdk.Context, from sdk.AccAddress, token types.NFT) error { - if !k.HasTokenType(ctx, token.GetTokenType()) { - return sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", k.getContractID(ctx), token.GetTokenType()) - } - - perm := types.NewMintPermission() - if !k.HasPermission(ctx, from, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", from.String(), perm.String()) - } - - err := k.mintNFTInternal(ctx, token) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeMintNFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyName, token.GetName()), - sdk.NewAttribute(types.AttributeKeyTokenID, token.GetTokenID()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, token.GetOwner().String()), - ), - }) - - return nil -} - -func (k Keeper) mintNFTInternal(ctx sdk.Context, token types.NFT) error { - err := k.SetToken(ctx, token) - if err != nil { - return err - } - - if k.HasNFTOwner(ctx, token.GetOwner(), token.GetTokenID()) { - return sdkerrors.Wrapf(types.ErrTokenExist, "ContractID: %s, TokenID: %s", k.getContractID(ctx), token.GetTokenID()) - } - k.AddNFTOwner(ctx, token.GetOwner(), token.GetTokenID()) - k.increaseTokenTypeMintCount(ctx, token.GetTokenType()) - return nil -} - -func (k Keeper) increaseTokenTypeMintCount(ctx sdk.Context, tokenType string) { - store := ctx.KVStore(k.storeKey) - count := k.getTokenTypeMintCount(ctx, tokenType) - count = count.Add(sdk.NewInt(1)) - - store.Set(types.TokenTypeMintCount(k.getContractID(ctx), tokenType), k.cdc.MustMarshalBinaryBare(count)) -} - -func (k Keeper) getTokenTypeMintCount(ctx sdk.Context, tokenType string) (count sdk.Int) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.TokenTypeMintCount(k.getContractID(ctx), tokenType)) - if bz == nil { - return sdk.ZeroInt() - } - k.cdc.MustUnmarshalBinaryBare(bz, &count) - return count -} - -func (k Keeper) isMintable(ctx sdk.Context, token types.Token, from sdk.AccAddress) error { - ft, ok := token.(types.FT) - if !ok { - return sdkerrors.Wrapf(types.ErrTokenNotMintable, "ContractID: %s, TokenID: %s", k.getContractID(ctx), token.GetTokenID()) - } - - if !ft.GetMintable() { - return sdkerrors.Wrapf(types.ErrTokenNotMintable, "ContractID: %s, TokenID: %s", k.getContractID(ctx), token.GetTokenID()) - } - perm := types.NewMintPermission() - if !k.HasPermission(ctx, from, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", from.String(), perm.String()) - } - return nil -} diff --git a/x/collection/internal/keeper/mint_test.go b/x/collection/internal/keeper/mint_test.go deleted file mode 100644 index a5ffc676d2..0000000000 --- a/x/collection/internal/keeper/mint_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" -) - -func TestKeeper_MintFT(t *testing.T) { - ctx := cacheKeeper() - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, "name", defaultMeta, defaultImgURI), addr1)) - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(1), true), sdk.NewInt(defaultAmount))) - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT2, defaultName, defaultMeta, sdk.NewInt(1), true), sdk.NewInt(defaultAmount))) - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT3, defaultName, defaultMeta, sdk.NewInt(1), false), sdk.NewInt(defaultAmount))) - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.MintFT(ctx2, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)))), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenIDFT).Error()) - require.EqualError(t, keeper.MintFT(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT4, sdk.NewInt(10)))), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenIDFT4).Error()) - require.EqualError(t, keeper.MintFT(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT3, sdk.NewInt(10)))), sdkerrors.Wrapf(types.ErrTokenNotMintable, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenIDFT3).Error()) - require.EqualError(t, keeper.MintFT(ctx, addr2, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)))), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2.String(), types.NewMintPermission()).Error()) - require.EqualError(t, keeper.MintFT(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenID1, sdk.NewInt(10)))), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID1).Error()) - - require.NoError(t, keeper.MintFT(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(10))))) - require.NoError(t, keeper.MintFT(ctx, addr1, addr2, types.NewCoins(types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)), types.NewCoin(defaultTokenIDFT2, sdk.NewInt(20))))) -} - -func TestKeeper_MintNFT(t *testing.T) { - ctx := cacheKeeper() - - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, "name", defaultMeta, defaultImgURI), addr1)) - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - - require.EqualError(t, keeper.MintNFT(ctx, addr2, types.NewNFT(defaultContractID, defaultTokenID1, "sword", defaultMeta, addr1)), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2.String(), types.NewMintPermission()).Error()) - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.MintNFT(ctx2, addr1, types.NewNFT(wrongContractID, defaultTokenID1, "sword", defaultMeta, addr1)), sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", wrongContractID, defaultTokenType).Error()) - require.EqualError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, wrongTokenID, "sword", defaultMeta, addr1)), sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", defaultContractID, defaultTokenType2).Error()) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID1, "sword", defaultMeta, addr1))) -} diff --git a/x/collection/internal/keeper/modify.go b/x/collection/internal/keeper/modify.go deleted file mode 100644 index 712507d148..0000000000 --- a/x/collection/internal/keeper/modify.go +++ /dev/null @@ -1,152 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func (k Keeper) Modify(ctx sdk.Context, owner sdk.AccAddress, tokenType, tokenIndex string, - changes types.Changes) error { - if tokenType != "" { - if tokenIndex != "" { - return k.modifyToken(ctx, owner, tokenType+tokenIndex, changes) - } - return k.modifyTokenType(ctx, owner, tokenType, changes) - } - if tokenIndex == "" { - return k.modifyCollection(ctx, owner, changes) - } - return types.ErrTokenIndexWithoutType -} - -// nolint:dupl -func (k Keeper) modifyCollection(ctx sdk.Context, owner sdk.AccAddress, changes types.Changes) error { - collection, err := k.GetCollection(ctx) - if err != nil { - return err - } - modifyPerm := types.NewModifyPermission() - if !k.HasPermission(ctx, owner, modifyPerm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", owner.String(), modifyPerm.String()) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyCollection, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - ), - }) - - for _, change := range changes { - switch change.Field { - case types.AttributeKeyName: - collection.SetName(change.Value) - case types.AttributeKeyMeta: - collection.SetMeta(change.Value) - case types.AttributeKeyBaseImgURI: - collection.SetBaseImgURI(change.Value) - default: - return sdkerrors.Wrapf(types.ErrInvalidChangesField, "Field: %s", change.Field) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyCollection, - sdk.NewAttribute(change.Field, change.Value), - ), - }) - } - err = k.UpdateCollection(ctx, collection) - if err != nil { - return err - } - return nil -} - -// nolint:dupl -func (k Keeper) modifyTokenType(ctx sdk.Context, owner sdk.AccAddress, tokenTypeID string, - changes types.Changes) error { - tokenType, err := k.GetTokenType(ctx, tokenTypeID) - if err != nil { - return err - } - modifyPerm := types.NewModifyPermission() - if !k.HasPermission(ctx, owner, modifyPerm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", owner.String(), modifyPerm.String()) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyTokenType, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyTokenType, tokenType.GetTokenType()), - ), - }) - - for _, change := range changes { - switch change.Field { - case types.AttributeKeyName: - tokenType.SetName(change.Value) - case types.AttributeKeyMeta: - tokenType.SetMeta(change.Value) - default: - return sdkerrors.Wrapf(types.ErrInvalidChangesField, "Field: %s", change.Field) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyTokenType, - sdk.NewAttribute(change.Field, change.Value), - ), - }) - } - err = k.UpdateTokenType(ctx, tokenType) - if err != nil { - return err - } - return nil -} - -// nolint:dupl -func (k Keeper) modifyToken(ctx sdk.Context, owner sdk.AccAddress, tokenID string, - changes types.Changes) error { - token, err := k.GetToken(ctx, tokenID) - if err != nil { - return err - } - modifyPerm := types.NewModifyPermission() - if !k.HasPermission(ctx, owner, modifyPerm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", owner.String(), modifyPerm.String()) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyToken, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyTokenID, token.GetTokenID()), - ), - }) - - for _, change := range changes { - switch change.Field { - case types.AttributeKeyName: - token.SetName(change.Value) - case types.AttributeKeyMeta: - token.SetMeta(change.Value) - default: - return sdkerrors.Wrapf(types.ErrInvalidChangesField, "Field: %s", change.Field) - } - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyToken, - sdk.NewAttribute(change.Field, change.Value), - ), - }) - } - err = k.UpdateToken(ctx, token) - if err != nil { - return err - } - return nil -} diff --git a/x/collection/internal/keeper/modify_test.go b/x/collection/internal/keeper/modify_test.go deleted file mode 100644 index 5d984ed072..0000000000 --- a/x/collection/internal/keeper/modify_test.go +++ /dev/null @@ -1,218 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" -) - -const nonExistentID = "1234abcd" - -func TestModifyCollection(t *testing.T) { - const ( - modifiedName = "modifiedName" - modifiedURI = "modifiedURI" - modifiedMeta = "modifiedMeta" - ) - changes := types.NewChanges( - types.NewChange("name", modifiedName), - types.NewChange("base_img_uri", modifiedURI), - types.NewChange("meta", modifiedMeta), - ) - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // Given collection and permission - collection, err := keeper.GetCollection(ctx) - require.NoError(t, err) - modifyPermission := types.NewModifyPermission() - keeper.AddPermission(ctx, addr1, modifyPermission) - - t.Log("Test to modify collection") - { - // When modify collection - require.NoError(t, keeper.modifyCollection(ctx, addr1, changes)) - - // Then collection is modified - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.CollectionKey(collection.GetContractID())) - actual := keeper.mustDecodeCollection(bz) - require.Equal(t, modifiedName, actual.GetName()) - require.Equal(t, modifiedURI, actual.GetBaseImgURI()) - require.Equal(t, modifiedMeta, actual.GetMeta()) - } - t.Log("Test with nonexistent contract") - { - // Given nonexistent contract, When modify collection name with invalid contract, Then error is occurred - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, nonExistentID)) - require.EqualError(t, keeper.modifyCollection(ctx2, addr1, changes), - sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", nonExistentID).Error()) - } - t.Log("Test without permission") - { - // Given user does not have permission - invalidUser := addr2 - - // When modify collection name with invalid permission, Then error is occurred - require.EqualError(t, keeper.modifyCollection(ctx, invalidUser, changes), - sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", invalidUser.String(), modifyPermission.String()).Error()) - } -} - -func TestModifyTokenType(t *testing.T) { - const modifiedName = "modifiedName" - const modifiedURI = "modifiedURI" - const modifiedMeta = "modifiedMeta" - - validChanges := types.NewChanges( - types.NewChange("name", modifiedName), - types.NewChange("meta", modifiedMeta), - ) - invalidChanges := types.NewChanges( - types.NewChange("base_img_uri", modifiedURI), - ) - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // Given collection and permission - modifyPermission := types.NewModifyPermission() - keeper.AddPermission(ctx, addr1, modifyPermission) - - t.Log("Test to modify token type with valid fields") - { - // When modify token type name - require.NoError(t, keeper.modifyTokenType(ctx, addr1, defaultTokenType, validChanges)) - - // Then collection name is modified - actual, err := keeper.GetTokenType(ctx, defaultTokenType) - require.NoError(t, err) - require.Equal(t, modifiedName, actual.GetName()) - } - t.Log("Test to modify token type with invalid fields") - { - require.EqualError(t, keeper.modifyTokenType(ctx, addr1, defaultTokenType, invalidChanges), - sdkerrors.Wrap(types.ErrInvalidChangesField, "Field: base_img_uri").Error()) - } - t.Log("Test with nonexistent contract") - { - // Given nonexistent token type, When modify token type name with invalid contract, Then error is occurred - require.EqualError(t, keeper.modifyTokenType(ctx, addr1, nonExistentID, validChanges), - sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", defaultContractID, nonExistentID).Error()) - } - t.Log("Test without permission") - { - // Given user does not have permission - invalidUser := addr2 - - // When modify token type name with invalid permission, Then error is occurred - require.EqualError(t, keeper.modifyTokenType(ctx, invalidUser, defaultTokenType, validChanges), - sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", invalidUser.String(), modifyPermission.String()).Error()) - } -} - -func TestModifyToken(t *testing.T) { - const modifiedName = "modifiedName" - const modifiedURI = "modifiedURI" - const modifiedMeta = "modifiedMeta" - - validChanges := types.NewChanges( - types.NewChange("name", modifiedName), - types.NewChange("meta", modifiedMeta), - ) - invalidChanges := types.NewChanges( - types.NewChange("base_img_uri", modifiedURI), - ) - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - // Given collection and permission - modifyPermission := types.NewModifyPermission() - keeper.AddPermission(ctx, addr1, modifyPermission) - // And token - token, err := keeper.GetToken(ctx, defaultTokenID1) - require.NoError(t, err) - - t.Log("Test to modify token with valid changes") - { - // When modify token name - require.NoError(t, keeper.modifyToken(ctx, addr1, token.GetTokenID(), validChanges)) - - // Then token name is modified - actual, err := keeper.GetToken(ctx, token.GetTokenID()) - require.NoError(t, err) - require.Equal(t, modifiedName, actual.GetName()) - } - t.Log("Test to modify token with invalid changes") - { - require.EqualError(t, keeper.modifyToken(ctx, addr1, token.GetTokenID(), invalidChanges), - sdkerrors.Wrap(types.ErrInvalidChangesField, "Field: base_img_uri").Error()) - } - t.Log("Test with nonexistent contract") - { - // Given nonexistent token id, When modify token name with invalid contract, Then error is occurred - require.EqualError(t, keeper.modifyToken(ctx, addr1, nonExistentID, validChanges), - sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", token.GetContractID(), nonExistentID).Error()) - } - t.Log("Test without permission") - { - // Given user does not have permission - invalidUser := addr2 - - // When modify token name with invalid permission, Then error is occurred - require.EqualError(t, keeper.modifyToken(ctx, invalidUser, token.GetTokenID(), validChanges), - sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", invalidUser.String(), modifyPermission.String()).Error()) - } -} - -func TestModify(t *testing.T) { - const modifiedName = "modifiedName" - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - changes := types.NewChanges( - types.NewChange("name", modifiedName), - ) - // Given permission - modifyPermission := types.NewModifyPermission() - keeper.AddPermission(ctx, addr1, modifyPermission) - - t.Logf("Test to modify name of collection to %s", modifiedName) - { - // When modify collection name - require.NoError(t, keeper.Modify(ctx, addr1, "", "", changes)) - - // Then collection name is modified - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.CollectionKey(defaultContractID)) - actual := keeper.mustDecodeCollection(bz) - require.Equal(t, modifiedName, actual.GetName()) - } - t.Logf("Test to modify name of token type to %s", modifiedName) - { - // When modify token type name - require.NoError(t, keeper.Modify(ctx, addr1, defaultTokenType, "", changes)) - - // Then token type name is modified - actual, err := keeper.GetTokenType(ctx, defaultTokenType) - require.NoError(t, err) - require.Equal(t, modifiedName, actual.GetName()) - } - t.Logf("Test to modify name of token to %s", modifiedName) - { - // When modify token name - require.NoError(t, keeper.Modify(ctx, addr1, defaultTokenType, defaultTokenIndex, changes)) - - // Then token name is modified - actual, err := keeper.GetToken(ctx, defaultTokenID1) - require.NoError(t, err) - require.Equal(t, modifiedName, actual.GetName()) - } - t.Log("Test with only token index not token type") - { - // When modify token name, Then error is occurred - require.EqualError(t, keeper.Modify(ctx, addr1, "", defaultTokenIndex, changes), types.ErrTokenIndexWithoutType.Error()) - } -} diff --git a/x/collection/internal/keeper/msg_encoder.go b/x/collection/internal/keeper/msg_encoder.go deleted file mode 100644 index f898434465..0000000000 --- a/x/collection/internal/keeper/msg_encoder.go +++ /dev/null @@ -1,291 +0,0 @@ -package keeper - -// import ( -// "encoding/json" - -// sdk "github.com/cosmos/cosmos-sdk/types" -// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -// "github.com/line/lbm-sdk/v2/x/collection/internal/types" -// "github.com/line/lbm-sdk/v2/x/wasm" -// ) - -// func NewMsgEncodeHandler(collectionKeeper Keeper) wasm.EncodeHandler { -// return func(jsonMsg json.RawMessage) ([]sdk.Msg, error) { -// var wasmCustomMsg types.WasmCustomMsg -// err := json.Unmarshal(jsonMsg, &wasmCustomMsg) -// if err != nil { -// return nil, err -// } - -// switch types.MsgRoute(wasmCustomMsg.Route) { -// case types.RCreateCollection: -// return handleMsgCreateCollection(wasmCustomMsg.Data) -// case types.RIssueNFT: -// return handleMsgIssueNFT(wasmCustomMsg.Data) -// case types.RIssueFT: -// return handleMsgIssueFT(wasmCustomMsg.Data) -// case types.RMintNFT: -// return handleMsgMintNFT(wasmCustomMsg.Data) -// case types.RMintFT: -// return handleMsgMintFT(wasmCustomMsg.Data) -// case types.RBurnNFT: -// return handleMsgBurnNFT(wasmCustomMsg.Data) -// case types.RBurnNFTFrom: -// return handleMsgBurnNFTFrom(wasmCustomMsg.Data) -// case types.RBurnFT: -// return handleMsgBurnFT(wasmCustomMsg.Data) -// case types.RBurnFTFrom: -// return handleMsgBurnFTFrom(wasmCustomMsg.Data) -// case types.RTransferNFT: -// return handleMsgTransferNFT(wasmCustomMsg.Data) -// case types.RTransferNFTFrom: -// return handleMsgTransferNFTFrom(wasmCustomMsg.Data) -// case types.RTransferFT: -// return handleMsgTransferFT(wasmCustomMsg.Data) -// case types.RTransferFTFrom: -// return handleMsgTransferFTFrom(wasmCustomMsg.Data) -// case types.RModify: -// return handleMsgModify(wasmCustomMsg.Data) -// case types.RApprove: -// return handleMsgApprove(wasmCustomMsg.Data) -// case types.RDisapprove: -// return handleMsgDisapprove(wasmCustomMsg.Data) -// case types.RGrantPerm: -// return handleMsgGrantPerm(wasmCustomMsg.Data) -// case types.RRevokePerm: -// return handleMsgRevokePerm(wasmCustomMsg.Data) -// case types.RAttach: -// return handleMsgAttach(wasmCustomMsg.Data) -// case types.RDetach: -// return handleMsgDetach(wasmCustomMsg.Data) -// case types.RAttachFrom: -// return handleMsgAttachFrom(wasmCustomMsg.Data) -// case types.RDetachFrom: -// return handleMsgDetachFrom(wasmCustomMsg.Data) -// default: -// return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized Msg route: %T", wasmCustomMsg.Route) -// } -// } -// } - -// func handleMsgCreateCollection(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgCreateCollection -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgIssueNFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgIssueNFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgIssueFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgIssueFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// if msg.Decimals.Int64() < 0 || msg.Decimals.Int64() > 18 { -// return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "invalid decimals. 0 <= decimals <= 18") -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgMintNFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgMintNFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgMintFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgMintFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgBurnNFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgBurnNFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgBurnNFTFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgBurnNFTFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgBurnFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgBurnFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgBurnFTFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgBurnFTFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgTransferNFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgTransferNFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgTransferNFTFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgTransferNFTFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgTransferFT(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgTransferFT -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgTransferFTFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgTransferFTFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgModify(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgModify -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgApprove(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgApprove -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgDisapprove(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgDisapprove -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgGrantPerm(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgGrantPermission -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgRevokePerm(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgRevokePermission -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgAttach(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgAttach -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgDetach(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgDetach -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgAttachFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgAttachFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgDetachFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgDetachFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } - -// return []sdk.Msg{msg}, nil -// } diff --git a/x/collection/internal/keeper/msg_encoder_test.go b/x/collection/internal/keeper/msg_encoder_test.go deleted file mode 100644 index 24e4413027..0000000000 --- a/x/collection/internal/keeper/msg_encoder_test.go +++ /dev/null @@ -1,311 +0,0 @@ -package keeper - -// import ( -// "encoding/json" -// "fmt" -// "testing" - -// sdk "github.com/cosmos/cosmos-sdk/types" -// "github.com/line/lbm-sdk/v2/x/collection/internal/types" -// "github.com/stretchr/testify/assert" -// "github.com/stretchr/testify/require" -// ) - -// func Test_Encode(t *testing.T) { -// encodeHandler := NewMsgEncodeHandler(keeper) - -// testContractName := "test_collection" -// testContractID := "9be17165" -// nft1 := "nft-1" -// ft1 := "ft-1" -// amount := int64(100) -// mintNftParams := []types.MintNFTParam{types.NewMintNFTParam(nft1, "", defaultTokenType)} -// coins := []types.Coin{types.NewCoin(defaultTokenIDFT, sdk.NewInt(amount))} -// changes := []types.Change{types.NewChange("f", "t")} - -// create := fmt.Sprintf(`{"route":"create","data":{"owner":"%s", "name":"%s","meta":"","base_img_uri":""}}`, addr1.String(), testContractName) -// createMsg := json.RawMessage(create) -// issueNft := fmt.Sprintf(`{"route":"issue_nft","data":{"owner":"%s", "contract_id":"%s", "name":"%s","meta":""}}`, addr1.String(), testContractID, nft1) -// issueNftMsg := json.RawMessage(issueNft) -// issueFt := fmt.Sprintf(`{"route":"issue_ft","data":{"owner":"%s", "contract_id":"%s", "to":"%s", "name":"%s","meta":"", "amount":"%d", "mintable":true, "decimals":"18"}}`, addr1.String(), testContractID, addr2.String(), ft1, amount) -// issueFtMsg := json.RawMessage(issueFt) -// mintNft := fmt.Sprintf(`{"route":"mint_nft","data":{"from":"%s", "contract_id":"%s", "to":"%s", "params":[{"name":"%s", "meta":"", "token_type":"%s"}]}}`, addr1.String(), testContractID, addr2.String(), nft1, defaultTokenType) -// mintNftMsg := json.RawMessage(mintNft) -// mintFt := fmt.Sprintf(`{"route":"mint_ft","data":{"from":"%s", "contract_id":"%s", "to":"%s", "amount":[{"token_id":"%s", "amount":"%d"}]}}`, addr1.String(), testContractID, addr2.String(), defaultTokenIDFT, amount) -// mintFtMsg := json.RawMessage(mintFt) -// burnNft := fmt.Sprintf(`{"route":"burn_nft","data":{"from":"%s", "contract_id":"%s", "token_ids":["%s"]}}`, addr1.String(), testContractID, defaultTokenID1) -// burnNftMsg := json.RawMessage(burnNft) -// burnNftFrom := fmt.Sprintf(`{"route":"burn_nft_from","data":{"proxy":"%s", "from":"%s","contract_id":"%s", "token_ids":["%s"]}}`, addr2.String(), addr1.String(), testContractID, defaultTokenID1) -// burnNftFromMsg := json.RawMessage(burnNftFrom) -// burnFt := fmt.Sprintf(`{"route":"burn_ft","data":{"from":"%s","contract_id":"%s", "amount":[{"token_id":"%s", "amount":"%d"}]}}`, addr1.String(), testContractID, defaultTokenIDFT, amount) -// burnFtMsg := json.RawMessage(burnFt) -// burnFtFrom := fmt.Sprintf(`{"route":"burn_ft_from","data":{"proxy":"%s", "from":"%s","contract_id":"%s", "amount":[{"token_id":"%s", "amount":"%d"}]}}`, addr2.String(), addr1.String(), testContractID, defaultTokenIDFT, amount) -// burnFtFromMsg := json.RawMessage(burnFtFrom) -// transferNft := fmt.Sprintf(`{"route":"transfer_nft","data":{"from":"%s", "contract_id":"%s", "to":"%s", "token_ids":["%s"]}}`, addr1.String(), testContractID, addr2.String(), defaultTokenID1) -// transferNftMsg := json.RawMessage(transferNft) -// transferNftFrom := fmt.Sprintf(`{"route":"transfer_nft_from","data":{"proxy":"%s", "from":"%s", "contract_id":"%s", "to":"%s", "token_ids":["%s"]}}`, addr2.String(), addr1.String(), testContractID, addr2.String(), defaultTokenID1) -// transferNftFromMsg := json.RawMessage(transferNftFrom) -// transferFt := fmt.Sprintf(`{"route":"transfer_ft","data":{"from":"%s", "contract_id":"%s", "to":"%s", "amount":[{"token_id":"%s", "amount":"%d"}]}}`, addr1.String(), testContractID, addr2.String(), defaultTokenIDFT, amount) -// transferFtMsg := json.RawMessage(transferFt) -// transferFtFrom := fmt.Sprintf(`{"route":"transfer_ft_from","data":{"proxy":"%s", "from":"%s", "contract_id":"%s", "to":"%s", "amount":[{"token_id":"%s", "amount":"%d"}]}}`, addr2.String(), addr1.String(), testContractID, addr2.String(), defaultTokenIDFT, amount) -// transferFtFromMsg := json.RawMessage(transferFtFrom) -// approve := fmt.Sprintf(`{"route":"approve","data":{"approver":"%s", "contract_id":"%s", "proxy":"%s"}}`, addr1.String(), testContractID, addr2.String()) -// approveMsg := json.RawMessage(approve) -// disapprove := fmt.Sprintf(`{"route":"disapprove","data":{"approver":"%s", "contract_id":"%s", "proxy":"%s"}}`, addr1.String(), testContractID, addr2.String()) -// disapproveMsg := json.RawMessage(disapprove) -// attach := fmt.Sprintf(`{"route":"attach","data":{"from":"%s", "contract_id":"%s", "to_token_id":"%s", "token_id":"%s"}}`, addr1.String(), testContractID, defaultTokenID1, defaultTokenID2) -// attachMsg := json.RawMessage(attach) -// detach := fmt.Sprintf(`{"route":"detach","data":{"from":"%s", "contract_id":"%s", "token_id":"%s"}}`, addr1.String(), testContractID, defaultTokenID1) -// detachMsg := json.RawMessage(detach) -// attachFrom := fmt.Sprintf(`{"route":"attach_from","data":{"proxy":"%s", "from":"%s", "contract_id":"%s", "to_token_id":"%s", "token_id":"%s"}}`, addr2.String(), addr1.String(), testContractID, defaultTokenID1, defaultTokenID2) -// attachFromMsg := json.RawMessage(attachFrom) -// detachFrom := fmt.Sprintf(`{"route":"detach_from","data":{"proxy":"%s", "from":"%s", "contract_id":"%s", "token_id":"%s"}}`, addr2.String(), addr1.String(), testContractID, defaultTokenID1) -// detachFromMsg := json.RawMessage(detachFrom) -// modify := fmt.Sprintf(`{"route":"modify","data":{"owner":"%s", "contract_id":"%s", "token_type":"%s", "token_index":"%s", "changes":[{"field":"f", "value":"t"}]}}`, addr1.String(), testContractID, defaultTokenType, defaultTokenIndex) -// modifyMsg := json.RawMessage(modify) - -// cases := map[string]struct { -// input json.RawMessage -// // set if valid -// output []sdk.Msg -// // set if invalid -// isError bool -// }{ -// "create collection": { -// input: createMsg, -// output: []sdk.Msg{ -// types.MsgCreateCollection{ -// Owner: addr1, -// Name: testContractName, -// Meta: "", -// BaseImgURI: "", -// }, -// }, -// }, -// "issue nft": { -// input: issueNftMsg, -// output: []sdk.Msg{ -// types.MsgIssueNFT{ -// Owner: addr1, -// ContractID: testContractID, -// Name: nft1, -// Meta: "", -// }, -// }, -// }, -// "issue ft": { -// input: issueFtMsg, -// output: []sdk.Msg{ -// types.MsgIssueFT{ -// Owner: addr1, -// ContractID: testContractID, -// To: addr2, -// Name: ft1, -// Meta: "", -// Amount: sdk.NewInt(amount), -// Mintable: true, -// Decimals: sdk.NewInt(18), -// }, -// }, -// }, -// "mint nft": { -// input: mintNftMsg, -// output: []sdk.Msg{ -// types.MsgMintNFT{ -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// MintNFTParams: mintNftParams, -// }, -// }, -// }, -// "mint ft": { -// input: mintFtMsg, -// output: []sdk.Msg{ -// types.MsgMintFT{ -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// Amount: coins, -// }, -// }, -// }, -// "burn nft": { -// input: burnNftMsg, -// output: []sdk.Msg{ -// types.MsgBurnNFT{ -// From: addr1, -// ContractID: testContractID, -// TokenIDs: []string{defaultTokenID1}, -// }, -// }, -// }, -// "burn nft from": { -// input: burnNftFromMsg, -// output: []sdk.Msg{ -// types.MsgBurnNFTFrom{ -// Proxy: addr2, -// From: addr1, -// ContractID: testContractID, -// TokenIDs: []string{defaultTokenID1}, -// }, -// }, -// }, -// "burn ft": { -// input: burnFtMsg, -// output: []sdk.Msg{ -// types.MsgBurnFT{ -// From: addr1, -// ContractID: testContractID, -// Amount: coins, -// }, -// }, -// }, -// "burn ft from": { -// input: burnFtFromMsg, -// output: []sdk.Msg{ -// types.MsgBurnFTFrom{ -// Proxy: addr2, -// From: addr1, -// ContractID: testContractID, -// Amount: coins, -// }, -// }, -// }, -// "transfer nft": { -// input: transferNftMsg, -// output: []sdk.Msg{ -// types.MsgTransferNFT{ -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// TokenIDs: []string{defaultTokenID1}, -// }, -// }, -// }, -// "transfer nft from": { -// input: transferNftFromMsg, -// output: []sdk.Msg{ -// types.MsgTransferNFTFrom{ -// Proxy: addr2, -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// TokenIDs: []string{defaultTokenID1}, -// }, -// }, -// }, -// "transfer ft": { -// input: transferFtMsg, -// output: []sdk.Msg{ -// types.MsgTransferFT{ -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// Amount: coins, -// }, -// }, -// }, -// "transfer ft from": { -// input: transferFtFromMsg, -// output: []sdk.Msg{ -// types.MsgTransferFTFrom{ -// Proxy: addr2, -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// Amount: coins, -// }, -// }, -// }, -// "approve": { -// input: approveMsg, -// output: []sdk.Msg{ -// types.MsgApprove{ -// Approver: addr1, -// ContractID: testContractID, -// Proxy: addr2, -// }, -// }, -// }, -// "disapprove": { -// input: disapproveMsg, -// output: []sdk.Msg{ -// types.MsgDisapprove{ -// Approver: addr1, -// ContractID: testContractID, -// Proxy: addr2, -// }, -// }, -// }, -// "attach": { -// input: attachMsg, -// output: []sdk.Msg{ -// types.MsgAttach{ -// From: addr1, -// ContractID: testContractID, -// ToTokenID: defaultTokenID1, -// TokenID: defaultTokenID2, -// }, -// }, -// }, -// "detach": { -// input: detachMsg, -// output: []sdk.Msg{ -// types.MsgDetach{ -// From: addr1, -// ContractID: testContractID, -// TokenID: defaultTokenID1, -// }, -// }, -// }, -// "attach from": { -// input: attachFromMsg, -// output: []sdk.Msg{ -// types.MsgAttachFrom{ -// Proxy: addr2, -// From: addr1, -// ContractID: testContractID, -// ToTokenID: defaultTokenID1, -// TokenID: defaultTokenID2, -// }, -// }, -// }, -// "detach from": { -// input: detachFromMsg, -// output: []sdk.Msg{ -// types.MsgDetachFrom{ -// Proxy: addr2, -// From: addr1, -// ContractID: testContractID, -// TokenID: defaultTokenID1, -// }, -// }, -// }, -// "modify": { -// input: modifyMsg, -// output: []sdk.Msg{ -// types.MsgModify{ -// Owner: addr1, -// ContractID: testContractID, -// TokenType: defaultTokenType, -// TokenIndex: defaultTokenIndex, -// Changes: changes, -// }, -// }, -// }, -// } - -// for name, tc := range cases { -// tc := tc -// t.Run(name, func(t *testing.T) { -// res, err := encodeHandler(tc.input) -// if tc.isError { -// require.Error(t, err) -// } else { -// require.NoError(t, err) -// assert.Equal(t, tc.output, res) -// } -// }) -// } -// } diff --git a/x/collection/internal/keeper/nftowner.go b/x/collection/internal/keeper/nftowner.go deleted file mode 100644 index 78c02a3eb0..0000000000 --- a/x/collection/internal/keeper/nftowner.go +++ /dev/null @@ -1,61 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func (k Keeper) AddNFTOwner(ctx sdk.Context, addr sdk.AccAddress, tokenID string) { - store := ctx.KVStore(k.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(k.getContractID(ctx), addr, tokenID) - if store.Has(tokenOwnerKey) { - panic(fmt.Sprintf("account: %s already has the token: %s", addr.String(), tokenID)) - } - store.Set(tokenOwnerKey, []byte(tokenID)) -} - -func (k Keeper) DeleteNFTOwner(ctx sdk.Context, addr sdk.AccAddress, tokenID string) { - store := ctx.KVStore(k.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(k.getContractID(ctx), addr, tokenID) - if !store.Has(tokenOwnerKey) { - panic(fmt.Sprintf("account: %s has not the token: %s", addr.String(), tokenID)) - } - store.Delete(tokenOwnerKey) -} - -func (k Keeper) HasNFTOwner(ctx sdk.Context, addr sdk.AccAddress, tokenID string) bool { - store := ctx.KVStore(k.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(k.getContractID(ctx), addr, tokenID) - return store.Has(tokenOwnerKey) -} - -func (k Keeper) ChangeNFTOwner(ctx sdk.Context, from, to sdk.AccAddress, tokenID string) error { - if !k.HasNFTOwner(ctx, from, tokenID) { - return sdkerrors.Wrapf(types.ErrInsufficientToken, "insufficient account funds[%s]; account has no coin", k.getContractID(ctx)) - } - - k.DeleteNFTOwner(ctx, from, tokenID) - k.AddNFTOwner(ctx, to, tokenID) - return nil -} - -func (k Keeper) GetNFTsOwner(ctx sdk.Context, addr sdk.AccAddress) (tokenIDs []string) { - store := ctx.KVStore(k.storeKey) - var iter = sdk.KVStorePrefixIterator(store, types.AccountOwnNFTKey(k.getContractID(ctx), addr, "")) - defer iter.Close() - for { - if !iter.Valid() { - break - } - - val := iter.Value() - tokenIDs = append(tokenIDs, string(val)) - iter.Next() - } - return tokenIDs -} diff --git a/x/collection/internal/keeper/nftowner_test.go b/x/collection/internal/keeper/nftowner_test.go deleted file mode 100644 index a232ab7436..0000000000 --- a/x/collection/internal/keeper/nftowner_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_AddNFTOwner(t *testing.T) { - ctx := cacheKeeper() - t.Log("Add Owner") - { - keeper.AddNFTOwner(ctx, addr1, defaultTokenID1) - } - t.Log("Add Owner Again") - { - require.Panics(t, func() { keeper.AddNFTOwner(ctx, addr1, defaultTokenID1) }, "") - } - t.Log("Get The Data") - { - store := ctx.KVStore(keeper.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID1) - require.True(t, store.Has(tokenOwnerKey)) - } - t.Log("Get The Wrong Data") - { - store := ctx.KVStore(keeper.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID2) - require.False(t, store.Has(tokenOwnerKey)) - } -} - -func TestKeeper_DeleteNFTOwner(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Owner") - { - store := ctx.KVStore(keeper.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID1) - store.Set(tokenOwnerKey, []byte(defaultTokenID1)) - } - t.Log("Delete the Data") - { - keeper.DeleteNFTOwner(ctx, addr1, defaultTokenID1) - } - t.Log("Is deleted") - { - store := ctx.KVStore(keeper.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID1) - require.False(t, store.Has(tokenOwnerKey)) - } - t.Log("Delete Wrong Data") - { - require.Panics(t, func() { keeper.DeleteNFTOwner(ctx, addr1, defaultTokenID1) }, "") - } -} - -func TestKeeepr_HasNFTOwner(t *testing.T) { - ctx := cacheKeeper() - t.Log("Has Not Data") - { - require.False(t, keeper.HasNFTOwner(ctx, addr1, defaultTokenID1)) - } - t.Log("Prepare Owner") - { - store := ctx.KVStore(keeper.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID1) - store.Set(tokenOwnerKey, []byte(defaultTokenID1)) - } - t.Log("Has Data") - { - require.True(t, keeper.HasNFTOwner(ctx, addr1, defaultTokenID1)) - } -} - -func TestKeeper_ChangeNFTOwner(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Owner") - { - store := ctx.KVStore(keeper.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID1) - store.Set(tokenOwnerKey, []byte(defaultTokenID1)) - } - t.Log("transfer") - { - require.NoError(t, keeper.ChangeNFTOwner(ctx, addr1, addr2, defaultTokenID1)) - } - t.Log("transfer again") - { - require.EqualError(t, keeper.ChangeNFTOwner(ctx, addr1, addr2, defaultTokenID1), "insufficient token: insufficient account funds[abcdef01]; account has no coin") - } -} - -func TestKeeper_GetNFTsOwner(t *testing.T) { - ctx := cacheKeeper() - { - tokenIDs := keeper.GetNFTsOwner(ctx, addr1) - require.Empty(t, tokenIDs) - } - t.Log("Prepare Owner") - { - store := ctx.KVStore(keeper.storeKey) - tokenOwnerKey := types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID1) - store.Set(tokenOwnerKey, []byte(defaultTokenID1)) - - tokenOwnerKey = types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID2) - store.Set(tokenOwnerKey, []byte(defaultTokenID2)) - - tokenOwnerKey = types.AccountOwnNFTKey(defaultContractID, addr1, defaultTokenID3) - store.Set(tokenOwnerKey, []byte(defaultTokenID3)) - } - t.Log("Get the data") - { - tokenIDs := keeper.GetNFTsOwner(ctx, addr1) - require.NotEmpty(t, tokenIDs) - require.Equal(t, defaultTokenID1, tokenIDs[0]) - require.Equal(t, defaultTokenID2, tokenIDs[1]) - require.Equal(t, defaultTokenID3, tokenIDs[2]) - } -} diff --git a/x/collection/internal/keeper/params.go b/x/collection/internal/keeper/params.go deleted file mode 100644 index f547e8eef5..0000000000 --- a/x/collection/internal/keeper/params.go +++ /dev/null @@ -1,16 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramsSpace.SetParamSet(ctx, ¶ms) -} - -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramsSpace.GetParamSet(ctx, ¶ms) - return -} diff --git a/x/collection/internal/keeper/perm.go b/x/collection/internal/keeper/perm.go deleted file mode 100644 index 787c44381a..0000000000 --- a/x/collection/internal/keeper/perm.go +++ /dev/null @@ -1,91 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -func (k Keeper) AddPermission(ctx sdk.Context, addr sdk.AccAddress, perm types.Permission) { - accPerm := k.getAccountPermission(ctx, addr) - accPerm.AddPermission(perm) - k.setAccountPermission(ctx, accPerm) -} - -func (k Keeper) HasPermission(ctx sdk.Context, addr sdk.AccAddress, p types.Permission) bool { - accPerm := k.getAccountPermission(ctx, addr) - return accPerm.HasPermission(p) -} - -func (k Keeper) GetPermissions(ctx sdk.Context, addr sdk.AccAddress) types.Permissions { - accPerm := k.getAccountPermission(ctx, addr) - return accPerm.GetPermissions() -} - -func (k Keeper) RevokePermission(ctx sdk.Context, addr sdk.AccAddress, perm types.Permission) error { - if !k.HasPermission(ctx, addr, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr.String(), perm.String()) - } - accPerm := k.getAccountPermission(ctx, addr) - accPerm.RemovePermission(perm) - k.setAccountPermission(ctx, accPerm) - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeRevokePermToken, - sdk.NewAttribute(types.AttributeKeyFrom, addr.String()), - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyPerm, perm.String()), - ), - }) - return nil -} - -func (k Keeper) GrantPermission(ctx sdk.Context, from, to sdk.AccAddress, perm types.Permission) error { - if !k.HasPermission(ctx, from, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", from.String(), perm.String()) - } - k.AddPermission(ctx, to, perm) - - // Set Account if not exists yet - account := k.accountKeeper.GetAccount(ctx, to) - if account == nil { - account = k.accountKeeper.NewAccountWithAddress(ctx, to) - k.accountKeeper.SetAccount(ctx, account) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeGrantPermToken, - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyPerm, perm.String()), - ), - }) - - return nil -} - -func (k Keeper) getAccountPermission(ctx sdk.Context, addr sdk.AccAddress) (accPerm types.AccountPermissionI) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.PermKey(k.getContractID(ctx), addr)) - if bz != nil { - accPerm = k.mustDecodeAccountPermission(bz) - return accPerm - } - return types.NewAccountPermission(addr) -} - -func (k Keeper) setAccountPermission(ctx sdk.Context, accPerm types.AccountPermissionI) { - store := ctx.KVStore(k.storeKey) - store.Set(types.PermKey(k.getContractID(ctx), accPerm.GetAddress()), k.cdc.MustMarshalBinaryBare(accPerm)) -} - -func (k Keeper) mustDecodeAccountPermission(bz []byte) (accPerm types.AccountPermissionI) { - err := k.cdc.UnmarshalBinaryBare(bz, &accPerm) - if err != nil { - panic(err) - } - return -} diff --git a/x/collection/internal/keeper/perm_test.go b/x/collection/internal/keeper/perm_test.go deleted file mode 100644 index ae6fc7838b..0000000000 --- a/x/collection/internal/keeper/perm_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func TestCollectionAndPermission(t *testing.T) { - ctx := cacheKeeper() - - issuePerm := types.NewIssuePermission() - { - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, - defaultMeta, defaultImgURI), addr1)) - require.True(t, keeper.HasPermission(ctx, addr1, issuePerm)) - require.Error(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, - defaultMeta, defaultImgURI), addr1)) - collection, err := keeper.GetCollection(ctx) - require.NoError(t, err) - require.Equal(t, defaultContractID, collection.GetContractID()) - - { - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true), sdk.NewInt(defaultAmount))) - token, err := keeper.GetToken(ctx, defaultTokenIDFT) - require.NoError(t, err) - require.Equal(t, defaultContractID, token.GetContractID()) - require.Equal(t, defaultTokenIDFT, token.GetTokenID()) - } - { - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1))) - - token, err := keeper.GetToken(ctx, defaultTokenID1) - require.NoError(t, err) - require.Equal(t, defaultContractID, token.GetContractID()) - require.Equal(t, defaultTokenID1, token.GetTokenID()) - - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID2, defaultName, defaultMeta, addr1))) - token, err = keeper.GetToken(ctx, defaultTokenID2) - require.NoError(t, err) - require.Equal(t, defaultContractID, token.GetContractID()) - require.Equal(t, defaultTokenID2, token.GetTokenID()) - - count, err := keeper.GetNFTCount(ctx, defaultTokenType) - require.NoError(t, err) - require.Equal(t, int64(2), count.Int64()) - - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType2, defaultName, defaultMeta), addr1)) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenType2+"00000001", defaultName, defaultMeta, addr1))) - token, err = keeper.GetToken(ctx, defaultTokenType2+"00000001") - require.NoError(t, err) - require.Equal(t, defaultContractID, token.GetContractID()) - require.Equal(t, defaultTokenType2+"00000001", token.GetTokenID()) - } - } - { - require.NoError(t, keeper.GrantPermission(ctx, addr1, addr2, issuePerm)) - require.True(t, keeper.HasPermission(ctx, addr1, issuePerm)) - require.True(t, keeper.HasPermission(ctx, addr2, issuePerm)) - } - - issuePerm2 := types.NewIssuePermission() - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID2)) - { - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID2, defaultName, - defaultMeta, defaultImgURI), addr1)) - require.True(t, keeper.HasPermission(ctx, addr1, issuePerm2)) - require.Error(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID2, defaultName, - defaultMeta, defaultImgURI), addr1)) - collection, err := keeper.GetCollection(ctx) - require.NoError(t, err) - require.Equal(t, defaultContractID2, collection.GetContractID()) - } - { - collections := keeper.GetAllCollections(ctx) - require.Equal(t, 2, len(collections)) - require.Equal(t, defaultContractID, collections[0].GetContractID()) - require.Equal(t, defaultContractID2, collections[1].GetContractID()) - } -} - -func TestPermission(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.RevokePermission(ctx, addr3, types.NewMintPermission()), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr3.String(), types.NewMintPermission().String()).Error()) - require.NoError(t, keeper.RevokePermission(ctx, addr1, types.NewMintPermission())) - require.EqualError(t, keeper.GrantPermission(ctx, addr3, addr1, types.NewMintPermission()), sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr3.String(), types.NewMintPermission().String()).Error()) -} diff --git a/x/collection/internal/keeper/proxy.go b/x/collection/internal/keeper/proxy.go deleted file mode 100644 index 249506102d..0000000000 --- a/x/collection/internal/keeper/proxy.go +++ /dev/null @@ -1,111 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -var ( - ApprovedValue = []byte{0x01} -) - -type ProxyKeeper interface { - IsApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) bool - SetApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) error - DeleteApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) error -} - -func (k Keeper) IsApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) bool { - store := ctx.KVStore(k.storeKey) - approvedKey := types.CollectionApprovedKey(k.getContractID(ctx), proxy, approver) - return store.Has(approvedKey) -} - -func (k Keeper) GetApprovers(ctx sdk.Context, proxy sdk.AccAddress) (accAds []sdk.AccAddress, err error) { - _, err = k.GetCollection(ctx) - if err != nil { - return nil, err - } - k.iterateApprovers(ctx, proxy, false, func(ad sdk.AccAddress) bool { - accAds = append(accAds, ad) - return false - }) - return accAds, nil -} - -func (k Keeper) iterateApprovers(ctx sdk.Context, prefix sdk.AccAddress, reverse bool, process func(accAd sdk.AccAddress) bool) { - store := ctx.KVStore(k.storeKey) - prefixKey := types.CollectionApproversKey(k.getContractID(ctx), prefix) - var iter sdk.Iterator - if reverse { - iter = sdk.KVStoreReversePrefixIterator(store, prefixKey) - } else { - iter = sdk.KVStorePrefixIterator(store, prefixKey) - } - defer iter.Close() - for { - if !iter.Valid() { - return - } - bz := iter.Key() - approver := bz[len(prefixKey):] - if process(approver) { - return - } - iter.Next() - } -} - -func (k Keeper) SetApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) error { - store := ctx.KVStore(k.storeKey) - if !store.Has(types.CollectionKey(k.getContractID(ctx))) { - return sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - approvedKey := types.CollectionApprovedKey(k.getContractID(ctx), proxy, approver) - if store.Has(approvedKey) { - return sdkerrors.Wrapf(types.ErrCollectionAlreadyApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), approver.String(), k.getContractID(ctx)) - } - store.Set(approvedKey, ApprovedValue) - - // Set Account if not exists yet - account := k.accountKeeper.GetAccount(ctx, proxy) - if account == nil { - account = k.accountKeeper.NewAccountWithAddress(ctx, proxy) - k.accountKeeper.SetAccount(ctx, account) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeApproveCollection, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyApprover, approver.String()), - ), - }) - - return nil -} - -func (k Keeper) DeleteApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) error { - store := ctx.KVStore(k.storeKey) - if !store.Has(types.CollectionKey(k.getContractID(ctx))) { - return sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - approvedKey := types.CollectionApprovedKey(k.getContractID(ctx), proxy, approver) - if !store.Has(approvedKey) { - return sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), approver.String(), k.getContractID(ctx)) - } - store.Delete(approvedKey) - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeDisapproveCollection, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyApprover, approver.String()), - ), - }) - - return nil -} diff --git a/x/collection/internal/keeper/proxy_test.go b/x/collection/internal/keeper/proxy_test.go deleted file mode 100644 index a32a8dfb7a..0000000000 --- a/x/collection/internal/keeper/proxy_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func TestApproveDisapproveScenario(t *testing.T) { - ctx := cacheKeeper() - const ( - defaultTokenIDFromContractID2 = defaultTokenType2 + "00000001" - ) - - // prepare collection, FT, NFT - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, "name", defaultMeta, defaultImgURI), addr1)) - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true), sdk.NewInt(defaultAmount))) - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType2, defaultName, defaultMeta), addr1)) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1))) - require.NoError(t, keeper.MintNFT(ctx, addr1, types.NewNFT(defaultContractID, defaultTokenType2+"00000001", defaultName, defaultMeta, addr1))) - - // approve test - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID2)) - require.EqualError(t, keeper.SetApproved(ctx2, addr3, addr1), sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", defaultContractID2).Error()) - require.NoError(t, keeper.SetApproved(ctx, addr3, addr1)) - require.EqualError(t, keeper.SetApproved(ctx, addr3, addr1), sdkerrors.Wrapf(types.ErrCollectionAlreadyApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr3.String(), addr1.String(), defaultContractID).Error()) - - // attach_from/detach_from test - require.EqualError(t, keeper.AttachFrom(ctx, addr2, addr1, defaultTokenID1, defaultTokenIDFromContractID2), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr2.String(), addr1.String(), defaultContractID).Error()) - require.NoError(t, keeper.AttachFrom(ctx, addr3, addr1, defaultTokenID1, defaultTokenIDFromContractID2)) - require.EqualError(t, keeper.DetachFrom(ctx, addr2, addr1, defaultTokenIDFromContractID2), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr2.String(), addr1.String(), defaultContractID).Error()) - require.NoError(t, keeper.DetachFrom(ctx, addr3, addr1, defaultTokenIDFromContractID2)) - - // transfer_from test - require.EqualError(t, keeper.TransferFTFrom(ctx, addr2, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10))), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr2.String(), addr1.String(), defaultContractID).Error()) - require.NoError(t, keeper.TransferFTFrom(ctx, addr3, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)))) - - require.EqualError(t, keeper.TransferNFTFrom(ctx, addr2, addr1, addr2, defaultTokenID1), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr2.String(), addr1.String(), defaultContractID).Error()) - require.NoError(t, keeper.TransferNFTFrom(ctx, addr3, addr1, addr2, defaultTokenID1)) - - // disapprove test - ctx2 = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID2)) - require.EqualError(t, keeper.DeleteApproved(ctx2, addr3, addr1), sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", defaultContractID2).Error()) - require.NoError(t, keeper.DeleteApproved(ctx, addr3, addr1)) - require.EqualError(t, keeper.DeleteApproved(ctx, addr3, addr1), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr3.String(), addr1.String(), defaultContractID).Error()) -} diff --git a/x/collection/internal/keeper/supply.go b/x/collection/internal/keeper/supply.go deleted file mode 100644 index ce935bd1cb..0000000000 --- a/x/collection/internal/keeper/supply.go +++ /dev/null @@ -1,98 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type SupplyKeeper interface { - GetTotalInt(ctx sdk.Context, tokenID, target string) (supply sdk.Int, err error) - GetSupply(ctx sdk.Context) (supply types.Supply) - SetSupply(ctx sdk.Context, supply types.Supply) - MintSupply(ctx sdk.Context, to sdk.AccAddress, amt types.Coins) error - BurnSupply(ctx sdk.Context, from sdk.AccAddress, amt types.Coins) error -} - -var _ SupplyKeeper = (*Keeper)(nil) - -func (k Keeper) GetSupply(ctx sdk.Context) (supply types.Supply) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.SupplyKey(k.getContractID(ctx))) - if b == nil { - panic("stored supply should not have been nil") - } - k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &supply) - return -} - -func (k Keeper) SetSupply(ctx sdk.Context, supply types.Supply) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryLengthPrefixed(supply) - store.Set(types.SupplyKey(supply.GetContractID()), b) -} - -func (k Keeper) GetTotalInt(ctx sdk.Context, tokenID, target string) (supply sdk.Int, err error) { - if _, err = k.GetToken(ctx, tokenID); err != nil { - return sdk.NewInt(0), err - } - - s := k.GetSupply(ctx) - switch target { - case types.QuerySupply: - return s.GetTotalSupply().AmountOf(tokenID), nil - case types.QueryBurn: - return s.GetTotalBurn().AmountOf(tokenID), nil - case types.QueryMint: - return s.GetTotalMint().AmountOf(tokenID), nil - default: - return sdk.ZeroInt(), sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid request target to query total %s", target) - } -} - -// MintCoins creates new coins from thin air and adds it to the module account. -// Panics if the name maps to a non-minter module account or if the amount is invalid. -func (k Keeper) MintSupply(ctx sdk.Context, to sdk.AccAddress, amt types.Coins) (err error) { - defer func() { - // to recover from overflows - if r := recover(); r != nil { - err = types.WrapIfOverflowPanic(r) - } - }() - - _, err = k.AddCoins(ctx, to, amt) - if err != nil { - return err - } - supply := k.GetSupply(ctx) - supply = supply.Inflate(amt) - // supply should never be negative. Big.Int.Add will be panic if it becomes overflow - - k.SetSupply(ctx, supply) - return nil -} - -// BurnCoins burns coins deletes coins from the balance of the module account. -// Panics if the name maps to a non-burner module account or if the amount is invalid. -func (k Keeper) BurnSupply(ctx sdk.Context, from sdk.AccAddress, amt types.Coins) (err error) { - defer func() { - // to recover from overflows - // however, it will return insufficient fund error instead of panicking in the case - if r := recover(); r != nil { - err = types.WrapIfOverflowPanic(r) - } - }() - - _, err = k.SubtractCoins(ctx, from, amt) - if err != nil { - return err - } - supply := k.GetSupply(ctx) - supply = supply.Deflate(amt) - if supply.GetTotalSupply().IsAnyNegative() { - return sdkerrors.Wrapf(types.ErrInsufficientSupply, "insufficient supply for token [%s]", k.getContractID(ctx)) - } - k.SetSupply(ctx, supply) - - return nil -} diff --git a/x/collection/internal/keeper/supply_test.go b/x/collection/internal/keeper/supply_test.go deleted file mode 100644 index a63ac6900d..0000000000 --- a/x/collection/internal/keeper/supply_test.go +++ /dev/null @@ -1,222 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -func TestKeeper_GetTotalInt(t *testing.T) { - ctx := cacheKeeper() - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - t.Log("Prepare Supply and FT") - expected := types.DefaultSupply(defaultContractID) - ft := types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.ZeroInt(), true) - { - keeper.SetSupply(ctx, expected) - err := keeper.SetCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI)) - require.NoError(t, err) - err = keeper.IssueFT(ctx, addr1, addr1, ft, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - } - t.Log("Get Total Supply Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount), actual.Int64()) - } - t.Log("Get Total Mint Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryMint) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount), actual.Int64()) - } - t.Log("Get Total Burn Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, int64(0), actual.Int64()) - } -} - -func TestKeeper_MintSupply(t *testing.T) { - ctx := cacheKeeper() - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - t.Log("Prepare Supply and FT") - expected := types.DefaultSupply(defaultContractID) - ft := types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.ZeroInt(), true) - { - keeper.SetSupply(ctx, expected) - err := keeper.SetCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI)) - require.NoError(t, err) - err = keeper.IssueFT(ctx, addr1, addr1, ft, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - } - t.Log("Get Balance") - { - balance, err := keeper.GetBalance(ctx, defaultTokenIDFT, addr1) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount).Int64(), balance.Int64()) - } - t.Log("Mint Supply") - { - require.NoError(t, keeper.MintSupply(ctx, addr1, types.OneCoins(defaultTokenIDFT))) - } - t.Log("Get Balance") - { - balance, err := keeper.GetBalance(ctx, defaultTokenIDFT, addr1) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount+1).Int64(), balance.Int64()) - } - t.Log("Get Total Supply Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount+1), actual) - } - t.Log("Get Total Mint Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryMint) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount+1), actual) - } - t.Log("Get Total Burn Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, sdk.ZeroInt(), actual) - } -} - -func TestKeeper_BurnSupply(t *testing.T) { - ctx := cacheKeeper() - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - t.Log("Prepare Supply and FT") - expected := types.DefaultSupply(defaultContractID) - ft := types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.ZeroInt(), true) - { - keeper.SetSupply(ctx, expected) - err := keeper.SetCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI)) - require.NoError(t, err) - err = keeper.IssueFT(ctx, addr1, addr1, ft, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - } - t.Log("Get Balance") - { - balance, err := keeper.GetBalance(ctx, defaultTokenIDFT, addr1) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount).Int64(), balance.Int64()) - } - t.Log("Burn Supply") - { - require.NoError(t, keeper.BurnSupply(ctx, addr1, types.OneCoins(defaultTokenIDFT))) - } - t.Log("Get Balance") - { - balance, err := keeper.GetBalance(ctx, defaultTokenIDFT, addr1) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount-1).Int64(), balance.Int64()) - } - t.Log("Get Total Supply Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount-1), actual) - } - t.Log("Get Total Mint Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryMint) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount), actual) - } - t.Log("Get Total Burn Int") - { - actual, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(1), actual) - } -} - -func TestKeeper_Handle_Overflows(t *testing.T) { - ctx := cacheKeeper() - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - // int64 is the set of all signed 64-bit integers. - // Range: -9223372036854775808 through 9223372036854775807. - - // Int wraps integer with 256 bit range bound - // Checks overflow, underflow and division by zero - // Exists in range from -(2^maxBitLen-1) to 2^maxBitLen-1 - - t.Log("Prepare Supply and FT less than the overflow limit") - maxInt64Supply := sdk.NewInt(9223372036854775807) - initialSupply := maxInt64Supply.Mul(maxInt64Supply).Mul(maxInt64Supply).Mul(maxInt64Supply) - ft := types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, initialSupply, true) - newSupply := types.NewSupply(defaultContractID, types.NewCoins(types.NewCoin(defaultTokenIDFT, initialSupply))) - { - keeper.SetSupply(ctx, newSupply) - err := keeper.SetCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI)) - require.NoError(t, err) - err = keeper.IssueFT(ctx, addr1, addr1, ft, sdk.ZeroInt()) - require.NoError(t, err) - } - - ts, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalSupply().AmountOf(defaultTokenIDFT), ts) - - tm, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryMint) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalMint().AmountOf(defaultTokenIDFT), tm) - - tb, err := keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalBurn().AmountOf(defaultTokenIDFT), tb) - - // inflate over the overflow limit - t.Log("Inflate the supply over the overflow limit") - addToOverflow := types.NewCoins(types.NewCoin(defaultTokenIDFT, initialSupply.Mul(sdk.NewInt(8)))) - err = keeper.MintSupply(ctx, addr1, addToOverflow) - require.Equal(t, types.ErrSupplyOverflow, err) - - // should have not changed - t.Log("Totals have not changed") - ts, err = keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalSupply().AmountOf(defaultTokenIDFT), ts) - - tm, err = keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryMint) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalMint().AmountOf(defaultTokenIDFT), tm) - - tb, err = keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalBurn().AmountOf(defaultTokenIDFT), tb) - - // deflate below the overflow limit - t.Log("Deflate the supply below the overflow limit") - subToOverflow := types.NewCoins(types.NewCoin(defaultTokenIDFT, initialSupply.Mul(sdk.NewInt(8)))) - err = keeper.BurnSupply(ctx, addr1, subToOverflow) - require.Error(t, err) - require.Equal(t, types.ErrSupplyOverflow, err) - - // should have not changed - t.Log("Totals have not changed") - ts, err = keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalSupply().AmountOf(defaultTokenIDFT), ts) - - tm, err = keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryMint) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalMint().AmountOf(defaultTokenIDFT), tm) - - tb, err = keeper.GetTotalInt(ctx, defaultTokenIDFT, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalBurn().AmountOf(defaultTokenIDFT), tb) -} diff --git a/x/collection/internal/keeper/test_common.go b/x/collection/internal/keeper/test_common.go deleted file mode 100644 index 6e0ebbc2af..0000000000 --- a/x/collection/internal/keeper/test_common.go +++ /dev/null @@ -1,59 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestKeeper() (sdk.Context, store.CommitMultiStore, Keeper) { - keyAuth := sdk.NewKVStoreKey(auth.StoreKey) - keyParams := sdk.NewKVStoreKey(params.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) - keyCollection := sdk.NewKVStoreKey(types.StoreKey) - keyContract := sdk.NewKVStoreKey(contract.StoreKey) - - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyAuth, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyCollection, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyContract, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) - - if err := ms.LoadLatestVersion(); err != nil { - panic(err) - } - - cdc := codec.New() - types.RegisterCodec(cdc) - auth.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - cdc.Seal() - - paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams) - authSubspace := paramsKeeper.Subspace(auth.DefaultParamspace) - - // add keepers - accountKeeper := auth.NewAccountKeeper(cdc, keyAuth, authSubspace, auth.ProtoBaseAccount) - paramsSpace := paramsKeeper.Subspace(types.DefaultParamspace) - keeper := NewKeeper( - cdc, - accountKeeper, - contract.NewContractKeeper(cdc, keyContract), - paramsSpace, - keyCollection, - ) - - ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) - keeper.SetParams(ctx, types.DefaultParams()) - return ctx, ms, keeper -} diff --git a/x/collection/internal/keeper/token.go b/x/collection/internal/keeper/token.go deleted file mode 100644 index d20f0b7eea..0000000000 --- a/x/collection/internal/keeper/token.go +++ /dev/null @@ -1,318 +0,0 @@ -// nolint:unparam -package keeper - -import ( - "math/big" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type TokenKeeper interface { - GetToken(ctx sdk.Context, tokenID string) (types.Token, error) - HasToken(ctx sdk.Context, tokenID string) bool - SetToken(ctx sdk.Context, token types.Token) error - DeleteToken(ctx sdk.Context, tokenID string) error - UpdateToken(ctx sdk.Context, token types.Token) error - GetTokens(ctx sdk.Context) (tokens types.Tokens, err error) - GetFT(ctx sdk.Context, tokenID string) (types.FT, error) - GetFTs(ctx sdk.Context) (tokens types.Tokens, err error) - GetNFT(ctx sdk.Context, tokenID string) (types.NFT, error) - GetNFTCount(ctx sdk.Context, tokenType string) (sdk.Int, error) - GetNFTCountInt(ctx sdk.Context, tokenType, target string) (sdk.Int, error) - GetNFTs(ctx sdk.Context, tokenType string) (tokens types.Tokens, err error) - GetNextTokenIDFT(ctx sdk.Context) (string, error) - GetNextTokenIDNFT(ctx sdk.Context, tokenType string) (string, error) -} - -var _ TokenKeeper = (*Keeper)(nil) - -func (k Keeper) GetToken(ctx sdk.Context, tokenID string) (types.Token, error) { - store := ctx.KVStore(k.storeKey) - tokenKey := types.TokenKey(k.getContractID(ctx), tokenID) - bz := store.Get(tokenKey) - if bz == nil { - return nil, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", k.getContractID(ctx), tokenID) - } - token := k.mustDecodeToken(bz) - return token, nil -} -func (k Keeper) HasToken(ctx sdk.Context, tokenID string) bool { - store := ctx.KVStore(k.storeKey) - tokenKey := types.TokenKey(k.getContractID(ctx), tokenID) - return store.Has(tokenKey) -} - -func (k Keeper) SetToken(ctx sdk.Context, token types.Token) error { - store := ctx.KVStore(k.storeKey) - tokenKey := types.TokenKey(k.getContractID(ctx), token.GetTokenID()) - if store.Has(tokenKey) { - return sdkerrors.Wrapf(types.ErrTokenExist, "ContractID: %s, TokenID: %s", k.getContractID(ctx), token.GetTokenID()) - } - store.Set(tokenKey, k.mustEncodeToken(token)) - tokenType := token.GetTokenType() - if tokenType[0] == types.FungibleFlag[0] { - k.setNextTokenTypeFT(ctx, tokenType) - } else { - k.setNextTokenIndexNFT(ctx, tokenType, token.GetTokenIndex()) - } - return nil -} - -func (k Keeper) UpdateToken(ctx sdk.Context, token types.Token) error { - store := ctx.KVStore(k.storeKey) - tokenKey := types.TokenKey(k.getContractID(ctx), token.GetTokenID()) - if !store.Has(tokenKey) { - return sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TotkenID: %s", k.getContractID(ctx), token.GetTokenID()) - } - store.Set(tokenKey, k.mustEncodeToken(token)) - return nil -} - -func (k Keeper) DeleteToken(ctx sdk.Context, tokenID string) error { - store := ctx.KVStore(k.storeKey) - tokenKey := types.TokenKey(k.getContractID(ctx), tokenID) - if !store.Has(tokenKey) { - return sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TotkenID: %s", k.getContractID(ctx), tokenID) - } - store.Delete(tokenKey) - return nil -} - -func (k Keeper) GetTokens(ctx sdk.Context) (tokens types.Tokens, err error) { - _, err = k.GetCollection(ctx) - if err != nil { - return nil, err - } - k.iterateToken(ctx, "", false, func(t types.Token) bool { - tokens = append(tokens, t) - return false - }) - return tokens, nil -} - -func (k Keeper) GetFTs(ctx sdk.Context) (tokens types.Tokens, err error) { - _, err = k.GetCollection(ctx) - if err != nil { - return nil, err - } - k.iterateToken(ctx, types.FungibleFlag, false, func(t types.Token) bool { - tokens = append(tokens, t) - return false - }) - return tokens, nil -} - -func (k Keeper) GetFT(ctx sdk.Context, tokenID string) (types.FT, error) { - token, err := k.GetToken(ctx, tokenID) - if err != nil { - return nil, err - } - ft, ok := token.(types.FT) - if !ok { - return nil, sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", token.GetTokenID()) - } - return ft, nil -} - -func (k Keeper) GetNFT(ctx sdk.Context, tokenID string) (types.NFT, error) { - token, err := k.GetToken(ctx, tokenID) - if err != nil { - return nil, err - } - nft, ok := token.(types.NFT) - if !ok { - return nil, sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", token.GetTokenID()) - } - return nft, nil -} - -func (k Keeper) GetNFTs(ctx sdk.Context, tokenType string) (tokens types.Tokens, err error) { - _, err = k.GetCollection(ctx) - if err != nil { - return nil, err - } - k.iterateToken(ctx, tokenType, false, func(t types.Token) bool { - tokens = append(tokens, t) - return false - }) - return tokens, nil -} - -func (k Keeper) GetNFTCount(ctx sdk.Context, tokenType string) (sdk.Int, error) { - _, err := k.GetCollection(ctx) - if err != nil { - return sdk.ZeroInt(), err - } - tokens, err := k.GetNFTs(ctx, tokenType) - if err != nil { - return sdk.ZeroInt(), err - } - return sdk.NewInt(int64(len(tokens))), nil -} - -func (k Keeper) GetNFTCountInt(ctx sdk.Context, tokenType, target string) (sdk.Int, error) { - _, err := k.GetCollection(ctx) - if err != nil { - return sdk.ZeroInt(), err - } - _, err = k.GetTokenType(ctx, tokenType) - if err != nil { - return sdk.ZeroInt(), err - } - switch target { - case types.QueryNFTCount: - return k.getNFTCountTotal(ctx, tokenType), nil - case types.QueryNFTMint: - return k.getNFTCountMint(ctx, tokenType), nil - case types.QueryNFTBurn: - return k.getNFTCountBurn(ctx, tokenType), nil - default: - panic("invalid request target to query") - } -} -func (k Keeper) getNFTCountTotal(ctx sdk.Context, tokenType string) sdk.Int { - return k.getNFTCountMint(ctx, tokenType).Sub(k.getNFTCountBurn(ctx, tokenType)) -} -func (k Keeper) getNFTCountMint(ctx sdk.Context, tokenType string) sdk.Int { - return k.getTokenTypeMintCount(ctx, tokenType) -} - -func (k Keeper) getNFTCountBurn(ctx sdk.Context, tokenType string) sdk.Int { - return k.getTokenTypeBurnCount(ctx, tokenType) -} - -func (k Keeper) setNextTokenTypeFT(ctx sdk.Context, tokenType string) { - store := ctx.KVStore(k.storeKey) - tokenType = nextID(tokenType) - store.Set(types.NextTokenTypeFTKey(k.getContractID(ctx)), k.mustEncodeString(tokenType)) -} -func (k Keeper) setNextTokenTypeNFT(ctx sdk.Context, tokenType string) { - store := ctx.KVStore(k.storeKey) - tokenType = nextID(tokenType) - store.Set(types.NextTokenTypeNFTKey(k.getContractID(ctx)), k.mustEncodeString(tokenType)) -} -func (k Keeper) setNextTokenIndexNFT(ctx sdk.Context, tokenType, tokenIndex string) { - store := ctx.KVStore(k.storeKey) - tokenIndex = nextID(tokenIndex) - store.Set(types.NextTokenIDNFTKey(k.getContractID(ctx), tokenType), k.mustEncodeString(tokenIndex)) -} - -func (k Keeper) getNextTokenTypeFT(ctx sdk.Context) (tokenType string, err error) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.NextTokenTypeFTKey(k.getContractID(ctx))) - if bz == nil { - panic("next token type for ft should be exist") - } - tokenType = k.mustDecodeString(bz) - if tokenType[0] != types.FungibleFlag[0] { - return "", sdkerrors.Wrapf(types.ErrTokenTypeFull, "contract id: %s", k.getContractID(ctx)) - } - return tokenType, nil -} - -func (k Keeper) getNextTokenTypeNFT(ctx sdk.Context) (tokenType string, err error) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.NextTokenTypeNFTKey(k.getContractID(ctx))) - if bz == nil { - panic("next token type for nft should be exist") - } - tokenType = k.mustDecodeString(bz) - if tokenType == types.ReservedEmpty { - return "", sdkerrors.Wrapf(types.ErrTokenTypeFull, "contract id: %s", k.getContractID(ctx)) - } - return tokenType, nil -} - -func (k Keeper) getNextTokenIndexNFT(ctx sdk.Context, tokenType string) (tokenIndex string, error error) { - if !k.HasTokenType(ctx, tokenType) { - return "", sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", k.getContractID(ctx), tokenType) - } - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.NextTokenIDNFTKey(k.getContractID(ctx), tokenType)) - if bz == nil { - panic("next token id for nft token type should be exist") - } - tokenIndex = k.mustDecodeString(bz) - if tokenIndex == types.ReservedEmpty { - return "", sdkerrors.Wrapf(types.ErrTokenIndexFull, "ContractID: %s, TokenType: %s", k.getContractID(ctx), tokenType) - } - return tokenIndex, nil -} - -func (k Keeper) GetNextTokenIDFT(ctx sdk.Context) (string, error) { - if !k.ExistCollection(ctx) { - return "", sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - tokenType, err := k.getNextTokenTypeFT(ctx) - if err != nil { - return "", sdkerrors.Wrapf(types.ErrTokenIDFull, "ContractID: %s, TokenType: %s", k.getContractID(ctx), tokenType) - } - return tokenType + types.ReservedEmpty, nil -} -func (k Keeper) GetNextTokenIDNFT(ctx sdk.Context, tokenType string) (string, error) { - if !k.ExistCollection(ctx) { - return "", sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - tokenIndex, err := k.getNextTokenIndexNFT(ctx, tokenType) - if err != nil { - return "", err - } - - if tokenIndex == types.ReservedEmpty { - return "", sdkerrors.Wrapf(types.ErrTokenIndexFull, "ContractID: %s, TokenType: %s", k.getContractID(ctx), tokenType) - } - return tokenType + tokenIndex, nil -} - -func (k Keeper) iterateToken(ctx sdk.Context, prefix string, reverse bool, process func(types.Token) (stop bool)) { - store := ctx.KVStore(k.storeKey) - var iter sdk.Iterator - if reverse { - iter = sdk.KVStoreReversePrefixIterator(store, types.TokenKey(k.getContractID(ctx), prefix)) - } else { - iter = sdk.KVStorePrefixIterator(store, types.TokenKey(k.getContractID(ctx), prefix)) - } - defer iter.Close() - for { - if !iter.Valid() { - return - } - val := iter.Value() - token := k.mustDecodeToken(val) - if process(token) { - return - } - iter.Next() - } -} - -func (k Keeper) mustEncodeToken(token types.Token) (bz []byte) { - return k.cdc.MustMarshalBinaryBare(token) -} -func (k Keeper) mustDecodeToken(bz []byte) (token types.Token) { - k.cdc.MustUnmarshalBinaryBare(bz, &token) - return token -} - -func fromHex(s string) *big.Int { - r, ok := new(big.Int).SetString(s, 16) - if !ok { - panic("bad hex") - } - return r -} - -func toHex(r *big.Int) string { - return r.Text(16) -} - -func nextID(id string) (nextTokenID string) { - idInt := fromHex(id) - idInt = idInt.Add(idInt, big.NewInt(1)) - nextTokenID = strings.Repeat("0", len(id)) + toHex(idInt) - nextTokenID = nextTokenID[len(nextTokenID)-len(id):] - return nextTokenID -} diff --git a/x/collection/internal/keeper/token_test.go b/x/collection/internal/keeper/token_test.go deleted file mode 100644 index eeec55722f..0000000000 --- a/x/collection/internal/keeper/token_test.go +++ /dev/null @@ -1,282 +0,0 @@ -package keeper - -import ( - "strings" - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestKeeper_GetToken(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Token") - var expected types.Token - expected = types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.TokenKey(defaultContractID, defaultTokenIDFT), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Token") - { - actual, err := keeper.GetToken(ctx, defaultTokenIDFT) - require.NoError(t, err) - verifyTokenFunc(t, expected, actual) - } - t.Log("Prepare Token") - expected = types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.TokenKey(defaultContractID, defaultTokenID1), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Token") - { - actual, err := keeper.GetToken(ctx, defaultTokenID1) - require.NoError(t, err) - verifyTokenFunc(t, expected, actual) - } -} -func TestKeeper_SetToken(t *testing.T) { - ctx := cacheKeeper() - var expected types.Token - t.Log("Set Token") - expected = types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.SetToken(ctx, expected)) - } - t.Log("Compare Token") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenKey(defaultContractID, defaultTokenIDFT)) - actual := keeper.mustDecodeToken(bz) - verifyTokenFunc(t, expected, actual) - } - t.Log("Set Token") - expected = types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1) - { - require.NoError(t, keeper.SetToken(ctx, expected)) - } - t.Log("Compare Token") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenKey(defaultContractID, defaultTokenID1)) - actual := keeper.mustDecodeToken(bz) - verifyTokenFunc(t, expected, actual) - } -} - -func TestKeeper_UpdateToken(t *testing.T) { - ctx := cacheKeeper() - var expected, token types.Token - t.Log("Set Token") - token = types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.SetToken(ctx, token)) - } - t.Log("Update Token") - expected = types.NewFT(defaultContractID, defaultTokenIDFT, "modifiedname", defaultMeta, sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.UpdateToken(ctx, expected)) - } - t.Log("Compare Token") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenKey(defaultContractID, defaultTokenIDFT)) - actual := keeper.mustDecodeToken(bz) - verifyTokenFunc(t, expected, actual) - } - t.Log("Set Token") - token = types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1) - { - require.NoError(t, keeper.SetToken(ctx, token)) - } - t.Log("Update Token") - expected = types.NewFT(defaultContractID, defaultTokenID1, "modifiedname", defaultMeta, sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.UpdateToken(ctx, expected)) - } - t.Log("Compare Token") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenKey(defaultContractID, defaultTokenID1)) - actual := keeper.mustDecodeToken(bz) - verifyTokenFunc(t, expected, actual) - } -} - -func TestKeeper_GeTokens(t *testing.T) { - ctx := cacheKeeper() - var allTokens types.Tokens - t.Log("Prepare collection") - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - t.Log("Prepare FT Tokens") - expected := types.Tokens{ - types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true), - types.NewFT(defaultContractID, defaultTokenIDFT2, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true), - types.NewFT(defaultContractID, defaultTokenIDFT3, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true), - types.NewFT(defaultContractID, defaultTokenIDFT4, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true), - } - allTokens = append(allTokens, expected...) - { - for _, to := range expected { - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, to.(types.FT), sdk.NewInt(10))) - } - } - t.Log("Compare FT Tokens") - { - actual, err := keeper.GetFTs(ctx) - require.NoError(t, err) - for index := range expected { - verifyTokenFunc(t, expected[index], actual[index]) - } - } - t.Log("Prepare NFT Tokens") - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - expected = types.Tokens{ - types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1), - types.NewNFT(defaultContractID, defaultTokenID2, defaultName, defaultMeta, addr1), - types.NewNFT(defaultContractID, defaultTokenID3, defaultName, defaultMeta, addr1), - types.NewNFT(defaultContractID, defaultTokenID4, defaultName, defaultMeta, addr1), - types.NewNFT(defaultContractID, defaultTokenID5, defaultName, defaultMeta, addr1), - } - allTokens = append(allTokens, expected...) - { - for _, to := range expected { - require.NoError(t, keeper.MintNFT(ctx, addr1, to.(types.NFT))) - } - } - t.Log("Compare NFT Tokens") - { - actual, err := keeper.GetNFTs(ctx, defaultTokenType) - require.NoError(t, err) - for index := range expected { - verifyTokenFunc(t, expected[index], actual[index]) - } - } - t.Log("Compare NFT Tokens Count") - { - count, err := keeper.GetNFTCount(ctx, defaultTokenType) - require.NoError(t, err) - require.Equal(t, int64(5), count.Int64()) - } - - t.Log("Compare NFT Tokens Count Int") - { - count, err := keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTCount) - require.NoError(t, err) - require.Equal(t, int64(5), count.Int64()) - } - t.Log("Compare NFT Tokens Count Int") - { - count, err := keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTMint) - require.NoError(t, err) - require.Equal(t, int64(5), count.Int64()) - } - t.Log("Compare NFT Tokens Count Int") - { - count, err := keeper.GetNFTCountInt(ctx, defaultTokenType, types.QueryNFTBurn) - require.NoError(t, err) - require.Equal(t, int64(0), count.Int64()) - } - - t.Log("Compare All Tokens") - { - actual, err := keeper.GetTokens(ctx) - require.NoError(t, err) - for index := range allTokens { - verifyTokenFunc(t, allTokens[index], actual[index]) - } - } -} - -func TestKeeper_GetNextTokenIDFT(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare collection") - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - t.Log("Get Next Token ID FT") - { - tokenID, err := keeper.GetNextTokenIDFT(ctx) - require.NoError(t, err) - require.Equal(t, defaultTokenIDFT, tokenID) - } - t.Log("Issue a token and get next token id") - { - require.NoError(t, keeper.SetToken(ctx, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true))) - tokenID, err := keeper.GetNextTokenIDFT(ctx) - require.NoError(t, err) - require.Equal(t, defaultTokenIDFT2, tokenID) - } - t.Log("Set Full") - { - keeper.setNextTokenTypeFT(ctx, "0fffffff") - _, err := keeper.GetNextTokenIDFT(ctx) - require.Error(t, err) - } -} -func TestKeeper_GetNextTokenIDNFT(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare collection") - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - t.Log("Prepare Token Type") - expected := types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - { - require.NoError(t, keeper.SetTokenType(ctx, expected)) - } - t.Log("Get Next Token ID NFT") - { - tokenID, err := keeper.GetNextTokenIDNFT(ctx, defaultTokenType) - require.NoError(t, err) - require.Equal(t, defaultTokenID1, tokenID) - } - t.Log("Issue a token and get next token id") - { - require.NoError(t, keeper.SetToken(ctx, types.NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1))) - tokenID, err := keeper.GetNextTokenIDNFT(ctx, defaultTokenType) - require.NoError(t, err) - require.Equal(t, defaultTokenID2, tokenID) - } - t.Log("Set Full") - { - keeper.setNextTokenIndexNFT(ctx, defaultTokenType, "ffffffff") - _, err := keeper.GetNextTokenIDNFT(ctx, defaultTokenType) - require.Error(t, err) - } -} - -func TestKeeper_getNFTCountMint(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare collection") - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - t.Log("Prepare Token Type") - require.NoError(t, keeper.IssueNFT(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta), addr1)) - - keeper.setNextTokenIndexNFT(ctx, defaultTokenType, strings.Repeat("f", len(types.ReservedEmpty))) - require.Equal(t, int64(0), keeper.getNFTCountMint(ctx, defaultTokenType).Int64()) -} - -func TestNextTokenID(t *testing.T) { - require.Panics(t, func() { nextID("") }) - require.Equal(t, "b", nextID("a")) - require.Equal(t, "00", nextID("ff")) - require.Equal(t, "0001", nextID("0000")) - require.Equal(t, "000a", nextID("0009")) - require.Equal(t, "0010", nextID("000f")) - require.Equal(t, "0000", nextID("ffff")) - require.Equal(t, "00000000", nextID("ffffffff")) - require.Equal(t, "abce0000", nextID("abcdffff")) - require.Equal(t, "abcdabc1", nextID("abcdabc0")) - require.Equal(t, "abcd0001", nextID("abcd0000")) - require.Equal(t, "abcd0010", nextID("abcd000f")) - require.Equal(t, "abcdeef0", nextID("abcdeeef")) - require.Equal(t, "abcdef00", nextID("abcdeeff")) - require.Equal(t, "abcd999a", nextID("abcd9999")) - require.Equal(t, "abcd99a0", nextID("abcd999f")) - - next := "0000" - for idx := 0; idx < 16*16*16*16; idx++ { - next = nextID(next) - } - require.Equal(t, "0000", next) -} diff --git a/x/collection/internal/keeper/token_type.go b/x/collection/internal/keeper/token_type.go deleted file mode 100644 index 90e9f600d7..0000000000 --- a/x/collection/internal/keeper/token_type.go +++ /dev/null @@ -1,119 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type TokenTypeKeeper interface { - GetNextTokenType(ctx sdk.Context) (tokenType string, err error) - GetTokenTypes(ctx sdk.Context) (types.TokenTypes, error) - GetTokenType(ctx sdk.Context, tokenType string) (types.TokenType, error) - HasTokenType(ctx sdk.Context, tokenType string) bool - SetTokenType(ctx sdk.Context, token types.TokenType) error - UpdateTokenType(ctx sdk.Context, token types.TokenType) error -} - -var _ TokenTypeKeeper = (*Keeper)(nil) - -func (k Keeper) SetTokenType(ctx sdk.Context, tokenType types.TokenType) error { - _, err := k.GetCollection(ctx) - if err != nil { - return err - } - store := ctx.KVStore(k.storeKey) - if store.Has(types.TokenTypeKey(k.getContractID(ctx), tokenType.GetTokenType())) { - return sdkerrors.Wrapf(types.ErrTokenTypeExist, "ContractID: %s, TokenType: %s", k.getContractID(ctx), tokenType.GetTokenType()) - } - store.Set(types.TokenTypeKey(k.getContractID(ctx), tokenType.GetTokenType()), k.cdc.MustMarshalBinaryBare(tokenType)) - k.setNextTokenTypeNFT(ctx, tokenType.GetTokenType()) - k.setNextTokenIndexNFT(ctx, tokenType.GetTokenType(), types.ReservedEmpty) - return nil -} - -func (k Keeper) UpdateTokenType(ctx sdk.Context, tokenType types.TokenType) error { - _, err := k.GetCollection(ctx) - if err != nil { - return err - } - store := ctx.KVStore(k.storeKey) - if !store.Has(types.TokenTypeKey(k.getContractID(ctx), tokenType.GetTokenType())) { - return sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", k.getContractID(ctx), tokenType.GetTokenType()) - } - store.Set(types.TokenTypeKey(k.getContractID(ctx), tokenType.GetTokenType()), k.cdc.MustMarshalBinaryBare(tokenType)) - return nil -} - -func (k Keeper) GetTokenType(ctx sdk.Context, tokenTypeID string) (types.TokenType, error) { - store := ctx.KVStore(k.storeKey) - tokenTypeKey := types.TokenTypeKey(k.getContractID(ctx), tokenTypeID) - bz := store.Get(tokenTypeKey) - if bz == nil { - return nil, sdkerrors.Wrapf(types.ErrTokenTypeNotExist, "ContractID: %s, TokenType: %s", k.getContractID(ctx), tokenTypeID) - } - tokenType := k.mustDecodeTokenType(bz) - return tokenType, nil -} - -func (k Keeper) GetTokenTypes(ctx sdk.Context) (tokenTypes types.TokenTypes, err error) { - _, err = k.GetCollection(ctx) - if err != nil { - return nil, err - } - k.iterateTokenTypes(ctx, "", false, func(t types.TokenType) bool { - tokenTypes = append(tokenTypes, t) - return false - }) - return tokenTypes, nil -} - -func (k Keeper) HasTokenType(ctx sdk.Context, tokenType string) bool { - store := ctx.KVStore(k.storeKey) - tokenTypeKey := types.TokenTypeKey(k.getContractID(ctx), tokenType) - return store.Has(tokenTypeKey) -} - -func (k Keeper) GetNextTokenType(ctx sdk.Context) (tokenType string, err error) { - if !k.ExistCollection(ctx) { - return "", sdkerrors.Wrapf(types.ErrCollectionNotExist, "ContractID: %s", k.getContractID(ctx)) - } - tokenType, err = k.getNextTokenTypeNFT(ctx) - if err != nil { - return "", err - } - if tokenType[0] == types.FungibleFlag[0] { - return "", sdkerrors.Wrapf(types.ErrTokenTypeFull, "ContractID: %s", k.getContractID(ctx)) - } - return tokenType, nil -} - -func (k Keeper) iterateTokenTypes(ctx sdk.Context, prefix string, reverse bool, process func(types.TokenType) (stop bool)) { - store := ctx.KVStore(k.storeKey) - var iter sdk.Iterator - if reverse { - iter = sdk.KVStoreReversePrefixIterator(store, types.TokenTypeKey(k.getContractID(ctx), prefix)) - } else { - iter = sdk.KVStorePrefixIterator(store, types.TokenTypeKey(k.getContractID(ctx), prefix)) - } - defer iter.Close() - for { - if !iter.Valid() { - return - } - val := iter.Value() - tokenType := k.mustDecodeTokenType(val) - if process(tokenType) { - return - } - iter.Next() - } -} - -func (k Keeper) mustDecodeTokenType(bz []byte) (tokenType types.TokenType) { - err := k.cdc.UnmarshalBinaryBare(bz, &tokenType) - if err != nil { - panic(err) - } - return tokenType -} diff --git a/x/collection/internal/keeper/token_type_test.go b/x/collection/internal/keeper/token_type_test.go deleted file mode 100644 index d07c214fc2..0000000000 --- a/x/collection/internal/keeper/token_type_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_GetTokenType(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Token Type") - expected := types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.TokenTypeKey(defaultContractID, defaultTokenType), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Token Type") - { - actual, err := keeper.GetTokenType(ctx, defaultTokenType) - require.NoError(t, err) - verifyTokenTypeFunc(t, expected, actual) - } -} - -func TestKeeper_SetTokenType(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare collection") - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - t.Log("Set Token Type") - expected := types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - { - require.NoError(t, keeper.SetTokenType(ctx, expected)) - } - t.Log("Compare Token Type") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenTypeKey(defaultContractID, defaultTokenType)) - actual := keeper.mustDecodeTokenType(bz) - verifyTokenTypeFunc(t, expected, actual) - } -} - -func TestKeeper_HasTokenType(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Token Type") - expected := types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.TokenTypeKey(defaultContractID, defaultTokenType), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Token Type") - { - require.True(t, keeper.HasTokenType(ctx, defaultTokenType)) - } -} - -func TestKeeper_UpdateTokenType(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare collection") - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - t.Log("Set Token Type") - expected := types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - { - require.NoError(t, keeper.SetTokenType(ctx, expected)) - } - t.Log("Update Token Type") - { - expected.SetName("modifiedname") - require.NoError(t, keeper.UpdateTokenType(ctx, expected)) - } - - t.Log("Get Token Type") - { - actual, err := keeper.GetTokenType(ctx, defaultTokenType) - require.NoError(t, err) - verifyTokenTypeFunc(t, expected, actual) - } -} - -func TestKeeper_GetNextTokenType(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare collection") - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - t.Log("Get Next Token Type") - { - tokenType, err := keeper.GetNextTokenType(ctx) - require.NoError(t, err) - require.Equal(t, defaultTokenType, tokenType) - } - t.Log("Set Token Type") - { - require.NoError(t, keeper.SetTokenType(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta))) - require.NoError(t, keeper.SetTokenType(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType2, defaultName, defaultMeta))) - require.NoError(t, keeper.SetTokenType(ctx, types.NewBaseTokenType(defaultContractID, defaultTokenType3, defaultName, defaultMeta))) - } - t.Log("Get TokenTypes") - { - tokenTypes, err := keeper.GetTokenTypes(ctx) - require.NoError(t, err) - require.Equal(t, tokenTypes[0].GetTokenType(), defaultTokenType) - require.Equal(t, tokenTypes[1].GetTokenType(), defaultTokenType2) - require.Equal(t, tokenTypes[2].GetTokenType(), defaultTokenType3) - } - t.Log("Get Next Token Type") - { - tokenType, err := keeper.GetNextTokenType(ctx) - require.NoError(t, err) - require.Equal(t, defaultTokenType4, tokenType) - } - t.Log("Set Full") - { - keeper.setNextTokenTypeNFT(ctx, "ffffffff") - _, err := keeper.getNextTokenTypeNFT(ctx) - require.Error(t, err) - } -} diff --git a/x/collection/internal/keeper/transfer.go b/x/collection/internal/keeper/transfer.go deleted file mode 100644 index 7efc63a6c4..0000000000 --- a/x/collection/internal/keeper/transfer.go +++ /dev/null @@ -1,179 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" -) - -type TransferKeeper interface { - TransferFT(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, amount ...types.Coin) error - TransferNFT(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, tokenID ...string) error - TransferFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, to sdk.AccAddress, amount ...types.Coin) error - TransferNFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, to sdk.AccAddress, tokenID ...string) error -} - -var _ TransferKeeper = (*Keeper)(nil) - -func (k Keeper) TransferFT(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, amount ...types.Coin) error { - if err := k.transferFT(ctx, from, to, amount); err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransferFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyAmount, types.NewCoins(amount...).String()), - ), - }) - - return nil -} - -func (k Keeper) transferFT(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, amount types.Coins) error { - return k.SendCoins(ctx, from, to, amount) -} - -func (k Keeper) TransferNFT(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, tokenIDs ...string) error { - for _, tokenID := range tokenIDs { - if err := k.transferNFT(ctx, from, to, tokenID); err != nil { - return err - } - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransferNFT, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - ), - }) - for _, tokenID := range tokenIDs { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransferNFT, - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - ), - }) - } - - return nil -} - -func (k Keeper) transferNFT(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, tokenID string) error { - store := ctx.KVStore(k.storeKey) - - token, err := k.GetToken(ctx, tokenID) - if err != nil { - return err - } - - nft, ok := token.(types.NFT) - if !ok { - return sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", token.GetTokenID()) - } - childToParentKey := types.TokenChildToParentKey(k.getContractID(ctx), nft.GetTokenID()) - if store.Has(childToParentKey) { - return sdkerrors.Wrapf(types.ErrTokenCannotTransferChildToken, "TokenID: %s", token.GetTokenID()) - } - if !from.Equals(nft.GetOwner()) { - return sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", token.GetTokenID(), from.String()) - } - if !from.Equals(to) { - if err := k.moveNFToken(ctx, from, to, nft); err != nil { - return err - } - } - - return nil -} - -func (k Keeper) TransferFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, to sdk.AccAddress, amount ...types.Coin) error { - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - if err := k.transferFT(ctx, from, to, amount); err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransferFTFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyAmount, types.NewCoins(amount...).String()), - ), - }) - - return nil -} - -// nolint:dupl -func (k Keeper) TransferNFTFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, to sdk.AccAddress, tokenIDs ...string) error { - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - for _, tokenID := range tokenIDs { - if err := k.transferNFT(ctx, from, to, tokenID); err != nil { - return err - } - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransferNFTFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - ), - }) - for _, tokenID := range tokenIDs { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransferNFTFrom, - sdk.NewAttribute(types.AttributeKeyTokenID, tokenID), - ), - }) - } - - return nil -} - -func (k Keeper) moveNFToken(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, token types.NFT) error { - if from.Equals(to) { - return nil - } - children, err := k.ChildrenOf(ctx, token.GetTokenID()) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeOperationTransferNFT, - sdk.NewAttribute(types.AttributeKeyTokenID, token.GetTokenID()), - ), - }) - - for _, child := range children { - err := k.moveNFToken(ctx, from, to, child.(types.NFT)) - if err != nil { - return err - } - } - - if err := k.ChangeNFTOwner(ctx, from, to, token.GetTokenID()); err != nil { - return err - } - token.SetOwner(to) - return k.UpdateToken(ctx, token) -} diff --git a/x/collection/internal/keeper/transfer_test.go b/x/collection/internal/keeper/transfer_test.go deleted file mode 100644 index cad3e9d9f9..0000000000 --- a/x/collection/internal/keeper/transfer_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func TestKeeper_TransferFT(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.TransferFT(ctx2, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10))), sdkerrors.Wrap(types.ErrInsufficientToken, "insufficient account funds[abcd1234]; account has no coin").Error()) - require.EqualError(t, keeper.TransferFT(ctx, addr2, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10))), sdkerrors.Wrap(types.ErrInsufficientToken, "insufficient account funds[abcdef01]; account has no coin").Error()) - require.EqualError(t, keeper.TransferFT(ctx, addr2, addr1, types.Coin{Denom: defaultTokenIDFT, Amount: sdk.NewInt(-1)}), sdkerrors.Wrap(types.ErrInvalidCoin, "send amount must be positive").Error()) - - require.NoError(t, keeper.TransferFT(ctx, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)))) - require.NoError(t, keeper.TransferFT(ctx, addr1, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)))) - require.NoError(t, keeper.TransferFT(ctx, addr1, addr3, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)))) -} - -func TestKeeper_TransferFTFrom(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.TransferFTFrom(ctx, addr1, addr2, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10))), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), defaultContractID).Error()) - - prepareProxy(ctx, t) - require.NoError(t, keeper.TransferFTFrom(ctx, addr1, addr2, addr1, types.NewCoin(defaultTokenIDFT, sdk.NewInt(10)))) -} - -func TestKeeper_TransferNFT(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, wrongContractID)) - require.EqualError(t, keeper.TransferNFT(ctx2, addr1, addr2, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", wrongContractID, defaultTokenID1).Error()) - require.EqualError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID6), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID6).Error()) - require.EqualError(t, keeper.TransferNFT(ctx, addr2, addr1, defaultTokenID1), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID1, addr2.String()).Error()) - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr1, defaultTokenID1)) - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID1)) -} - -func TestKeeper_TransferNFTFrom(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.EqualError(t, keeper.TransferNFTFrom(ctx, addr1, addr2, addr1, defaultTokenID1), sdkerrors.Wrapf(types.ErrCollectionNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr1.String(), addr2.String(), defaultContractID).Error()) - prepareProxy(ctx, t) - require.NoError(t, keeper.TransferNFTFrom(ctx, addr1, addr2, addr1, defaultTokenID1)) -} - -func TestTransferFTScenario(t *testing.T) { - ctx := cacheKeeper() - - // issue idf token - require.NoError(t, keeper.CreateCollection(ctx, types.NewCollection(defaultContractID, defaultName, defaultMeta, defaultImgURI), addr1)) - require.NoError(t, keeper.IssueFT(ctx, addr1, addr1, types.NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true), sdk.NewInt(defaultAmount))) - - // - // transfer success cases - // - require.NoError(t, keeper.TransferFT(ctx, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount/2)))) - - // - // transfer failure cases - // - // Insufficient coins - require.EqualError(t, keeper.TransferFT(ctx, addr1, addr2, types.NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))), sdkerrors.Wrap(types.ErrInsufficientToken, "insufficient account funds[abcdef01]; 500:0000000100000000 < 1000:0000000100000000").Error()) -} - -func TestTransferNFTScenario(t *testing.T) { - ctx := cacheKeeper() - prepareCollectionTokens(ctx, t) - - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID2)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID2, defaultTokenID3)) - require.NoError(t, keeper.Attach(ctx, addr1, defaultTokenID1, defaultTokenID4)) - - // - // transfer failure cases - // - - // transfer non-exist token : failure - require.EqualError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID8), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s, TokenID: %s", defaultContractID, defaultTokenID8).Error()) - - // transfer a child : failure - require.EqualError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID2), sdkerrors.Wrapf(types.ErrTokenCannotTransferChildToken, "TokenID: %s", defaultTokenID2).Error()) - require.EqualError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID3), sdkerrors.Wrapf(types.ErrTokenCannotTransferChildToken, "TokenID: %s", defaultTokenID3).Error()) - require.EqualError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID4), sdkerrors.Wrapf(types.ErrTokenCannotTransferChildToken, "TokenID: %s", defaultTokenID4).Error()) - - // transfer non-mine : failure - require.EqualError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID5), sdkerrors.Wrapf(types.ErrTokenNotOwnedBy, "TokenID: %s, Owner: %s", defaultTokenID5, addr1.String()).Error()) - - // transfer-cnft cft : failure - require.EqualError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenIDFT), sdkerrors.Wrapf(types.ErrTokenNotNFT, "TokenID: %s", defaultTokenIDFT).Error()) - - // - // transfer success cases - // - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID1)) - require.NoError(t, keeper.TransferNFT(ctx, addr2, addr1, defaultTokenID1)) - require.NoError(t, keeper.TransferNFT(ctx, addr1, addr2, defaultTokenID1)) - - // verify the owner of transferred tokens - // owner of token1 is addr2 - token1, err1 := keeper.GetToken(ctx, defaultTokenID1) - require.NoError(t, err1) - require.Equal(t, token1.(types.NFT).GetOwner(), addr2) - - // owner of token2 is addr2 - token2, err2 := keeper.GetToken(ctx, defaultTokenID2) - require.NoError(t, err2) - require.Equal(t, token2.(types.NFT).GetOwner(), addr2) - - // owner of token3 is addr2 - token3, err3 := keeper.GetToken(ctx, defaultTokenID3) - require.NoError(t, err3) - require.Equal(t, token3.(types.NFT).GetOwner(), addr2) - - // owner of token4 is addr2 - token4, err4 := keeper.GetToken(ctx, defaultTokenID4) - require.NoError(t, err4) - require.Equal(t, token4.(types.NFT).GetOwner(), addr2) -} diff --git a/x/collection/internal/legacy/upgrade.go b/x/collection/internal/legacy/upgrade.go deleted file mode 100644 index 177ded52c9..0000000000 --- a/x/collection/internal/legacy/upgrade.go +++ /dev/null @@ -1,13 +0,0 @@ -package legacy - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/upgrade" -) - -func UpgradeHandler(version string) upgrade.UpgradeHandler { - // XXX: return handler for the migration version - return func(ctx sdk.Context, plan upgrade.Plan) { - - } -} diff --git a/x/collection/internal/querier/querier.go b/x/collection/internal/querier/querier.go deleted file mode 100644 index 74cdc0820c..0000000000 --- a/x/collection/internal/querier/querier.go +++ /dev/null @@ -1,382 +0,0 @@ -package querier - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - abci "github.com/tendermint/tendermint/abci/types" -) - -// creates a querier for token REST endpoints -func NewQuerier(keeper keeper.Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - if len(path) >= 2 { - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, path[1])) - } - switch path[0] { - case types.QueryBalance: - return queryBalance(ctx, req, keeper) - case types.QueryBalances: - return queryBalances(ctx, req, keeper) - case types.QueryPerms: - return queryAccountPermission(ctx, req, keeper) - case types.QueryTokens: - return queryTokens(ctx, req, keeper) - case types.QueryTokensWithTokenType: - return queryTokensWithTokenType(ctx, req, keeper) - case types.QueryTokenTypes: - return queryTokenTypes(ctx, req, keeper) - case types.QueryCollections: - return queryCollections(ctx, req, keeper) - case types.QueryNFTCount: - return queryNFTCount(ctx, req, keeper, types.QueryNFTCount) - case types.QueryNFTMint: - return queryNFTCount(ctx, req, keeper, types.QueryNFTMint) - case types.QueryNFTBurn: - return queryNFTCount(ctx, req, keeper, types.QueryNFTBurn) - case types.QuerySupply: - return queryTotal(ctx, req, keeper, types.QuerySupply) - case types.QueryMint: - return queryTotal(ctx, req, keeper, types.QueryMint) - case types.QueryBurn: - return queryTotal(ctx, req, keeper, types.QueryBurn) - case types.QueryParent: - return queryParent(ctx, req, keeper) - case types.QueryRoot: - return queryRoot(ctx, req, keeper) - case types.QueryChildren: - return queryChildren(ctx, req, keeper) - case types.QueryApprovers: - return queryApprovers(ctx, req, keeper) - case types.QueryIsApproved: - return queryIsApproved(ctx, req, keeper) - default: - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown collection query endpoint") - } - } -} - -func queryBalance(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenIDAccAddressParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - if !keeper.HasContractID(ctx) { - return nil, sdkerrors.Wrap(types.ErrCollectionNotExist, ctx.Context().Value(contract.CtxKey{}).(string)) - } - - if !keeper.HasToken(ctx, params.TokenID) { - return nil, sdkerrors.Wrapf(types.ErrTokenNotExist, "%s %s", ctx.Context().Value(contract.CtxKey{}).(string), params.TokenID) - } - - var balance sdk.Int - if params.TokenID[0] == types.FungibleFlag[0] { - var err error - balance, err = keeper.GetBalance(ctx, params.TokenID, params.Addr) - if err != nil { - if _, err2 := keeper.GetAccount(ctx, params.Addr); err2 != nil { - balance = sdk.ZeroInt() - } else { - return nil, err - } - } - } else { - if keeper.HasNFTOwner(ctx, params.Addr, params.TokenID) { - balance = sdk.NewInt(1) - } else { - balance = sdk.NewInt(0) - } - } - - bz, err2 := keeper.MarshalJSONIndent(balance) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryBalances(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenIDAccAddressParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - coins := make([]types.Coin, 0) - if !keeper.HasContractID(ctx) { - return nil, sdkerrors.Wrap(types.ErrCollectionNotExist, ctx.Context().Value(contract.CtxKey{}).(string)) - } - // FT - acc, err := keeper.GetAccount(ctx, params.Addr) - if err == nil { - coins = acc.GetCoins() - } - - // NFT - tokenIds := keeper.GetNFTsOwner(ctx, params.Addr) - for _, tokenID := range tokenIds { - var coin types.Coin - coin.Amount = sdk.NewInt(1) - coin.Denom = tokenID - coins = append(coins, coin) - } - - bz, err2 := keeper.MarshalJSONIndent(coins) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -// nolint:dupl -func queryTokenTypes(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenIDParams - if len(req.Data) != 0 { - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - } - if len(params.TokenID) == 0 { - tokenTypes, err := keeper.GetTokenTypes(ctx) - if err != nil { - return nil, err - } - bz, err2 := keeper.MarshalJSONIndent(tokenTypes) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - return bz, nil - } - - tokenType, err := keeper.GetTokenType(ctx, params.TokenID) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(tokenType) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -// nolint:dupl -func queryTokens(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenIDParams - if len(req.Data) != 0 { - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - } - if len(params.TokenID) == 0 { - tokens, err := keeper.GetTokens(ctx) - if err != nil { - return nil, err - } - bz, err2 := keeper.MarshalJSONIndent(tokens) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - return bz, nil - } - - token, err := keeper.GetToken(ctx, params.TokenID) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(token) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryTokensWithTokenType(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenTypeParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - tokens, err := keeper.GetNFTs(ctx, params.TokenType) - if err != nil { - return nil, err - } - bz, err2 := keeper.MarshalJSONIndent(tokens) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - return bz, nil -} - -func queryAccountPermission(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - if len(req.Data) == 0 { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "data is nil") - } - var params types.QueryAccAddressParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - pms := keeper.GetPermissions(ctx, params.Addr) - - bz, err := keeper.MarshalJSONIndent(pms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryCollections(ctx sdk.Context, _ abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - collection, err := keeper.GetCollection(ctx) - if err != nil { - return nil, err - } - bz, err2 := keeper.MarshalJSONIndent(collection) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryNFTCount(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper, target string) ([]byte, error) { - var params types.QueryTokenIDParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - count, err := keeper.GetNFTCountInt(ctx, params.TokenID, target) - if err != nil { - return nil, err - } - bz, err2 := keeper.MarshalJSONIndent(count) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryParent(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenIDParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - token, err := keeper.ParentOf(ctx, params.TokenID) - if err != nil { - return nil, err - } - if token == nil { - return nil, nil - } - - bz, err2 := keeper.MarshalJSONIndent(token) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryRoot(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenIDParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - token, err := keeper.RootOf(ctx, params.TokenID) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(token) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryChildren(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryTokenIDParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - tokens, err := keeper.ChildrenOf(ctx, params.TokenID) - if err != nil { - return nil, err - } - if tokens == nil { - return nil, nil - } - - bz, err2 := keeper.MarshalJSONIndent(tokens) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryApprovers(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryProxyParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - approvers, err := keeper.GetApprovers(ctx, params.Proxy) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(approvers) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryIsApproved(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryIsApprovedParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - approved := keeper.IsApproved(ctx, params.Proxy, params.Approver) - - bz, err := keeper.MarshalJSONIndent(approved) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryTotal(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper, target string) ([]byte, error) { - var params types.QueryTokenIDParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - supply, err := keeper.GetTotalInt(ctx, params.TokenID, target) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(supply) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} diff --git a/x/collection/internal/querier/querier_encoder.go b/x/collection/internal/querier/querier_encoder.go deleted file mode 100644 index b4d5d9c8ab..0000000000 --- a/x/collection/internal/querier/querier_encoder.go +++ /dev/null @@ -1,247 +0,0 @@ -package querier - -// import ( -// "encoding/json" - -// "github.com/cosmos/cosmos-sdk/codec" -// sdk "github.com/cosmos/cosmos-sdk/types" -// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -// "github.com/line/lbm-sdk/v2/x/collection/internal/types" -// abci "github.com/tendermint/tendermint/abci/types" - -// "github.com/line/lbm-sdk/v2/x/wasm" -// ) - -// func NewQueryEncoder(collectionQuerier sdk.Querier) wasm.EncodeQuerier { -// return func(ctx sdk.Context, jsonQuerier json.RawMessage) ([]byte, error) { -// var customQuerier types.WasmCustomQuerier -// err := json.Unmarshal(jsonQuerier, &customQuerier) -// if err != nil { -// return nil, err -// } -// switch customQuerier.Route { -// case types.QueryCollections: -// return handleQueryCollections(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryBalance: -// return handleQueryBalances(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryBalances: -// return handleQueryBalances(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryTokenTypes: -// return handleQueryTokenTypes(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryTokens: -// return handleQueryTokens(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryTokensWithTokenType: -// return handleQueryTokensWithTokenType(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryNFTCount: -// return handleQueryNFTCount(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryNFTMint: -// return handleQueryNFTCount(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryNFTBurn: -// return handleQueryNFTCount(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QuerySupply: -// return handleQueryTotal(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryMint: -// return handleQueryTotal(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryBurn: -// return handleQueryTotal(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryParent: -// return handleQueryRootOrParentOrChildren(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryRoot: -// return handleQueryRootOrParentOrChildren(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryChildren: -// return handleQueryRootOrParentOrChildren(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryPerms: -// return handleQueryPerms(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryApprovers: -// return handleQueryApprovers(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryIsApproved: -// return handleQueryApproved(ctx, collectionQuerier, []string{customQuerier.Route}, customQuerier.Data) -// default: -// return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized Msg route: %T", customQuerier.Route) -// } -// } -// } - -// func handleQueryCollections(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryCollectionWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// req := makeRequestQuery(nil) - -// contractID := wrapper.CollectionParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryBalances(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryBalanceWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryTokenIDAccAddressParams(wrapper.BalanceParam.TokenID, wrapper.BalanceParam.Addr) -// req := makeRequestQuery(param) - -// contractID := wrapper.BalanceParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryTokenTypes(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryTokenTypesWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryTokenIDParams(wrapper.TokenTypesParam.TokenID) -// req := makeRequestQuery(param) - -// contractID := wrapper.TokenTypesParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryTokens(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryTokensWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryTokenIDParams(wrapper.TokensParam.TokenID) -// req := makeRequestQuery(param) - -// contractID := wrapper.TokensParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryTokensWithTokenType(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryTokenTypeWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryTokenTypeParams(wrapper.TokenTypeParam.TokenType) -// req := makeRequestQuery(param) - -// contractID := wrapper.TokenTypeParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryNFTCount(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryNFTCountWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryTokenIDParams(wrapper.TokensParam.TokenID) -// req := makeRequestQuery(param) - -// contractID := wrapper.TokensParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryTotal(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryTotalWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// params := types.NewQueryTokenIDParams(wrapper.TotalParam.TokenID) -// req := makeRequestQuery(params) - -// contractID := wrapper.TotalParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } - -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryRootOrParentOrChildren(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryTokensWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryTokenIDParams(wrapper.TokensParam.TokenID) -// req := makeRequestQuery(param) - -// contractID := wrapper.TokensParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryPerms(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryPermsWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryAccAddressParams(wrapper.PermParam.Address) -// req := makeRequestQuery(param) - -// contractID := wrapper.PermParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryApproved(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryApprovedWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryIsApprovedParams(wrapper.IsApprovedParam.Proxy, wrapper.IsApprovedParam.Approver) -// req := makeRequestQuery(param) - -// contractID := wrapper.IsApprovedParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func handleQueryApprovers(ctx sdk.Context, collectionQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryApproversWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// param := types.NewQueryApproverParams(wrapper.ApproversParam.Proxy) -// req := makeRequestQuery(param) - -// contractID := wrapper.ApproversParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return collectionQuerier(ctx, path, req) -// } - -// func makeRequestQuery(params interface{}) abci.RequestQuery { -// req := abci.RequestQuery{ -// Path: "", -// Data: []byte(string(codec.MustMarshalJSONIndent(types.ModuleCdc, params))), -// } -// return req -// } diff --git a/x/collection/internal/querier/querier_encoder_test.go b/x/collection/internal/querier/querier_encoder_test.go deleted file mode 100644 index 856cad0512..0000000000 --- a/x/collection/internal/querier/querier_encoder_test.go +++ /dev/null @@ -1,442 +0,0 @@ -package querier - -// import ( -// "bytes" -// "encoding/json" -// "fmt" -// "testing" - -// sdk "github.com/cosmos/cosmos-sdk/types" -// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -// "github.com/line/lbm-sdk/v2/x/collection/internal/types" -// "github.com/line/lbm-sdk/v2/x/wasm" -// "github.com/stretchr/testify/require" -// ) - -// var ( -// collectionQueryEncoder wasm.EncodeQuerier -// ) - -// func setupQueryEncoder() { -// collectionQuerier := NewQuerier(ckeeper) - -// collectionQueryEncoder = NewQueryEncoder(collectionQuerier) -// } - -// func encodeQuery(t *testing.T, jsonQuerier json.RawMessage, result interface{}) error { -// res, err := collectionQueryEncoder(ctx, jsonQuerier) -// if len(res) > 0 { -// require.NoError(t, ckeeper.UnmarshalJSON(res, result)) -// } -// return err -// } - -// func TestNewQuerier_encodeQueryBalance(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"balance","data":{"balance_param":{"contract_id":"%s", "token_id":"%s", "addr":"%s"}}}`, contractID, tokenFTID, addr1) - -// var balance sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &balance) -// require.NoError(t, err) -// require.True(t, balance.Equal(sdk.NewInt(1000))) -// } - -// func TestNewQuerier_encodeQueryBalances(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"balances","data":{"balance_param":{"contract_id":"%s", "token_id":"%s", "addr":"%s"}}}`, contractID, "", addr1) - -// var coins types.Coins -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &coins) -// require.NoError(t, err) -// require.Equal(t, tokenFTID, coins[0].Denom) -// require.Equal(t, sdk.NewInt(tokenFTSupply), coins[0].Amount) -// require.Equal(t, tokenNFTID1, coins[1].Denom) -// require.Equal(t, sdk.NewInt(1), coins[1].Amount) -// require.Equal(t, tokenNFTID2, coins[2].Denom) -// require.Equal(t, sdk.NewInt(1), coins[2].Amount) -// require.Equal(t, tokenNFTID3, coins[3].Denom) -// require.Equal(t, sdk.NewInt(1), coins[3].Amount) -// paramsNoExist1 := types.QueryAccAddressParams{ -// Addr: addr3, -// } -// var coinsEmpty types.Coins -// query(t, paramsNoExist1, types.QueryBalances, &coinsEmpty) -// require.Empty(t, coinsEmpty) -// } - -// func TestNewQuerier_encodeQueryBalanceNonExistentAccount(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"balance","data":{"balance_param":{"contract_id":"%s", "token_id":"%s", "addr":"%s"}}}`, contractID, tokenFTID, addr3) - -// var balance sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &balance) -// require.NoError(t, err) -// require.True(t, balance.Equal(sdk.NewInt(0))) -// } - -// func TestNewQuerier_encodeQueryBalanceNonExistentContractID(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// contractID := "12345678" -// jsonQuerier := fmt.Sprintf(`{"route":"balance","data":{"balance_param":{"contract_id":"%s", "token_id":"%s", "addr":"%s"}}}`, contractID, tokenFTID, addr1) - -// var balance sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &balance) -// require.Error(t, err, sdkerrors.Wrap(types.ErrCollectionNotExist, contractID)) -// } - -// func TestNewQuerier_encodeQueryBalanceNonExistentTokenID(t *testing.T) { -// prepare(t) - -// tokenID := "00000009" + tokenFTIndex -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"balance","data":{"balance_param":{"contract_id":"%s", "token_id":"%s", "addr":"%s"}}}`, contractID, tokenID, addr1) - -// var balance sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &balance) -// require.Error(t, err, sdkerrors.Wrapf(types.ErrCollectionNotExist, "%s %s", contractID, tokenID)) -// } - -// func TestNewQuerier_encodeQueryAccountPermission(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"perms","data":{"perm_param":{"contract_id":"%s", "address":"%s"}}}`, contractID, addr1) - -// var permissions types.Permissions -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &permissions) -// require.NoError(t, err) - -// require.Equal(t, len(permissions), 4) -// require.Equal(t, permissions[0].String(), "issue") -// require.Equal(t, permissions[1].String(), "mint") -// require.Equal(t, permissions[2].String(), "burn") -// require.Equal(t, permissions[3].String(), "modify") -// } - -// func TestNewQuerier_encodeQueryTokens_FT(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"tokens","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenFTID) - -// var token types.Token -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &token) -// require.NoError(t, err) -// require.Equal(t, token.GetContractID(), contractID) -// require.Equal(t, token.GetTokenID(), tokenFTID) -// require.Equal(t, token.GetName(), tokenFTName) -// require.Equal(t, token.GetTokenType(), tokenFTType) -// require.Equal(t, token.GetTokenIndex(), tokenFTIndex) -// } - -// func TestNewQuerier_encodeQueryTokens_NFT(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"tokens","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTID1) - -// var token types.Token -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &token) -// require.NoError(t, err) -// require.Equal(t, token.GetContractID(), contractID) -// require.Equal(t, token.GetTokenID(), tokenNFTID1) -// require.Equal(t, token.GetName(), tokenNFTName1) -// require.Equal(t, token.GetTokenType(), tokenNFTType) -// require.Equal(t, token.GetTokenIndex(), tokenNFTIndex1) -// } - -// func TestNewQuerier_encodeQueryTokens_all(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"tokens","data":{"tokens_param":{"contract_id":"%s", "token_id":""}}}`, contractID) - -// var tokens types.Tokens -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &tokens) -// require.NoError(t, err) -// require.Equal(t, len(tokens), 4) -// require.Equal(t, tokens[0].GetContractID(), contractID) -// require.Equal(t, tokens[0].GetTokenID(), tokenFTID) -// require.Equal(t, tokens[0].GetName(), tokenFTName) -// require.Equal(t, tokens[0].GetTokenType(), tokenFTType) -// require.Equal(t, tokens[0].GetTokenIndex(), tokenFTIndex) -// require.Equal(t, tokens[1].GetContractID(), contractID) -// require.Equal(t, tokens[1].GetTokenID(), tokenNFTID1) -// require.Equal(t, tokens[1].GetName(), tokenNFTName1) -// require.Equal(t, tokens[1].GetTokenType(), tokenNFTType) -// require.Equal(t, tokens[1].GetTokenIndex(), tokenNFTIndex1) -// require.Equal(t, tokens[2].GetContractID(), contractID) -// require.Equal(t, tokens[2].GetTokenID(), tokenNFTID2) -// require.Equal(t, tokens[2].GetName(), tokenNFTName2) -// require.Equal(t, tokens[2].GetTokenType(), tokenNFTType) -// require.Equal(t, tokens[2].GetTokenIndex(), tokenNFTIndex2) -// require.Equal(t, tokens[3].GetContractID(), contractID) -// require.Equal(t, tokens[3].GetTokenID(), tokenNFTID3) -// require.Equal(t, tokens[3].GetName(), tokenNFTName3) -// require.Equal(t, tokens[3].GetTokenType(), tokenNFTType) -// require.Equal(t, tokens[3].GetTokenIndex(), tokenNFTIndex3) -// } - -// func TestNewQuerier_encodeQueryTokenTypes_one(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"tokentypes","data":{"tokentypes_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTType) - -// var tokenType types.TokenType -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &tokenType) -// require.NoError(t, err) -// require.Equal(t, tokenType.GetContractID(), contractID) -// require.Equal(t, tokenType.GetTokenType(), tokenNFTType) -// require.Equal(t, tokenType.GetName(), tokenNFTTypeName) -// } - -// func TestNewQuerier_encodeQueryTokenTypes_all(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"tokentypes","data":{"tokentypes_param":{"contract_id":"%s", "token_id":""}}}`, contractID) - -// var tokenTypes types.TokenTypes -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &tokenTypes) -// require.NoError(t, err) -// require.Equal(t, len(tokenTypes), 1) -// require.Equal(t, tokenTypes[0].GetContractID(), contractID) -// require.Equal(t, tokenTypes[0].GetTokenType(), tokenNFTType) -// require.Equal(t, tokenTypes[0].GetName(), tokenNFTTypeName) -// } - -// func TestNewQuerier_encodeQueryTokensWithTokenType(t *testing.T) { -// prepare(t) -// setupQueryEncoder() - -// jsonQuerier := fmt.Sprintf(`{"route":"tokensWithTokenType","data":{"token_type_param":{"contract_id":"%s", "token_type":"%s"}}}`, contractID, tokenNFTType) -// var tokens types.Tokens -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &tokens) -// require.NoError(t, err) -// require.Equal(t, len(tokens), 3) -// require.Equal(t, tokens[0].GetContractID(), contractID) -// require.Equal(t, tokens[0].GetName(), tokenNFTName1) -// require.Equal(t, tokens[0].GetTokenType(), tokenNFTType) -// require.Equal(t, tokens[1].GetContractID(), contractID) -// require.Equal(t, tokens[1].GetName(), tokenNFTName2) -// require.Equal(t, tokens[1].GetTokenType(), tokenNFTType) -// require.Equal(t, tokens[2].GetContractID(), contractID) -// require.Equal(t, tokens[2].GetName(), tokenNFTName3) -// require.Equal(t, tokens[2].GetTokenType(), tokenNFTType) - -// var tokens2 types.Tokens -// jsonQuerier = fmt.Sprintf(`{"route":"tokensWithTokenType","data":{"token_type_param":{"contract_id":"%s", "token_type":"%s"}}}`, contractID, tokenFTType) -// err = encodeQuery(t, json.RawMessage(jsonQuerier), &tokens2) -// require.NoError(t, err) -// require.Equal(t, len(tokens2), 1) -// require.Equal(t, tokens2[0].GetContractID(), contractID) -// require.Equal(t, tokens2[0].GetName(), tokenFTName) -// require.Equal(t, tokens2[0].GetTokenType(), tokenFTType) - -// tokenType := "99999999" -// var tokensNoExist types.Tokens -// jsonQuerier = fmt.Sprintf(`{"route":"tokensWithTokenType","data":{"token_type_param":{"contract_id":"%s", "token_type":"%s"}}}`, contractID, tokenType) -// err = encodeQuery(t, json.RawMessage(jsonQuerier), &tokensNoExist) -// require.NoError(t, err) -// require.Equal(t, len(tokensNoExist), 0) -// require.Empty(t, tokensNoExist) -// } - -// func TestNewQuerier_encodeQueryCollections_one(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"collections","data":{"collection_param":{"contract_id":"%s"}}}`, contractID) - -// var collection types.Collection -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &collection) -// require.NoError(t, err) -// require.Equal(t, collection.GetContractID(), contractID) -// require.Equal(t, collection.GetName(), collectionName) -// require.Equal(t, collection.GetBaseImgURI(), imageURL) -// } - -// func TestNewQuerier_encodeQueryNFTCount(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"nftcount","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTType) - -// var count sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &count) -// require.NoError(t, err) -// require.Equal(t, count, sdk.NewInt(3)) -// } - -// func TestNewQuerier_encodeQueryTotalMint_NFT(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"nftmint","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTType) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, int64(3), supply.Int64()) -// } - -// func TestNewQuerier_encodeQueryTotalBurn_NFT(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"nftburn","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTType) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, supply.Int64(), int64(0)) -// } - -// func TestNewQuerier_encodeQueryTotalSupply_FT(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"%s","data":{"total_param":{"contract_id":"%s", "token_id":"%s"}}}`, types.QuerySupply, contractID, tokenFTID) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, supply.Int64(), int64(tokenFTSupply)) -// } - -// func TestNewQuerier_encodeQueryTotalMint_FT(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"%s","data":{"total_param":{"contract_id":"%s", "token_id":"%s"}}}`, types.QueryMint, contractID, tokenFTID) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, supply.Int64(), int64(tokenFTSupply)) -// } - -// func TestNewQuerier_encodeQueryTotalBurn_FT(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"%s","data":{"total_param":{"contract_id":"%s", "token_id":"%s"}}}`, types.QueryBurn, contractID, tokenFTID) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, supply.Int64(), int64(0)) -// } - -// func TestNewQuerier_encodeQueryParent(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"parent","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTID2) - -// var token types.Token -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &token) -// require.NoError(t, err) -// require.Equal(t, token.GetContractID(), contractID) -// require.Equal(t, token.GetTokenID(), tokenNFTID1) -// } - -// func TestNewQuerier_encodeQueryParent_nil(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"parent","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTID1) - -// var token types.Token -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &token) -// require.NoError(t, err) -// require.Equal(t, token, nil) -// } - -// func TestNewQuerier_encodeQueryRoot(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"root","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTID3) - -// var token types.Token -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &token) -// require.NoError(t, err) -// require.Equal(t, token.GetContractID(), contractID) -// require.Equal(t, token.GetTokenID(), tokenNFTID1) -// } - -// func TestNewQuerier_encodeQueryRoot_self(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"root","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTID1) - -// var token types.Token -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &token) -// require.NoError(t, err) -// require.Equal(t, token.GetContractID(), contractID) -// require.Equal(t, token.GetTokenID(), tokenNFTID1) -// } - -// func TestNewQuerier_encodeQueryChildren(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"children","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTID1) - -// var tokens types.Tokens -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &tokens) -// require.NoError(t, err) -// require.Equal(t, len(tokens), 2) -// require.Equal(t, tokens[0].GetContractID(), contractID) -// require.Equal(t, tokens[0].GetTokenID(), tokenNFTID2) -// require.Equal(t, tokens[1].GetContractID(), contractID) -// require.Equal(t, tokens[1].GetTokenID(), tokenNFTID3) -// } - -// func TestNewQuerier_encodeQueryChildren_empty(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"children","data":{"tokens_param":{"contract_id":"%s", "token_id":"%s"}}}`, contractID, tokenNFTID2) - -// var tokens types.Tokens -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &tokens) -// require.NoError(t, err) -// require.Equal(t, len(tokens), 0) -// } - -// func TestNewQuerier_encodeQueryApprovers(t *testing.T) { -// prepare(t) - -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"approver","data":{"approvers_param":{"contract_id":"%s", "proxy":"%s"}}}`, contractID, addr1) - -// var acAd1 []sdk.AccAddress -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &acAd1) -// require.NoError(t, err) -// require.Equal(t, 2, len(acAd1)) -// if bytes.Compare(addr2, addr3) <= 0 { -// require.Equal(t, addr2, acAd1[0]) -// require.Equal(t, addr3, acAd1[1]) -// } else { -// require.Equal(t, addr2, acAd1[1]) -// require.Equal(t, addr3, acAd1[0]) -// } - -// var acAdEmpty []sdk.AccAddress -// paramsEmpty := types.QueryProxyParams{ -// Proxy: addr2, -// } -// query(t, paramsEmpty, types.QueryApprovers, &acAdEmpty) -// require.Empty(t, acAdEmpty) -// } - -// func TestNewQuerier_encodeQueryIsApproved_true(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"approved","data":{"is_approved_param":{"contract_id":"%s", "proxy":"%s", "approver":"%s"}}}`, contractID, addr1, addr2) - -// var approved bool -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &approved) -// require.NoError(t, err) -// require.True(t, approved) -// } - -// func TestNewQuerier_encodeQueryIsApproved_false(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"approved","data":{"is_approved_param":{"contract_id":"%s", "proxy":"%s", "approver":"%s"}}}`, contractID, addr2, addr1) - -// var approved bool -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &approved) -// require.NoError(t, err) -// require.False(t, approved) -// } diff --git a/x/collection/internal/querier/querier_test.go b/x/collection/internal/querier/querier_test.go deleted file mode 100644 index 7f09614bed..0000000000 --- a/x/collection/internal/querier/querier_test.go +++ /dev/null @@ -1,554 +0,0 @@ -package querier - -import ( - "bytes" - "context" - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - contractID = "9be17165" - collectionName = "mycol" - imageURL = "url" - meta = "meta" - tokenFTType = "00000001" - tokenFTIndex = "00000000" - tokenFTID = tokenFTType + tokenFTIndex - tokenFTSupply = 1000 - tokenNFTType = "10000001" - tokenNFTIndex1 = "00000001" - tokenNFTIndex2 = "00000002" - tokenNFTIndex3 = "00000003" - tokenNFTID1 = tokenNFTType + tokenNFTIndex1 - tokenNFTID2 = tokenNFTType + tokenNFTIndex2 /* #nosec */ - tokenNFTID3 = tokenNFTType + tokenNFTIndex3 /* #nosec */ - tokenNFTTypeName = "sword" - tokenFTName = "ft_token" - tokenNFTName1 = "nft_token1" /* #nosec */ - tokenNFTName2 = "nft_token2" /* #nosec */ - tokenNFTName3 = "nft_token3" /* #nosec */ -) - -var ( - ms store.CommitMultiStore - ctx sdk.Context - ckeeper keeper.Keeper - addr1 sdk.AccAddress - addr2 sdk.AccAddress - addr3 sdk.AccAddress -) - -func prepare(t *testing.T) { - ctx, ms, ckeeper = keeper.TestKeeper() - msCache := ms.CacheMultiStore() - ctx = ctx.WithMultiStore(msCache) - - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr3 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - // prepare contract ID - newContractID := ckeeper.NewContractID(ctx) - require.Equal(t, contractID, newContractID) - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, contractID)) - - // prepare collection - require.NoError(t, ckeeper.CreateCollection(ctx2, types.NewCollection(contractID, collectionName, meta, imageURL), addr1)) - require.NoError(t, ckeeper.IssueFT(ctx2, addr1, addr1, types.NewFT(contractID, tokenFTID, tokenFTName, meta, sdk.NewInt(1), true), sdk.NewInt(tokenFTSupply))) - require.NoError(t, ckeeper.IssueNFT(ctx2, types.NewBaseTokenType(contractID, tokenNFTType, tokenNFTTypeName, meta), addr1)) - require.NoError(t, ckeeper.MintNFT(ctx2, addr1, types.NewNFT(contractID, tokenNFTID1, tokenNFTName1, meta, addr1))) - require.NoError(t, ckeeper.MintNFT(ctx2, addr1, types.NewNFT(contractID, tokenNFTID2, tokenNFTName2, meta, addr1))) - require.NoError(t, ckeeper.MintNFT(ctx2, addr1, types.NewNFT(contractID, tokenNFTID3, tokenNFTName3, meta, addr1))) - - require.NoError(t, ckeeper.Attach(ctx2, addr1, tokenNFTID1, tokenNFTID2)) - require.NoError(t, ckeeper.Attach(ctx2, addr1, tokenNFTID1, tokenNFTID3)) - require.NoError(t, ckeeper.GrantPermission(ctx2, addr1, addr2, types.NewMintPermission())) - require.NoError(t, ckeeper.SetApproved(ctx2, addr1, addr2)) - require.NoError(t, ckeeper.SetApproved(ctx2, addr1, addr3)) -} - -func query(t *testing.T, params interface{}, query string, result interface{}) { - res, err := queryInternal(params, query, contractID) - require.NoError(t, err) - if len(res) > 0 { - require.NoError(t, ckeeper.UnmarshalJSON(res, result)) - } -} - -func queryInternal(params interface{}, query, contractID string) ([]byte, error) { - req := abci.RequestQuery{ - Path: "", - Data: []byte(string(codec.MustMarshalJSONIndent(types.ModuleCdc, params))), - } - if params == nil { - req.Data = nil - } - path := []string{query} - if contractID != "" { - path = append(path, contractID) - } - querier := NewQuerier(ckeeper) - return querier(ctx, path, req) -} - -func TestNewQuerier_queryBalance(t *testing.T) { - prepare(t) - params := types.QueryTokenIDAccAddressParams{ - TokenID: tokenFTID, - Addr: addr1, - } - var balance sdk.Int - query(t, params, types.QueryBalance, &balance) - require.True(t, balance.Equal(sdk.NewInt(1000))) -} - -func TestNewQuerier_queryBalances(t *testing.T) { - prepare(t) - params := types.QueryAccAddressParams{ - Addr: addr1, - } - var coins types.Coins - query(t, params, types.QueryBalances, &coins) - require.Equal(t, tokenFTID, coins[0].Denom) - require.Equal(t, sdk.NewInt(tokenFTSupply), coins[0].Amount) - require.Equal(t, tokenNFTID1, coins[1].Denom) - require.Equal(t, sdk.NewInt(1), coins[1].Amount) - require.Equal(t, tokenNFTID2, coins[2].Denom) - require.Equal(t, sdk.NewInt(1), coins[2].Amount) - require.Equal(t, tokenNFTID3, coins[3].Denom) - require.Equal(t, sdk.NewInt(1), coins[3].Amount) - paramsNoExist1 := types.QueryAccAddressParams{ - Addr: addr3, - } - var coinsEmpty types.Coins - query(t, paramsNoExist1, types.QueryBalances, &coinsEmpty) - require.Empty(t, coinsEmpty) -} - -func TestNewQuerier_queryBalanceOwnedNFT(t *testing.T) { - prepare(t) - params := types.QueryTokenIDAccAddressParams{ - TokenID: tokenNFTID1, - Addr: addr1, - } - var balance sdk.Int - query(t, params, types.QueryBalance, &balance) - require.True(t, balance.Equal(sdk.NewInt(1))) -} - -func TestNewQuerier_queryBalanceNoOwnedNFT(t *testing.T) { - prepare(t) - params := types.QueryTokenIDAccAddressParams{ - TokenID: tokenNFTID1, - Addr: addr2, - } - var balance sdk.Int - query(t, params, types.QueryBalance, &balance) - require.True(t, balance.Equal(sdk.NewInt(0))) -} - -func TestNewQuerier_queryBalanceNonExistentAccount(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDAccAddressParams{ - TokenID: tokenFTID, - Addr: addr3, - } - var balance sdk.Int - query(t, params, types.QueryBalance, &balance) - require.True(t, balance.Equal(sdk.NewInt(0))) -} - -func TestNewQuerier_queryBalanceNonExistentContractID(t *testing.T) { - prepare(t) - - contractID := "12345678" - params := types.QueryTokenIDAccAddressParams{ - TokenID: tokenFTID, - Addr: addr1, - } - _, err := queryInternal(params, types.QueryBalance, contractID) - require.Error(t, err, sdkerrors.Wrap(types.ErrCollectionNotExist, contractID)) -} - -func TestNewQuerier_queryBalanceNonExistentTokenID(t *testing.T) { - prepare(t) - - tokenID := "00000009" + tokenFTIndex - params := types.QueryTokenIDAccAddressParams{ - TokenID: tokenID, - Addr: addr1, - } - _, err := queryInternal(params, types.QueryBalance, contractID) - require.Error(t, err, sdkerrors.Wrapf(types.ErrCollectionNotExist, "%s %s", contractID, tokenID)) -} - -func TestNewQuerier_queryAccountPermission(t *testing.T) { - prepare(t) - - params := types.NewQueryAccAddressParams(addr1) - var permissions types.Permissions - query(t, params, types.QueryPerms, &permissions) - require.Equal(t, len(permissions), 4) - require.Equal(t, permissions[0].String(), "issue") - require.Equal(t, permissions[1].String(), "mint") - require.Equal(t, permissions[2].String(), "burn") - require.Equal(t, permissions[3].String(), "modify") -} - -func TestNewQuerier_queryTokens_FT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenFTID, - } - var token types.Token - query(t, params, types.QueryTokens, &token) - require.Equal(t, token.GetContractID(), contractID) - require.Equal(t, token.GetTokenID(), tokenFTID) - require.Equal(t, token.GetName(), tokenFTName) - require.Equal(t, token.GetTokenType(), tokenFTType) - require.Equal(t, token.GetTokenIndex(), tokenFTIndex) -} - -func TestNewQuerier_queryTokens_NFT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID1, - } - var token types.Token - query(t, params, types.QueryTokens, &token) - require.Equal(t, token.GetContractID(), contractID) - require.Equal(t, token.GetTokenID(), tokenNFTID1) - require.Equal(t, token.GetName(), tokenNFTName1) - require.Equal(t, token.GetTokenType(), tokenNFTType) - require.Equal(t, token.GetTokenIndex(), tokenNFTIndex1) -} - -func TestNewQuerier_queryTokens_all(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: "", - } - var tokens types.Tokens - query(t, params, types.QueryTokens, &tokens) - require.Equal(t, len(tokens), 4) - require.Equal(t, tokens[0].GetContractID(), contractID) - require.Equal(t, tokens[0].GetTokenID(), tokenFTID) - require.Equal(t, tokens[0].GetName(), tokenFTName) - require.Equal(t, tokens[0].GetTokenType(), tokenFTType) - require.Equal(t, tokens[0].GetTokenIndex(), tokenFTIndex) - require.Equal(t, tokens[1].GetContractID(), contractID) - require.Equal(t, tokens[1].GetTokenID(), tokenNFTID1) - require.Equal(t, tokens[1].GetName(), tokenNFTName1) - require.Equal(t, tokens[1].GetTokenType(), tokenNFTType) - require.Equal(t, tokens[1].GetTokenIndex(), tokenNFTIndex1) - require.Equal(t, tokens[2].GetContractID(), contractID) - require.Equal(t, tokens[2].GetTokenID(), tokenNFTID2) - require.Equal(t, tokens[2].GetName(), tokenNFTName2) - require.Equal(t, tokens[2].GetTokenType(), tokenNFTType) - require.Equal(t, tokens[2].GetTokenIndex(), tokenNFTIndex2) - require.Equal(t, tokens[3].GetContractID(), contractID) - require.Equal(t, tokens[3].GetTokenID(), tokenNFTID3) - require.Equal(t, tokens[3].GetName(), tokenNFTName3) - require.Equal(t, tokens[3].GetTokenType(), tokenNFTType) - require.Equal(t, tokens[3].GetTokenIndex(), tokenNFTIndex3) -} - -func TestNewQuerier_queryTokenTypes_one(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTType, - } - var tokenType types.TokenType - query(t, params, types.QueryTokenTypes, &tokenType) - require.Equal(t, tokenType.GetContractID(), contractID) - require.Equal(t, tokenType.GetTokenType(), tokenNFTType) - require.Equal(t, tokenType.GetName(), tokenNFTTypeName) -} - -func TestNewQuerier_queryTokenTypes_all(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: "", - } - var tokenTypes types.TokenTypes - query(t, params, types.QueryTokenTypes, &tokenTypes) - require.Equal(t, len(tokenTypes), 1) - require.Equal(t, tokenTypes[0].GetContractID(), contractID) - require.Equal(t, tokenTypes[0].GetTokenType(), tokenNFTType) - require.Equal(t, tokenTypes[0].GetName(), tokenNFTTypeName) -} - -func TestNewQuerier_queryTokensWithTokenType(t *testing.T) { - prepare(t) - - params := types.QueryTokenTypeParams{ - TokenType: tokenNFTType, - } - var tokens types.Tokens - query(t, params, types.QueryTokensWithTokenType, &tokens) - require.Equal(t, len(tokens), 3) - require.Equal(t, tokens[0].GetContractID(), contractID) - require.Equal(t, tokens[0].GetName(), tokenNFTName1) - require.Equal(t, tokens[0].GetTokenType(), tokenNFTType) - require.Equal(t, tokens[1].GetContractID(), contractID) - require.Equal(t, tokens[1].GetName(), tokenNFTName2) - require.Equal(t, tokens[1].GetTokenType(), tokenNFTType) - require.Equal(t, tokens[2].GetContractID(), contractID) - require.Equal(t, tokens[2].GetName(), tokenNFTName3) - require.Equal(t, tokens[2].GetTokenType(), tokenNFTType) - params2 := types.QueryTokenTypeParams{ - TokenType: tokenFTType, - } - var tokens2 types.Tokens - query(t, params2, types.QueryTokensWithTokenType, &tokens2) - require.Equal(t, len(tokens2), 1) - require.Equal(t, tokens2[0].GetContractID(), contractID) - require.Equal(t, tokens2[0].GetName(), tokenFTName) - require.Equal(t, tokens2[0].GetTokenType(), tokenFTType) - paramsNoExist := types.QueryTokenTypeParams{ - TokenType: "99999999", - } - var tokensNoExist types.Tokens - query(t, paramsNoExist, types.QueryTokensWithTokenType, &tokensNoExist) - require.Equal(t, len(tokensNoExist), 0) - require.Empty(t, tokensNoExist) -} - -func TestNewQuerier_queryCollections_one(t *testing.T) { - prepare(t) - - var collection types.Collection - query(t, nil, types.QueryCollections, &collection) - require.Equal(t, collection.GetContractID(), contractID) - require.Equal(t, collection.GetName(), collectionName) - require.Equal(t, collection.GetBaseImgURI(), imageURL) -} - -func TestNewQuerier_queryNFTCount(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTType, - } - var count sdk.Int - query(t, params, types.QueryNFTCount, &count) - require.Equal(t, count, sdk.NewInt(3)) -} - -func TestNewQuerier_queryTotalSupply_FT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenFTID, - } - var supply sdk.Int - query(t, params, types.QuerySupply, &supply) - require.Equal(t, supply.Int64(), int64(tokenFTSupply)) -} - -func TestNewQuerier_queryTotalMint_FT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenFTID, - } - var supply sdk.Int - query(t, params, types.QueryMint, &supply) - require.Equal(t, supply.Int64(), int64(tokenFTSupply)) -} - -func TestNewQuerier_queryTotalBurn_FT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenFTID, - } - var supply sdk.Int - query(t, params, types.QueryBurn, &supply) - require.Equal(t, supply.Int64(), int64(0)) -} - -func TestNewQuerier_queryTotalSupply_NFT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTType, - } - var supply sdk.Int - query(t, params, types.QueryNFTCount, &supply) - require.Equal(t, int64(3), supply.Int64()) -} - -func TestNewQuerier_queryTotalMint_NFT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTType, - } - var supply sdk.Int - query(t, params, types.QueryNFTMint, &supply) - require.Equal(t, int64(3), supply.Int64()) -} - -func TestNewQuerier_queryTotalBurn_NFT(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTType, - } - var supply sdk.Int - query(t, params, types.QueryNFTBurn, &supply) - require.Equal(t, supply.Int64(), int64(0)) -} - -func TestNewQuerier_queryParent(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID2, - } - var token types.Token - query(t, params, types.QueryParent, &token) - require.Equal(t, token.GetContractID(), contractID) - require.Equal(t, token.GetTokenID(), tokenNFTID1) -} - -func TestNewQuerier_queryParent_nil(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID1, - } - var token types.Token - query(t, params, types.QueryParent, &token) - require.Equal(t, token, nil) -} - -func TestNewQuerier_queryRoot(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID3, - } - var token types.Token - query(t, params, types.QueryRoot, &token) - require.Equal(t, token.GetContractID(), contractID) - require.Equal(t, token.GetTokenID(), tokenNFTID1) -} - -func TestNewQuerier_queryRoot_self(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID1, - } - var token types.Token - query(t, params, types.QueryRoot, &token) - require.Equal(t, token.GetContractID(), contractID) - require.Equal(t, token.GetTokenID(), tokenNFTID1) -} - -func TestNewQuerier_queryChildren(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID1, - } - var tokens types.Tokens - query(t, params, types.QueryChildren, &tokens) - require.Equal(t, len(tokens), 2) - require.Equal(t, tokens[0].GetContractID(), contractID) - require.Equal(t, tokens[0].GetTokenID(), tokenNFTID2) - require.Equal(t, tokens[1].GetContractID(), contractID) - require.Equal(t, tokens[1].GetTokenID(), tokenNFTID3) -} - -func TestNewQuerier_queryChildren_empty(t *testing.T) { - prepare(t) - - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID2, - } - var tokens types.Tokens - query(t, params, types.QueryChildren, &tokens) - require.Equal(t, len(tokens), 0) -} - -func TestNewQuerier_queryApprovers(t *testing.T) { - prepare(t) - params := types.QueryProxyParams{ - Proxy: addr1, - } - var acAd1 []sdk.AccAddress - query(t, params, types.QueryApprovers, &acAd1) - require.Equal(t, 2, len(acAd1)) - if bytes.Compare(addr2, addr3) <= 0 { - require.Equal(t, addr2, acAd1[0]) - require.Equal(t, addr3, acAd1[1]) - } else { - require.Equal(t, addr2, acAd1[1]) - require.Equal(t, addr3, acAd1[0]) - } - - var acAdEmpty []sdk.AccAddress - paramsEmpty := types.QueryProxyParams{ - Proxy: addr2, - } - query(t, paramsEmpty, types.QueryApprovers, &acAdEmpty) - require.Empty(t, acAdEmpty) -} - -func TestNewQuerier_queryIsApproved_true(t *testing.T) { - prepare(t) - params := types.QueryIsApprovedParams{ - Proxy: addr1, - Approver: addr2, - } - var approved bool - query(t, params, types.QueryIsApproved, &approved) - require.True(t, approved) -} - -func TestNewQuerier_queryIsApproved_false(t *testing.T) { - prepare(t) - - params := types.QueryIsApprovedParams{ - Proxy: addr2, - Approver: addr1, - } - var approved bool - query(t, params, types.QueryIsApproved, &approved) - require.False(t, approved) -} - -func TestNewQuerier_invalid(t *testing.T) { - prepare(t) - params := types.QueryTokenIDParams{ - TokenID: tokenNFTID1, - } - querier := NewQuerier(ckeeper) - path := []string{"noquery"} - req := abci.RequestQuery{ - Path: "", - Data: []byte(string(codec.MustMarshalJSONIndent(types.ModuleCdc, params))), - } - _, err := querier(ctx, path, req) - require.EqualError(t, err, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown collection query endpoint").Error()) -} diff --git a/x/collection/internal/types/account.go b/x/collection/internal/types/account.go deleted file mode 100644 index 1b4be05dd7..0000000000 --- a/x/collection/internal/types/account.go +++ /dev/null @@ -1,56 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Account interface { - GetAddress() sdk.AccAddress - GetContractID() string - GetCoins() Coins - SetCoins(Coins) Account - String() string -} - -type BaseAccount struct { - Address sdk.AccAddress `json:"address"` - ContractID string `json:"contract_id"` - Coins Coins `json:"tokens"` -} - -func NewBaseAccountWithAddress(contractID string, addr sdk.AccAddress) *BaseAccount { - return &BaseAccount{ - ContractID: contractID, - Address: addr, - Coins: NewCoins(), - } -} - -func (acc BaseAccount) String() string { - b, err := json.Marshal(acc) - if err != nil { - panic(err) - } - return string(b) -} - -func (acc BaseAccount) GetContractID() string { - return acc.ContractID -} - -func (acc BaseAccount) GetAddress() sdk.AccAddress { - return acc.Address -} - -func (acc BaseAccount) GetCoins() Coins { - return acc.Coins -} - -func (acc BaseAccount) SetCoins(coins Coins) Account { - acc.Coins = coins - return acc -} - -type Accounts []Account diff --git a/x/collection/internal/types/codec.go b/x/collection/internal/types/codec.go deleted file mode 100644 index 78e00a26a2..0000000000 --- a/x/collection/internal/types/codec.go +++ /dev/null @@ -1,59 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -var ModuleCdc *codec.Codec - -func init() { - ModuleCdc = codec.New() - RegisterCodec(ModuleCdc) - ModuleCdc.Seal() -} - -// RegisterCodec registers concrete types on the Amino codec -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgCreateCollection{}, "collection/MsgCreate", nil) - cdc.RegisterConcrete(MsgIssueFT{}, "collection/MsgIssueFT", nil) - cdc.RegisterConcrete(MsgIssueNFT{}, "collection/MsgIssueNFT", nil) - cdc.RegisterConcrete(MsgMintNFT{}, "collection/MsgMintNFT", nil) - cdc.RegisterConcrete(MsgBurnNFT{}, "collection/MsgBurnNFT", nil) - cdc.RegisterConcrete(MsgBurnNFTFrom{}, "collection/MsgBurnNFTFrom", nil) - cdc.RegisterConcrete(MsgModify{}, "collection/MsgModify", nil) - cdc.RegisterConcrete(MsgMintFT{}, "collection/MsgMintFT", nil) - cdc.RegisterConcrete(MsgBurnFT{}, "collection/MsgBurnFT", nil) - cdc.RegisterConcrete(MsgBurnFTFrom{}, "collection/MsgBurnFTFrom", nil) - cdc.RegisterConcrete(MsgGrantPermission{}, "collection/MsgGrantPermission", nil) - cdc.RegisterConcrete(MsgRevokePermission{}, "collection/MsgRevokePermission", nil) - cdc.RegisterConcrete(MsgTransferFT{}, "collection/MsgTransferFT", nil) - cdc.RegisterConcrete(MsgTransferNFT{}, "collection/MsgTransferNFT", nil) - cdc.RegisterConcrete(MsgTransferFTFrom{}, "collection/MsgTransferFTFrom", nil) - cdc.RegisterConcrete(MsgTransferNFTFrom{}, "collection/MsgTransferNFTFrom", nil) - cdc.RegisterConcrete(MsgAttach{}, "collection/MsgAttach", nil) - cdc.RegisterConcrete(MsgDetach{}, "collection/MsgDetach", nil) - cdc.RegisterConcrete(MsgAttachFrom{}, "collection/MsgAttachFrom", nil) - cdc.RegisterConcrete(MsgDetachFrom{}, "collection/MsgDetachFrom", nil) - cdc.RegisterConcrete(MsgApprove{}, "collection/MsgApprove", nil) - cdc.RegisterConcrete(MsgDisapprove{}, "collection/MsgDisapprove", nil) - - cdc.RegisterInterface((*Token)(nil), nil) - cdc.RegisterInterface((*FT)(nil), nil) - - cdc.RegisterInterface((*Collection)(nil), nil) - cdc.RegisterConcrete(&BaseCollection{}, "collection/Collection", nil) - cdc.RegisterConcrete(&BaseFT{}, "collection/FT", nil) - cdc.RegisterConcrete(&BaseNFT{}, "collection/NFT", nil) - - cdc.RegisterInterface((*Account)(nil), nil) - cdc.RegisterConcrete(&BaseAccount{}, "collection/Account", nil) - - cdc.RegisterInterface((*Supply)(nil), nil) - cdc.RegisterConcrete(&BaseSupply{}, "collection/Supply", nil) - - cdc.RegisterInterface((*TokenType)(nil), nil) - cdc.RegisterConcrete(&BaseTokenType{}, "collection/TokenType", nil) - - cdc.RegisterInterface((*AccountPermissionI)(nil), nil) - cdc.RegisterConcrete(&AccountPermission{}, "collection/AccountPermission", nil) -} diff --git a/x/collection/internal/types/coin.go b/x/collection/internal/types/coin.go deleted file mode 100644 index e5798c2d15..0000000000 --- a/x/collection/internal/types/coin.go +++ /dev/null @@ -1,698 +0,0 @@ -// copied from https://github.com/cosmos/cosmos-sdk/blob/v0.38.1/types/coin.go -package types - -import ( - "encoding/json" - "fmt" - "regexp" - "sort" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - OneCoin = func(denom string) Coin { return NewCoin(denom, sdk.NewInt(1)) } - OneCoins = func(denom string) Coins { return NewCoins(OneCoin(denom)) } -) - -// ----------------------------------------------------------------------------- -// Coin - -// Coin hold some amount of one currency. -// -// CONTRACT: A coin will never hold a negative amount of any denomination. -// -type Coin struct { - Denom string `json:"token_id"` - - // To allow the use of unsigned integers (see: #1273) a larger refactor will - // need to be made. So we use signed integers for now with safety measures in - // place preventing negative values being used. - Amount sdk.Int `json:"amount"` -} - -// NewCoin returns a new coin with a denomination and amount. It will panic if -// the amount is negative. -func NewCoin(denom string, amount sdk.Int) Coin { - if err := validate(denom, amount); err != nil { - panic(err) - } - - return Coin{ - Denom: denom, - Amount: amount, - } -} - -// NewInt64Coin returns a new coin with a denomination and amount. It will panic -// if the amount is negative. -func NewInt64Coin(denom string, amount int64) Coin { - return NewCoin(denom, sdk.NewInt(amount)) -} - -// String provides a human-readable representation of a coin -func (coin Coin) String() string { - return fmt.Sprintf("%v:%v", coin.Amount, coin.Denom) -} - -// validate returns an error if the Coin has a negative amount or if -// the denom is invalid. -func validate(denom string, amount sdk.Int) error { - if err := ValidateDenom(denom); err != nil { - return err - } - - if amount.IsNegative() { - return fmt.Errorf("negative coin amount: %v", amount) - } - - return nil -} - -// IsValid returns true if the Coin has a non-negative amount and the denom is vaild. -func (coin Coin) IsValid() bool { - if err := validate(coin.Denom, coin.Amount); err != nil { - return false - } - return true -} - -// IsZero returns if this represents no money -func (coin Coin) IsZero() bool { - return coin.Amount.IsZero() -} - -// IsGTE returns true if they are the same type and the receiver is -// an equal or greater value -func (coin Coin) IsGTE(other Coin) bool { - if coin.Denom != other.Denom { - panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom)) - } - - return !coin.Amount.LT(other.Amount) -} - -// IsLT returns true if they are the same type and the receiver is -// a smaller value -func (coin Coin) IsLT(other Coin) bool { - if coin.Denom != other.Denom { - panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom)) - } - - return coin.Amount.LT(other.Amount) -} - -// IsEqual returns true if the two sets of Coins have the same value -func (coin Coin) IsEqual(other Coin) bool { - if coin.Denom != other.Denom { - panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom)) - } - - return coin.Amount.Equal(other.Amount) -} - -// Adds amounts of two coins with same denom. If the coins differ in denom then -// it panics. -func (coin Coin) Add(coinB Coin) Coin { - if coin.Denom != coinB.Denom { - panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, coinB.Denom)) - } - - return Coin{coin.Denom, coin.Amount.Add(coinB.Amount)} -} - -// Subtracts amounts of two coins with same denom. If the coins differ in denom -// then it panics. -func (coin Coin) Sub(coinB Coin) Coin { - if coin.Denom != coinB.Denom { - panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, coinB.Denom)) - } - - res := Coin{coin.Denom, coin.Amount.Sub(coinB.Amount)} - if res.IsNegative() { - panic("negative coin amount") - } - - return res -} - -// IsPositive returns true if coin amount is positive. -// -func (coin Coin) IsPositive() bool { - return coin.Amount.Sign() == 1 -} - -// IsNegative returns true if the coin amount is negative and false otherwise. -// -func (coin Coin) IsNegative() bool { - return coin.Amount.Sign() == -1 -} - -// ----------------------------------------------------------------------------- -// Coins - -// Coins is a set of Coin, one per currency -type Coins []Coin - -// NewCoins constructs a new coin set. -func NewCoins(coins ...Coin) Coins { - // remove zeroes - newCoins := removeZeroCoins(Coins(coins)) - if len(newCoins) == 0 { - return Coins{} - } - - newCoins.Sort() - - // detect duplicate Denoms - if dupIndex := findDup(newCoins); dupIndex != -1 { - panic(fmt.Errorf("find duplicate denom: %s", newCoins[dupIndex])) - } - - if !newCoins.IsValid() { - panic(fmt.Errorf("invalid coin set: %s", newCoins)) - } - - return newCoins -} - -type coinsJSON Coins - -// MarshalJSON implements a custom JSON marshaller for the Coins type to allow -// nil Coins to be encoded as an empty array. -func (coins Coins) MarshalJSON() ([]byte, error) { - if coins == nil { - return json.Marshal(coinsJSON(Coins{})) - } - - return json.Marshal(coinsJSON(coins)) -} - -func (coins Coins) String() string { - if len(coins) == 0 { - return "" - } - - out := "" - for _, coin := range coins { - out += fmt.Sprintf("%v,", coin.String()) - } - return out[:len(out)-1] -} - -// IsValid asserts the Coins are sorted, have positive amount, -// and Denom does not contain upper case characters. -func (coins Coins) IsValid() bool { - switch len(coins) { - case 0: - return true - case 1: - if err := ValidateDenom(coins[0].Denom); err != nil { - return false - } - return coins[0].IsPositive() - default: - // check single coin case - if !(Coins{coins[0]}).IsValid() { - return false - } - - lowDenom := coins[0].Denom - for _, coin := range coins[1:] { - if strings.ToLower(coin.Denom) != coin.Denom { - return false - } - if coin.Denom <= lowDenom { - return false - } - if !coin.IsPositive() { - return false - } - - // we compare each coin against the last denom - lowDenom = coin.Denom - } - - return true - } -} - -// Add adds two sets of coins. -// -// e.g. -// {2A} + {A, 2B} = {3A, 2B} -// {2A} + {0B} = {2A} -// -// NOTE: Add operates under the invariant that coins are sorted by -// denominations. -// -// CONTRACT: Add will never return Coins where one Coin has a non-positive -// amount. In otherwords, IsValid will always return true. -func (coins Coins) Add(coinsB ...Coin) Coins { - return coins.safeAdd(coinsB) -} - -// safeAdd will perform addition of two coins sets. If both coin sets are -// empty, then an empty set is returned. If only a single set is empty, the -// other set is returned. Otherwise, the coins are compared in order of their -// denomination and addition only occurs when the denominations match, otherwise -// the coin is simply added to the sum assuming it's not zero. -func (coins Coins) safeAdd(coinsB Coins) Coins { - sum := ([]Coin)(nil) - indexA, indexB := 0, 0 - lenA, lenB := len(coins), len(coinsB) - - for { - if indexA == lenA { - if indexB == lenB { - // return nil coins if both sets are empty - return sum - } - - // return set B (excluding zero coins) if set A is empty - return append(sum, removeZeroCoins(coinsB[indexB:])...) - } else if indexB == lenB { - // return set A (excluding zero coins) if set B is empty - return append(sum, removeZeroCoins(coins[indexA:])...) - } - - coinA, coinB := coins[indexA], coinsB[indexB] - - switch strings.Compare(coinA.Denom, coinB.Denom) { - case -1: // coin A denom < coin B denom - if !coinA.IsZero() { - sum = append(sum, coinA) - } - - indexA++ - - case 0: // coin A denom == coin B denom - res := coinA.Add(coinB) - if !res.IsZero() { - sum = append(sum, res) - } - - indexA++ - indexB++ - - case 1: // coin A denom > coin B denom - if !coinB.IsZero() { - sum = append(sum, coinB) - } - - indexB++ - } - } -} - -// DenomsSubsetOf returns true if receiver's denom set -// is subset of coinsB's denoms. -func (coins Coins) DenomsSubsetOf(coinsB Coins) bool { - // more denoms in B than in receiver - if len(coins) > len(coinsB) { - return false - } - - for _, coin := range coins { - if coinsB.AmountOf(coin.Denom).IsZero() { - return false - } - } - - return true -} - -// Sub subtracts a set of coins from another. -// -// e.g. -// {2A, 3B} - {A} = {A, 3B} -// {2A} - {0B} = {2A} -// {A, B} - {A} = {B} -// -// CONTRACT: Sub will never return Coins where one Coin has a non-positive -// amount. In otherwords, IsValid will always return true. -func (coins Coins) Sub(coinsB Coins) Coins { - diff, hasNeg := coins.SafeSub(coinsB) - if hasNeg { - panic("negative coin amount") - } - - return diff -} - -// SafeSub performs the same arithmetic as Sub but returns a boolean if any -// negative coin amount was returned. -func (coins Coins) SafeSub(coinsB Coins) (Coins, bool) { - diff := coins.safeAdd(coinsB.negative()) - return diff, diff.IsAnyNegative() -} - -// IsAllGT returns true if for every denom in coinsB, -// the denom is present at a greater amount in coins. -func (coins Coins) IsAllGT(coinsB Coins) bool { - if len(coins) == 0 { - return false - } - - if len(coinsB) == 0 { - return true - } - - if !coinsB.DenomsSubsetOf(coins) { - return false - } - - for _, coinB := range coinsB { - amountA, amountB := coins.AmountOf(coinB.Denom), coinB.Amount - if !amountA.GT(amountB) { - return false - } - } - - return true -} - -// IsAllGTE returns false if for any denom in coinsB, -// the denom is present at a smaller amount in coins; -// else returns true. -func (coins Coins) IsAllGTE(coinsB Coins) bool { - if len(coinsB) == 0 { - return true - } - - if len(coins) == 0 { - return false - } - - for _, coinB := range coinsB { - if coinB.Amount.GT(coins.AmountOf(coinB.Denom)) { - return false - } - } - - return true -} - -// IsAllLT returns True iff for every denom in coins, the denom is present at -// a smaller amount in coinsB. -func (coins Coins) IsAllLT(coinsB Coins) bool { - return coinsB.IsAllGT(coins) -} - -// IsAllLTE returns true iff for every denom in coins, the denom is present at -// a smaller or equal amount in coinsB. -func (coins Coins) IsAllLTE(coinsB Coins) bool { - return coinsB.IsAllGTE(coins) -} - -// IsAnyGT returns true iff for any denom in coins, the denom is present at a -// greater amount in coinsB. -// -// e.g. -// {2A, 3B}.IsAnyGT{A} = true -// {2A, 3B}.IsAnyGT{5C} = false -// {}.IsAnyGT{5C} = false -// {2A, 3B}.IsAnyGT{} = false -func (coins Coins) IsAnyGT(coinsB Coins) bool { - if len(coinsB) == 0 { - return false - } - - for _, coin := range coins { - amt := coinsB.AmountOf(coin.Denom) - if coin.Amount.GT(amt) && !amt.IsZero() { - return true - } - } - - return false -} - -// IsAnyGTE returns true iff coins contains at least one denom that is present -// at a greater or equal amount in coinsB; it returns false otherwise. -// -// NOTE: IsAnyGTE operates under the invariant that both coin sets are sorted -// by denominations and there exists no zero coins. -func (coins Coins) IsAnyGTE(coinsB Coins) bool { - if len(coinsB) == 0 { - return false - } - - for _, coin := range coins { - amt := coinsB.AmountOf(coin.Denom) - if coin.Amount.GTE(amt) && !amt.IsZero() { - return true - } - } - - return false -} - -// IsZero returns true if there are no coins or all coins are zero. -func (coins Coins) IsZero() bool { - for _, coin := range coins { - if !coin.IsZero() { - return false - } - } - return true -} - -// IsEqual returns true if the two sets of Coins have the same value -func (coins Coins) IsEqual(coinsB Coins) bool { - if len(coins) != len(coinsB) { - return false - } - - coins = coins.Sort() - coinsB = coinsB.Sort() - - for i := 0; i < len(coins); i++ { - if !coins[i].IsEqual(coinsB[i]) { - return false - } - } - - return true -} - -// Empty returns true if there are no coins and false otherwise. -func (coins Coins) Empty() bool { - return len(coins) == 0 -} - -// Returns the amount of a denom from coins -func (coins Coins) AmountOf(denom string) sdk.Int { - mustValidateDenom(denom) - - switch len(coins) { - case 0: - return sdk.ZeroInt() - - case 1: - coin := coins[0] - if coin.Denom == denom { - return coin.Amount - } - return sdk.ZeroInt() - - default: - midIdx := len(coins) / 2 // 2:1, 3:1, 4:2 - coin := coins[midIdx] - switch { - case denom < coin.Denom: - return coins[:midIdx].AmountOf(denom) - case denom == coin.Denom: - return coin.Amount - default: - return coins[midIdx+1:].AmountOf(denom) - } - } -} - -// GetDenomByIndex returns the Denom of the certain coin to make the findDup generic -func (coins Coins) GetDenomByIndex(i int) string { - return coins[i].Denom -} - -// IsAllPositive returns true if there is at least one coin and all currencies -// have a positive value. -func (coins Coins) IsAllPositive() bool { - if len(coins) == 0 { - return false - } - - for _, coin := range coins { - if !coin.IsPositive() { - return false - } - } - - return true -} - -// IsAnyNegative returns true if there is at least one coin whose amount -// is negative; returns false otherwise. It returns false if the coin set -// is empty too. -// -func (coins Coins) IsAnyNegative() bool { - for _, coin := range coins { - if coin.IsNegative() { - return true - } - } - - return false -} - -// negative returns a set of coins with all amount negative. -// -func (coins Coins) negative() Coins { - res := make([]Coin, 0, len(coins)) - - for _, coin := range coins { - res = append(res, Coin{ - Denom: coin.Denom, - Amount: coin.Amount.Neg(), - }) - } - - return res -} - -// removeZeroCoins removes all zero coins from the given coin set in-place. -func removeZeroCoins(coins Coins) Coins { - i, l := 0, len(coins) - for i < l { - if coins[i].IsZero() { - // remove coin - coins = append(coins[:i], coins[i+1:]...) - l-- - } else { - i++ - } - } - - return coins[:i] -} - -// ----------------------------------------------------------------------------- -// Sort interface - -// nolint -func (coins Coins) Len() int { return len(coins) } -func (coins Coins) Less(i, j int) bool { return coins[i].Denom < coins[j].Denom } -func (coins Coins) Swap(i, j int) { coins[i], coins[j] = coins[j], coins[i] } - -var _ sort.Interface = Coins{} - -// Sort is a helper function to sort the set of coins inplace -func (coins Coins) Sort() Coins { - sort.Sort(coins) - return coins -} - -// ----------------------------------------------------------------------------- -// Parsing - -var ( - // Denominations can be 3 ~ 16 characters long. - reDnmString = `[a-f0-9]{16}` - reDnm = regexp.MustCompile(fmt.Sprintf(`^%s$`, reDnmString)) - reAmt = `[[:digit:]]+` - reSpc = `:` - reCoin = regexp.MustCompile(fmt.Sprintf(`^(%s)%s(%s)$`, reAmt, reSpc, reDnmString)) -) - -// ParseCoins will parse out a list of coins separated by commas. -// If nothing is provided, it returns nil Coins. -// Returned coins are sorted. -func ParseCoins(coinsStr string) (Coins, error) { - coinsStr = strings.TrimSpace(coinsStr) - if len(coinsStr) == 0 { - return nil, nil - } - - coinStrs := strings.Split(coinsStr, ",") - coins := make(Coins, len(coinStrs)) - for i, coinStr := range coinStrs { - coin, err := ParseCoin(coinStr) - if err != nil { - return nil, err - } - - coins[i] = coin - } - - // sort coins for determinism - coins.Sort() - - // validate coins before returning - if !coins.IsValid() { - return nil, fmt.Errorf("parseCoins invalid: %#v", coins) - } - - return coins, nil -} - -// ParseCoin parses a cli input for one coin type, returning errors if invalid. -// This returns an error on an empty string as well. -func ParseCoin(coinStr string) (coin Coin, err error) { - coinStr = strings.TrimSpace(coinStr) - - matches := reCoin.FindStringSubmatch(coinStr) - if matches == nil { - return Coin{}, fmt.Errorf("invalid coin expression: %s", coinStr) - } - - denomStr, amountStr := matches[2], matches[1] - - amount, ok := sdk.NewIntFromString(amountStr) - if !ok { - return Coin{}, fmt.Errorf("failed to parse coin amount: %s", amountStr) - } - - if err := ValidateDenom(denomStr); err != nil { - return Coin{}, fmt.Errorf("invalid denom cannot contain upper case characters or spaces: %s", err) - } - - return NewCoin(denomStr, amount), nil -} - -// ValidateDenom validates a denomination string returning an error if it is -// invalid. -func ValidateDenom(denom string) error { - if !reDnm.MatchString(denom) { - return fmt.Errorf("invalid denom: %s", denom) - } - return nil -} - -func mustValidateDenom(denom string) { - if err := ValidateDenom(denom); err != nil { - panic(err) - } -} - -type findDupDescriptor interface { - GetDenomByIndex(int) string - Len() int -} - -// findDup works on the assumption that coins is sorted -func findDup(coins findDupDescriptor) int { - if coins.Len() <= 1 { - return -1 - } - - prevDenom := coins.GetDenomByIndex(0) - for i := 1; i < coins.Len(); i++ { - if coins.GetDenomByIndex(i) == prevDenom { - return i - } - prevDenom = coins.GetDenomByIndex(i) - } - - return -1 -} diff --git a/x/collection/internal/types/coin_test.go b/x/collection/internal/types/coin_test.go deleted file mode 100644 index 48f79cd9b1..0000000000 --- a/x/collection/internal/types/coin_test.go +++ /dev/null @@ -1,712 +0,0 @@ -// copied from https://github.com/cosmos/cosmos-sdk/blob/v0.38.1/types/coin_test.go -package types - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - testDenom1 = "0000000100000000" - testDenom2 = "0000000200000000" - testDenom3 = "0000000300000000" - testDenom4 = "0000000400000000" - testDenomA = "0000000a00000000" -) - -// ---------------------------------------------------------------------------- -// Coin tests - -func TestCoin(t *testing.T) { - require.Panics(t, func() { NewInt64Coin(testDenom1, -1) }) - require.Panics(t, func() { NewCoin(testDenom1, sdk.NewInt(-1)) }) - require.Panics(t, func() { NewInt64Coin(strings.ToUpper(testDenomA), 10) }) - require.Panics(t, func() { NewCoin(strings.ToUpper(testDenomA), sdk.NewInt(10)) }) - require.Equal(t, sdk.NewInt(5), NewInt64Coin(testDenom1, 5).Amount) - require.Equal(t, sdk.NewInt(5), NewCoin(testDenom1, sdk.NewInt(5)).Amount) - require.Equal(t, OneCoins(testDenom1)[0].Amount.Int64(), int64(1)) -} - -func TestIsEqualCoin(t *testing.T) { - cases := []struct { - inputOne Coin - inputTwo Coin - expected bool - panics bool - }{ - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 1), true, false}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom2, 1), false, true}, - {NewInt64Coin(testDenom3, 1), NewInt64Coin(testDenom3, 10), false, false}, - } - - for tcIndex, tc := range cases { - tc := tc - if tc.panics { - require.Panics(t, func() { tc.inputOne.IsEqual(tc.inputTwo) }) - } else { - res := tc.inputOne.IsEqual(tc.inputTwo) - require.Equal(t, tc.expected, res, "coin equality relation is incorrect, tc #%d", tcIndex) - } - } -} - -func TestCoinIsValid(t *testing.T) { - cases := []struct { - coin Coin - expectPass bool - }{ - {Coin{testDenom1, sdk.NewInt(-1)}, false}, - {Coin{testDenom1, sdk.NewInt(0)}, true}, - {Coin{testDenom1, sdk.NewInt(1)}, true}, - {Coin{"a", sdk.NewInt(1)}, false}, - {Coin{"a very long coin denom", sdk.NewInt(1)}, false}, - {Coin{"atOm", sdk.NewInt(1)}, false}, - {Coin{" ", sdk.NewInt(1)}, false}, - } - - for i, tc := range cases { - require.Equal(t, tc.expectPass, tc.coin.IsValid(), "unexpected result for IsValid, tc #%d", i) - } -} - -func TestAddCoin(t *testing.T) { - cases := []struct { - inputOne Coin - inputTwo Coin - expected Coin - shouldPanic bool - }{ - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 2), false}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom1, 1), false}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom2, 1), NewInt64Coin(testDenom1, 1), true}, - } - - for tcIndex, tc := range cases { - tc := tc - if tc.shouldPanic { - require.Panics(t, func() { tc.inputOne.Add(tc.inputTwo) }) - } else { - res := tc.inputOne.Add(tc.inputTwo) - require.Equal(t, tc.expected, res, "sum of coins is incorrect, tc #%d", tcIndex) - } - } -} - -func TestSubCoin(t *testing.T) { - cases := []struct { - inputOne Coin - inputTwo Coin - expected Coin - shouldPanic bool - }{ - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom2, 1), NewInt64Coin(testDenom1, 1), true}, - {NewInt64Coin(testDenom1, 10), NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 9), false}, - {NewInt64Coin(testDenom1, 5), NewInt64Coin(testDenom1, 3), NewInt64Coin(testDenom1, 2), false}, - {NewInt64Coin(testDenom1, 5), NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom1, 5), false}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 5), Coin{}, true}, - } - - for tcIndex, tc := range cases { - tc := tc - if tc.shouldPanic { - require.Panics(t, func() { tc.inputOne.Sub(tc.inputTwo) }) - } else { - res := tc.inputOne.Sub(tc.inputTwo) - require.Equal(t, tc.expected, res, "difference of coins is incorrect, tc #%d", tcIndex) - } - } - - tc := struct { - inputOne Coin - inputTwo Coin - expected int64 - }{NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 1), 0} - res := tc.inputOne.Sub(tc.inputTwo) - require.Equal(t, tc.expected, res.Amount.Int64()) -} - -func TestIsGTECoin(t *testing.T) { - cases := []struct { - inputOne Coin - inputTwo Coin - expected bool - panics bool - }{ - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 1), true, false}, - {NewInt64Coin(testDenom1, 2), NewInt64Coin(testDenom1, 1), true, false}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom2, 1), false, true}, - } - - for tcIndex, tc := range cases { - tc := tc - if tc.panics { - require.Panics(t, func() { tc.inputOne.IsGTE(tc.inputTwo) }) - } else { - res := tc.inputOne.IsGTE(tc.inputTwo) - require.Equal(t, tc.expected, res, "coin GTE relation is incorrect, tc #%d", tcIndex) - } - } -} - -func TestIsLTCoin(t *testing.T) { - cases := []struct { - inputOne Coin - inputTwo Coin - expected bool - panics bool - }{ - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 1), false, false}, - {NewInt64Coin(testDenom1, 2), NewInt64Coin(testDenom1, 1), false, false}, - {NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 1), false, true}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom2, 1), false, true}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 1), false, false}, - {NewInt64Coin(testDenom1, 1), NewInt64Coin(testDenom1, 2), true, false}, - } - - for tcIndex, tc := range cases { - tc := tc - if tc.panics { - require.Panics(t, func() { tc.inputOne.IsLT(tc.inputTwo) }) - } else { - res := tc.inputOne.IsLT(tc.inputTwo) - require.Equal(t, tc.expected, res, "coin LT relation is incorrect, tc #%d", tcIndex) - } - } -} - -func TestCoinIsZero(t *testing.T) { - coin := NewInt64Coin(testDenom1, 0) - res := coin.IsZero() - require.True(t, res) - - coin = NewInt64Coin(testDenom1, 1) - res = coin.IsZero() - require.False(t, res) -} - -// ---------------------------------------------------------------------------- -// Coins tests - -func TestIsZeroCoins(t *testing.T) { - cases := []struct { - inputOne Coins - expected bool - }{ - {Coins{}, true}, - {Coins{NewInt64Coin(testDenom1, 0)}, true}, - {Coins{NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 0)}, true}, - {Coins{NewInt64Coin(testDenom1, 1)}, false}, - {Coins{NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 1)}, false}, - } - - for _, tc := range cases { - res := tc.inputOne.IsZero() - require.Equal(t, tc.expected, res) - } -} - -func TestEqualCoins(t *testing.T) { - cases := []struct { - inputOne Coins - inputTwo Coins - expected bool - panics bool - }{ - {Coins{}, Coins{}, true, false}, - {Coins{NewInt64Coin(testDenom1, 0)}, Coins{NewInt64Coin(testDenom1, 0)}, true, false}, - {Coins{NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 1)}, Coins{NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 1)}, true, false}, - {Coins{NewInt64Coin(testDenom1, 0)}, Coins{NewInt64Coin(testDenom2, 0)}, false, true}, - {Coins{NewInt64Coin(testDenom1, 0)}, Coins{NewInt64Coin(testDenom1, 1)}, false, false}, - {Coins{NewInt64Coin(testDenom1, 0)}, Coins{NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 1)}, false, false}, - {Coins{NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 1)}, Coins{NewInt64Coin(testDenom1, 0), NewInt64Coin(testDenom2, 1)}, true, false}, - } - - for tcnum, tc := range cases { - tc := tc - if tc.panics { - require.Panics(t, func() { tc.inputOne.IsEqual(tc.inputTwo) }) - } else { - res := tc.inputOne.IsEqual(tc.inputTwo) - require.Equal(t, tc.expected, res, "Equality is differed from exported. tc #%d, expected %b, actual %b.", tcnum, tc.expected, res) - } - } -} - -func TestAddCoins(t *testing.T) { - zero := sdk.NewInt(0) - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - cases := []struct { - inputOne Coins - inputTwo Coins - expected Coins - }{ - {Coins{{testDenom1, one}, {testDenom2, one}}, Coins{{testDenom1, one}, {testDenom2, one}}, Coins{{testDenom1, two}, {testDenom2, two}}}, - {Coins{{testDenom1, zero}, {testDenom2, one}}, Coins{{testDenom1, zero}, {testDenom2, zero}}, Coins{{testDenom2, one}}}, - {Coins{{testDenom1, two}}, Coins{{testDenom2, zero}}, Coins{{testDenom1, two}}}, - {Coins{{testDenom1, one}}, Coins{{testDenom1, one}, {testDenom2, two}}, Coins{{testDenom1, two}, {testDenom2, two}}}, - {Coins{{testDenom1, zero}, {testDenom2, zero}}, Coins{{testDenom1, zero}, {testDenom2, zero}}, Coins(nil)}, - } - - for tcIndex, tc := range cases { - res := tc.inputOne.Add(tc.inputTwo...) - assert.True(t, res.IsValid()) - require.Equal(t, tc.expected, res, "sum of coins is incorrect, tc #%d", tcIndex) - } -} - -func TestSubCoins(t *testing.T) { - zero := sdk.NewInt(0) - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - testCases := []struct { - inputOne Coins - inputTwo Coins - expected Coins - shouldPanic bool - }{ - {Coins{{testDenom1, two}}, Coins{{testDenom1, one}, {testDenom2, two}}, Coins{{testDenom1, one}, {testDenom2, two}}, true}, - {Coins{{testDenom1, two}}, Coins{{testDenom2, zero}}, Coins{{testDenom1, two}}, false}, - {Coins{{testDenom1, one}}, Coins{{testDenom2, zero}}, Coins{{testDenom1, one}}, false}, - {Coins{{testDenom1, one}, {testDenom2, one}}, Coins{{testDenom1, one}}, Coins{{testDenom2, one}}, false}, - {Coins{{testDenom1, one}, {testDenom2, one}}, Coins{{testDenom1, two}}, Coins{}, true}, - } - - for i, tc := range testCases { - tc := tc - if tc.shouldPanic { - require.Panics(t, func() { tc.inputOne.Sub(tc.inputTwo) }) - } else { - res := tc.inputOne.Sub(tc.inputTwo) - assert.True(t, res.IsValid()) - require.Equal(t, tc.expected, res, "sum of coins is incorrect, tc #%d", i) - } - } -} - -func TestCoins(t *testing.T) { - good := Coins{ - {testDenom1, sdk.NewInt(1)}, - {testDenom2, sdk.NewInt(1)}, - {testDenom3, sdk.NewInt(1)}, - } - mixedCase1 := Coins{ - {"000A0000", sdk.NewInt(1)}, - {"A0000000", sdk.NewInt(1)}, - {"ABCD0000", sdk.NewInt(1)}, - } - mixedCase2 := Coins{ - {"000A0000", sdk.NewInt(1)}, - {testDenom3, sdk.NewInt(1)}, - } - mixedCase3 := Coins{ - {"000A0000", sdk.NewInt(1)}, - } - empty := NewCoins() - badSort1 := Coins{ - {testDenom3, sdk.NewInt(1)}, - {testDenom1, sdk.NewInt(1)}, - {testDenom2, sdk.NewInt(1)}, - } - - // both are after the first one, but the second and third are in the wrong order - badSort2 := Coins{ - {testDenom1, sdk.NewInt(1)}, - {testDenom3, sdk.NewInt(1)}, - {testDenom2, sdk.NewInt(1)}, - } - badAmt := Coins{ - {testDenom1, sdk.NewInt(1)}, - {testDenom3, sdk.NewInt(0)}, - {testDenom2, sdk.NewInt(1)}, - } - dup := Coins{ - {testDenom1, sdk.NewInt(1)}, - {testDenom1, sdk.NewInt(1)}, - {testDenom2, sdk.NewInt(1)}, - } - neg := Coins{ - {testDenom1, sdk.NewInt(-1)}, - {testDenom2, sdk.NewInt(1)}, - } - - assert.True(t, good.IsValid(), "Coins are valid") - assert.False(t, mixedCase1.IsValid(), "Coins denoms contain upper case characters") - assert.False(t, mixedCase2.IsValid(), "First Coins denoms contain upper case characters") - assert.False(t, mixedCase3.IsValid(), "Single denom in Coins contains upper case characters") - assert.True(t, good.IsAllPositive(), "Expected coins to be positive: %v", good) - assert.False(t, empty.IsAllPositive(), "Expected coins to not be positive: %v", empty) - assert.True(t, good.IsAllGTE(empty), "Expected %v to be >= %v", good, empty) - assert.False(t, good.IsAllLT(empty), "Expected %v to be < %v", good, empty) - assert.True(t, empty.IsAllLT(good), "Expected %v to be < %v", empty, good) - assert.False(t, badSort1.IsValid(), "Coins are not sorted") - assert.False(t, badSort2.IsValid(), "Coins are not sorted") - assert.False(t, badAmt.IsValid(), "Coins cannot include 0 amounts") - assert.False(t, dup.IsValid(), "Duplicate coin") - assert.False(t, neg.IsValid(), "Negative first-denom coin") -} - -func TestCoinsGT(t *testing.T) { - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - assert.False(t, Coins{}.IsAllGT(Coins{})) - assert.True(t, Coins{{testDenom1, one}}.IsAllGT(Coins{})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGT(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGT(Coins{{testDenom2, one}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, two}}.IsAllGT(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllGT(Coins{{testDenom2, two}})) -} - -// nolint:dupl -func TestCoinsLT(t *testing.T) { - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - assert.False(t, Coins{}.IsAllLT(Coins{})) - assert.False(t, Coins{{testDenom1, one}}.IsAllLT(Coins{})) - assert.False(t, Coins{{testDenom1, one}}.IsAllLT(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllLT(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLT(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLT(Coins{{testDenom2, two}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLT(Coins{{testDenom1, one}, {testDenom2, one}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLT(Coins{{testDenom1, two}, {testDenom2, two}})) - assert.True(t, Coins{}.IsAllLT(Coins{{testDenom1, one}})) -} - -// nolint:dupl -func TestCoinsLTE(t *testing.T) { - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - assert.True(t, Coins{}.IsAllLTE(Coins{})) - assert.False(t, Coins{{testDenom1, one}}.IsAllLTE(Coins{})) - assert.True(t, Coins{{testDenom1, one}}.IsAllLTE(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllLTE(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLTE(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLTE(Coins{{testDenom2, two}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLTE(Coins{{testDenom1, one}, {testDenom2, one}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllLTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.True(t, Coins{}.IsAllLTE(Coins{{testDenom1, one}})) -} - -func TestSortCoins(t *testing.T) { - good := Coins{ - NewInt64Coin(testDenom1, 1), - NewInt64Coin(testDenom2, 1), - NewInt64Coin(testDenom3, 1), - } - empty := Coins{ - NewInt64Coin(testDenom4, 0), - } - badSort1 := Coins{ - NewInt64Coin(testDenom3, 1), - NewInt64Coin(testDenom1, 1), - NewInt64Coin(testDenom2, 1), - } - badSort2 := Coins{ // both are after the first one, but the second and third are in the wrong order - NewInt64Coin(testDenom1, 1), - NewInt64Coin(testDenom3, 1), - NewInt64Coin(testDenom2, 1), - } - badAmt := Coins{ - NewInt64Coin(testDenom1, 1), - NewInt64Coin(testDenom3, 0), - NewInt64Coin(testDenom2, 1), - } - dup := Coins{ - NewInt64Coin(testDenom1, 1), - NewInt64Coin(testDenom1, 1), - NewInt64Coin(testDenom2, 1), - } - - cases := []struct { - coins Coins - before, after bool // valid before/after sort - }{ - {good, true, true}, - {empty, false, false}, - {badSort1, false, true}, - {badSort2, false, true}, - {badAmt, false, false}, - {dup, false, false}, - } - - for tcIndex, tc := range cases { - require.Equal(t, tc.before, tc.coins.IsValid(), "coin validity is incorrect before sorting, tc #%d", tcIndex) - tc.coins.Sort() - require.Equal(t, tc.after, tc.coins.IsValid(), "coin validity is incorrect after sorting, tc #%d", tcIndex) - } -} - -func TestAmountOf(t *testing.T) { - case0 := Coins{} - case1 := Coins{ - NewInt64Coin(testDenom4, 0), - } - case2 := Coins{ - NewInt64Coin(testDenom1, 1), - NewInt64Coin(testDenom2, 1), - NewInt64Coin(testDenom3, 1), - } - case3 := Coins{ - NewInt64Coin(testDenom2, 1), - NewInt64Coin(testDenom3, 1), - } - case4 := Coins{ - NewInt64Coin(testDenom1, 8), - } - - cases := []struct { - coins Coins - amountOf int64 - amountOfSpace int64 - amountOfGAS int64 - amountOfMINERAL int64 - amountOfTREE int64 - }{ - {case0, 0, 0, 0, 0, 0}, - {case1, 0, 0, 0, 0, 0}, - {case2, 0, 0, 1, 1, 1}, - {case3, 0, 0, 0, 1, 1}, - {case4, 0, 0, 8, 0, 0}, - } - - for _, tc := range cases { - assert.Equal(t, sdk.NewInt(tc.amountOfGAS), tc.coins.AmountOf(testDenom1)) - assert.Equal(t, sdk.NewInt(tc.amountOfMINERAL), tc.coins.AmountOf(testDenom2)) - assert.Equal(t, sdk.NewInt(tc.amountOfTREE), tc.coins.AmountOf(testDenom3)) - } - - assert.Panics(t, func() { cases[0].coins.AmountOf("Invalid") }) -} - -// nolint:dupl -func TestCoinsIsAnyGTE(t *testing.T) { - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - assert.False(t, Coins{}.IsAnyGTE(Coins{})) - assert.False(t, Coins{{testDenom1, one}}.IsAnyGTE(Coins{})) - assert.False(t, Coins{}.IsAnyGTE(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAnyGTE(Coins{{testDenom1, two}})) - assert.False(t, Coins{{testDenom1, one}}.IsAnyGTE(Coins{{testDenom2, one}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, two}}.IsAnyGTE(Coins{{testDenom1, two}, {testDenom2, one}})) - assert.True(t, Coins{{testDenom1, one}}.IsAnyGTE(Coins{{testDenom1, one}})) - assert.True(t, Coins{{testDenom1, two}}.IsAnyGTE(Coins{{testDenom1, one}})) - assert.True(t, Coins{{testDenom1, one}}.IsAnyGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.True(t, Coins{{testDenom2, two}}.IsAnyGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{testDenom2, one}}.IsAnyGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, two}}.IsAnyGTE(Coins{{testDenom1, one}, {testDenom2, one}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAnyGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.True(t, Coins{{"00000aaa00000000", one}, {"00000bbb00000000", one}}.IsAnyGTE(Coins{{testDenom2, one}, {"00000ccc00000000", one}, {"00000bbb00000000", one}, {"00000ddd00000000", one}})) -} - -// nolint:dupl -func TestCoinsIsAllGT(t *testing.T) { - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - assert.False(t, Coins{}.IsAllGT(Coins{})) - assert.True(t, Coins{{testDenom1, one}}.IsAllGT(Coins{})) - assert.False(t, Coins{}.IsAllGT(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGT(Coins{{testDenom1, two}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGT(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, two}}.IsAllGT(Coins{{testDenom1, two}, {testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGT(Coins{{testDenom1, one}})) - assert.True(t, Coins{{testDenom1, two}}.IsAllGT(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGT(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{testDenom2, two}}.IsAllGT(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{testDenom2, one}}.IsAllGT(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, two}}.IsAllGT(Coins{{testDenom1, one}, {testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllGT(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{"xxx", one}, {"yyy", one}}.IsAllGT(Coins{{testDenom2, one}, {"ccc", one}, {"yyy", one}, {"zzz", one}})) -} - -func TestCoinsIsAllGTE(t *testing.T) { - one := sdk.NewInt(1) - two := sdk.NewInt(2) - - assert.True(t, Coins{}.IsAllGTE(Coins{})) - assert.True(t, Coins{{testDenom1, one}}.IsAllGTE(Coins{})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllGTE(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllGTE(Coins{{testDenom2, two}})) - assert.False(t, Coins{}.IsAllGTE(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGTE(Coins{{testDenom1, two}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGTE(Coins{{testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, two}}.IsAllGTE(Coins{{testDenom1, two}, {testDenom2, one}})) - assert.True(t, Coins{{testDenom1, one}}.IsAllGTE(Coins{{testDenom1, one}})) - assert.True(t, Coins{{testDenom1, two}}.IsAllGTE(Coins{{testDenom1, one}})) - assert.False(t, Coins{{testDenom1, one}}.IsAllGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{testDenom2, two}}.IsAllGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{testDenom2, one}}.IsAllGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.True(t, Coins{{testDenom1, one}, {testDenom2, two}}.IsAllGTE(Coins{{testDenom1, one}, {testDenom2, one}})) - assert.False(t, Coins{{testDenom1, one}, {testDenom2, one}}.IsAllGTE(Coins{{testDenom1, one}, {testDenom2, two}})) - assert.False(t, Coins{{"xxx", one}, {"yyy", one}}.IsAllGTE(Coins{{testDenom2, one}, {"ccc", one}, {"yyy", one}, {"zzz", one}})) -} - -func TestNewCoins(t *testing.T) { - tenatom := NewInt64Coin(testDenom1, 10) - tenbtc := NewInt64Coin(testDenom2, 10) - zeroeth := NewInt64Coin(testDenom3, 0) - tests := []struct { - name string - coins Coins - want Coins - wantPanic bool - }{ - {"empty args", []Coin{}, Coins{}, false}, - {"one coin", []Coin{tenatom}, Coins{tenatom}, false}, - {"sort after create", []Coin{tenbtc, tenatom}, Coins{tenatom, tenbtc}, false}, - {"sort and remove zeroes", []Coin{zeroeth, tenbtc, tenatom}, Coins{tenatom, tenbtc}, false}, - {"panic on dups", []Coin{tenatom, tenatom}, Coins{}, true}, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - if tt.wantPanic { - require.Panics(t, func() { NewCoins(tt.coins...) }) - return - } - got := NewCoins(tt.coins...) - require.True(t, got.IsEqual(tt.want)) - }) - } -} - -func TestCoinsIsAnyGT(t *testing.T) { - twoAtom := NewInt64Coin(testDenom1, 2) - fiveAtom := NewInt64Coin(testDenom1, 5) - threeEth := NewInt64Coin(testDenom2, 3) - sixEth := NewInt64Coin(testDenom2, 6) - twoBtc := NewInt64Coin(testDenom3, 2) - - require.False(t, Coins{}.IsAnyGT(Coins{})) - - require.False(t, Coins{fiveAtom}.IsAnyGT(Coins{})) - require.False(t, Coins{}.IsAnyGT(Coins{fiveAtom})) - require.True(t, Coins{fiveAtom}.IsAnyGT(Coins{twoAtom})) - require.False(t, Coins{twoAtom}.IsAnyGT(Coins{fiveAtom})) - - require.True(t, Coins{twoAtom, sixEth}.IsAnyGT(Coins{twoBtc, fiveAtom, threeEth})) - require.False(t, Coins{twoBtc, twoAtom, threeEth}.IsAnyGT(Coins{fiveAtom, sixEth})) - require.False(t, Coins{twoAtom, sixEth}.IsAnyGT(Coins{twoBtc, fiveAtom})) -} - -func TestFindDup(t *testing.T) { - abc := NewInt64Coin(testDenom1, 10) - def := NewInt64Coin(testDenom2, 10) - ghi := NewInt64Coin(testDenom3, 10) - - type args struct { - coins Coins - } - tests := []struct { - name string - args args - want int - }{ - {"empty", args{NewCoins()}, -1}, - {"one coin", args{NewCoins(NewInt64Coin("00000abc00000000", 10))}, -1}, - {"no dups", args{Coins{abc, def, ghi}}, -1}, - {"dup at first position", args{Coins{abc, abc, def}}, 1}, - {"dup after first position", args{Coins{abc, def, def}}, 2}, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - if got := findDup(tt.args.coins); got != tt.want { - t.Errorf("findDup() = %v, want %v", got, tt.want) - } - }) - } -} - -func TestMarshalJSONCoins(t *testing.T) { - cdc := codec.New() - RegisterCodec(cdc) - - testCases := []struct { - name string - input Coins - strOutput string - }{ - {"nil coins", nil, `[]`}, - {"empty coins", Coins{}, `[]`}, - {"non-empty coins", NewCoins(NewInt64Coin("00000fee00000000", 50)), `[{"token_id":"00000fee00000000","amount":"50"}]`}, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - bz, err := cdc.MarshalJSON(tc.input) - require.NoError(t, err) - require.Equal(t, tc.strOutput, string(bz)) - - var newCoins Coins - require.NoError(t, cdc.UnmarshalJSON(bz, &newCoins)) - - if tc.input.Empty() { - require.Nil(t, newCoins) - } else { - require.Equal(t, tc.input, newCoins) - } - }) - } -} - -func TestParseCoin(t *testing.T) { - cases := []struct { - coinStr string - expectPass bool - }{ - {"1:0000000100000000", true}, - {"1000:0000000100000000", true}, - {"21302131270312:0000000100000000", true}, - {"1:000000010000000", false}, - {"10000000100000000", false}, - {"0001:0000000100000000", true}, - {"1 : 0000000100000000", false}, - {"1:0000000a00000000", true}, - {"1:0000000A00000000", false}, - } - - for i, tc := range cases { - _, err := ParseCoin(tc.coinStr) - if tc.expectPass { - require.NoError(t, err, "unexpected result for IsValid, tc #%d", i) - } else { - require.Error(t, err, "unexpected result for IsValid, tc #%d", i) - } - } -} - -func TestParseCoins(t *testing.T) { - cases := []struct { - coinStr string - expectPass bool - }{ - {"1:0000000100000000", true}, - {"1:0000000100000000,2:0000000200000000", true}, - {"1:0000000100000000,2:0000000200000000,3:0000000300000000", true}, - {"1:0000000100000000 , 2:0000000200000000 , 3:0000000300000000", true}, - } - - for i, tc := range cases { - _, err := ParseCoins(tc.coinStr) - if tc.expectPass { - require.NoError(t, err, "unexpected result for IsValid, tc #%d", i) - } else { - require.Error(t, err, "unexpected result for IsValid, tc #%d", i) - } - } -} diff --git a/x/collection/internal/types/collection.go b/x/collection/internal/types/collection.go deleted file mode 100644 index 78991d3d27..0000000000 --- a/x/collection/internal/types/collection.go +++ /dev/null @@ -1,69 +0,0 @@ -package types - -import ( - "encoding/json" -) - -type Findable interface { - IDAtIndex(index int) string - Len() int -} -type Collection interface { - GetContractID() string - GetName() string - SetName(name string) - GetBaseImgURI() string - SetBaseImgURI(baseImgURI string) - GetMeta() string - SetMeta(meta string) - String() string -} -type BaseCollection struct { - ContractID string `json:"contract_id"` - Name string `json:"name"` - Meta string `json:"meta"` - BaseImgURI string `json:"base_img_uri"` -} - -func NewCollection(contractID, name, meta, baseImgURI string) Collection { - return &BaseCollection{ - ContractID: contractID, - Name: name, - Meta: meta, - BaseImgURI: baseImgURI, - } -} - -func (c BaseCollection) GetContractID() string { return c.ContractID } -func (c BaseCollection) GetName() string { return c.Name } -func (c *BaseCollection) SetName(name string) { - c.Name = name -} - -func (c BaseCollection) GetMeta() string { return c.Meta } -func (c *BaseCollection) SetMeta(meta string) { - c.Meta = meta -} - -func (c BaseCollection) GetBaseImgURI() string { return c.BaseImgURI } -func (c *BaseCollection) SetBaseImgURI(baseImgURI string) { - c.BaseImgURI = baseImgURI -} - -func (c BaseCollection) String() string { - b, err := json.Marshal(c) - if err != nil { - panic(err) - } - return string(b) -} - -type Collections []Collection - -func (collections Collections) String() string { - b, err := json.Marshal(collections) - if err != nil { - panic(err) - } - return string(b) -} diff --git a/x/collection/internal/types/collection_test.go b/x/collection/internal/types/collection_test.go deleted file mode 100644 index 5267312e61..0000000000 --- a/x/collection/internal/types/collection_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSetCollection(t *testing.T) { - collection := NewCollection(defaultContractID, defaultName, defaultMeta, defaultBaseImgURI) - collection.SetName("new_name") - collection.SetBaseImgURI("new_uri") - collection.SetMeta("new_meta") - require.Equal(t, "new_name", collection.GetName()) - require.Equal(t, "new_uri", collection.GetBaseImgURI()) - require.Equal(t, "new_meta", collection.GetMeta()) -} diff --git a/x/collection/internal/types/common_test.go b/x/collection/internal/types/common_test.go deleted file mode 100644 index 4cc490147e..0000000000 --- a/x/collection/internal/types/common_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - defaultName = "name" - defaultContractID = "abcdef01" - defaultBaseImgURI = "base-img-uri" - defaultMeta = "{}" - defaultDecimals = 6 - defaultAmount = 1000 - defaultTokenType = "10000001" - defaultTokenIndex = "00000001" - defaultTokenID1 = defaultTokenType + defaultTokenIndex - defaultTokenID2 = defaultTokenType + "00000002" - defaultTokenTypeFT = "00000001" - defaultTokenIDFT = defaultTokenTypeFT + "00000000" -) - -var ( - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) -) diff --git a/x/collection/internal/types/encoder.go b/x/collection/internal/types/encoder.go deleted file mode 100644 index e553a846b0..0000000000 --- a/x/collection/internal/types/encoder.go +++ /dev/null @@ -1,134 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - EncodeRouterKey = "collectionencode" -) - -type MsgRoute string - -const ( - RCreateCollection = MsgRoute("create") - RIssueNFT = MsgRoute("issue_nft") - RIssueFT = MsgRoute("issue_ft") - RMintFT = MsgRoute("mint_ft") - RMintNFT = MsgRoute("mint_nft") - RBurnNFT = MsgRoute("burn_nft") - RBurnFT = MsgRoute("burn_ft") - RBurnFTFrom = MsgRoute("burn_ft_from") - RBurnNFTFrom = MsgRoute("burn_nft_from") - RTransferFT = MsgRoute("transfer_ft") - RTransferNFT = MsgRoute("transfer_nft") - RTransferFTFrom = MsgRoute("transfer_ft_from") - RTransferNFTFrom = MsgRoute("transfer_nft_from") - RModify = MsgRoute("modify") - RApprove = MsgRoute("approve") - RDisapprove = MsgRoute("disapprove") - RGrantPerm = MsgRoute("grant_perm") - RRevokePerm = MsgRoute("revoke_perm") - RAttach = MsgRoute("attach") - RDetach = MsgRoute("detach") - RAttachFrom = MsgRoute("attach_from") - RDetachFrom = MsgRoute("detach_from") -) - -type WasmCustomMsg struct { - Route string `json:"route"` - Data json.RawMessage `json:"data"` -} - -type WasmCustomQuerier struct { - Route string `json:"route"` - Data json.RawMessage `json:"data"` -} - -type QueryCollectionWrapper struct { - CollectionParam CollectionParam `json:"collection_param"` -} - -type QueryBalanceWrapper struct { - BalanceParam BalanceParam `json:"balance_param"` -} - -type QueryTokenTypesWrapper struct { - TokenTypesParam TokenTypesParam `json:"tokentypes_param"` -} - -type QueryTokensWrapper struct { - TokensParam TokensParam `json:"tokens_param"` -} - -type QueryTokenTypeWrapper struct { - TokenTypeParam TokenTypeParam `json:"token_type_param"` -} - -type QueryNFTCountWrapper struct { - TokensParam TokensParam `json:"tokens_param"` -} - -type QueryTotalWrapper struct { - TotalParam TotalParam `json:"total_param"` -} - -type QueryPermsWrapper struct { - PermParam PermParam `json:"perm_param"` -} - -type QueryApprovedWrapper struct { - IsApprovedParam IsApprovedParam `json:"is_approved_param"` -} - -type QueryApproversWrapper struct { - ApproversParam ApproversParam `json:"approvers_param"` -} - -type CollectionParam struct { - ContractID string `json:"contract_id"` -} - -type BalanceParam struct { - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` - Addr sdk.AccAddress `json:"addr"` -} - -type TokenTypesParam struct { - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` -} - -type TokensParam struct { - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` -} - -type TokenTypeParam struct { - ContractID string `json:"contract_id"` - TokenType string `json:"token_type"` -} - -type TotalParam struct { - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` -} - -type PermParam struct { - ContractID string `json:"contract_id"` - Address sdk.AccAddress `json:"address"` -} - -type ApproversParam struct { - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` -} - -type IsApprovedParam struct { - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` - Approver sdk.AccAddress `json:"approver"` -} diff --git a/x/collection/internal/types/errors.go b/x/collection/internal/types/errors.go deleted file mode 100644 index 8b8d87edcc..0000000000 --- a/x/collection/internal/types/errors.go +++ /dev/null @@ -1,68 +0,0 @@ -package types - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -var ( - ErrTokenExist = sdkerrors.Register(ModuleName, 1, "token symbol, token-id already exists") - ErrTokenNotExist = sdkerrors.Register(ModuleName, 2, "token symbol, token-id does not exist") - ErrTokenNotMintable = sdkerrors.Register(ModuleName, 3, "token symbol, token-id is not mintable") - ErrInvalidTokenName = sdkerrors.Register(ModuleName, 4, "token name should not be empty") - ErrInvalidTokenID = sdkerrors.Register(ModuleName, 5, "invalid token id") - ErrInvalidTokenDecimals = sdkerrors.Register(ModuleName, 6, "token decimals should be within the range in 0 ~ 18") - ErrInvalidIssueFT = sdkerrors.Register(ModuleName, 7, "Issuing token with amount[1], decimals[0], mintable[false] prohibited. Issue nft token instead.") - ErrInvalidAmount = sdkerrors.Register(ModuleName, 8, "invalid token amount") - ErrInvalidBaseImgURILength = sdkerrors.Register(ModuleName, 9, "invalid base_img_uri length") - ErrInvalidNameLength = sdkerrors.Register(ModuleName, 10, "invalid name length") - ErrInvalidTokenType = sdkerrors.Register(ModuleName, 11, "invalid token type pattern found") - ErrInvalidTokenIndex = sdkerrors.Register(ModuleName, 12, "invalid token index pattern found") - ErrCollectionExist = sdkerrors.Register(ModuleName, 13, "collection already exists") - ErrCollectionNotExist = sdkerrors.Register(ModuleName, 14, "collection does not exists") - ErrTokenTypeExist = sdkerrors.Register(ModuleName, 15, "token type for contract_id, token-type already exists") - ErrTokenTypeNotExist = sdkerrors.Register(ModuleName, 16, "token type for contract_id, token-type does not exist") - ErrTokenTypeFull = sdkerrors.Register(ModuleName, 17, "all token type for contract_id are occupied") - ErrTokenIndexFull = sdkerrors.Register(ModuleName, 18, "all non-fungible token index for contract_id, token-type are occupied") - ErrTokenIDFull = sdkerrors.Register(ModuleName, 19, "all fungible token-id for contract_id are occupied") - ErrTokenNoPermission = sdkerrors.Register(ModuleName, 20, "account does not have the permission") - ErrTokenAlreadyAChild = sdkerrors.Register(ModuleName, 21, "token is already a child of some other") - ErrTokenNotAChild = sdkerrors.Register(ModuleName, 22, "token is not a child of some other") - ErrTokenNotOwnedBy = sdkerrors.Register(ModuleName, 23, "token is being not owned by") - ErrTokenCannotTransferChildToken = sdkerrors.Register(ModuleName, 24, "cannot transfer a child token") - ErrTokenNotNFT = sdkerrors.Register(ModuleName, 25, "token is not a NFT") - ErrCannotAttachToItself = sdkerrors.Register(ModuleName, 26, "cannot attach token to itself") - ErrCannotAttachToADescendant = sdkerrors.Register(ModuleName, 27, "cannot attach token to a descendant") - ErrApproverProxySame = sdkerrors.Register(ModuleName, 28, "approver is same with proxy") - ErrCollectionNotApproved = sdkerrors.Register(ModuleName, 29, "proxy is not approved on the collection") - ErrCollectionAlreadyApproved = sdkerrors.Register(ModuleName, 30, "proxy is already approved on the collection") - ErrAccountExist = sdkerrors.Register(ModuleName, 31, "account already exists") - ErrAccountNotExist = sdkerrors.Register(ModuleName, 32, "account does not exists") - ErrInsufficientSupply = sdkerrors.Register(ModuleName, 33, "insufficient supply") - ErrInvalidCoin = sdkerrors.Register(ModuleName, 34, "invalid coin") - ErrInvalidChangesFieldCount = sdkerrors.Register(ModuleName, 35, "invalid count of field changes") - ErrEmptyChanges = sdkerrors.Register(ModuleName, 36, "changes is empty") - ErrInvalidChangesField = sdkerrors.Register(ModuleName, 37, "invalid field of changes") - ErrTokenIndexWithoutType = sdkerrors.Register(ModuleName, 38, "There is a token index but no token type") - ErrTokenTypeFTWithoutIndex = sdkerrors.Register(ModuleName, 39, "There is a token type of ft but no token index") - ErrInsufficientToken = sdkerrors.Register(ModuleName, 40, "insufficient token") - ErrDuplicateChangesField = sdkerrors.Register(ModuleName, 41, "duplicate field of changes") - ErrInvalidMetaLength = sdkerrors.Register(ModuleName, 42, "invalid meta length") - ErrSupplyOverflow = sdkerrors.Register(ModuleName, 43, "supply for collection reached maximum") - ErrEmptyField = sdkerrors.Register(ModuleName, 44, "required field cannot be empty") - ErrCompositionTooDeep = sdkerrors.Register(ModuleName, 45, "cannot attach token (composition too deep)") - ErrCompositionTooWide = sdkerrors.Register(ModuleName, 46, "cannot attach token (composition too wide)") - ErrBurnNonRootNFT = sdkerrors.Register(ModuleName, 47, "cannot burn non-root NFTs") - ErrInvalidPermissionAction = sdkerrors.Register(ModuleName, 48, "invalid permission action") -) - -func WrapIfOverflowPanic(r interface{}) error { - if isOverflowPanic(r) { - return ErrSupplyOverflow - } - // unknown panic, bubble up :( - panic(r) -} - -func isOverflowPanic(r interface{}) bool { - return r == "Int overflow" || r == "negative coin amount" -} diff --git a/x/collection/internal/types/events.go b/x/collection/internal/types/events.go deleted file mode 100644 index bc039fb23b..0000000000 --- a/x/collection/internal/types/events.go +++ /dev/null @@ -1,54 +0,0 @@ -package types - -var ( - EventTypeIssueFT = "issue_ft" - EventTypeIssueNFT = "issue_nft" - EventTypeMintFT = "mint_ft" - EventTypeBurnFT = "burn_ft" - EventTypeMintNFT = "mint_nft" - EventTypeModifyCollection = "modify_collection" - EventTypeModifyTokenType = "modify_token_type" /* #nosec */ - EventTypeModifyToken = "modify_token" - EventTypeGrantPermToken = "grant_perm" - EventTypeRevokePermToken = "revoke_perm" - EventTypeCreateCollection = "create_collection" - EventTypeAttachToken = "attach" /* #nosec */ - EventTypeDetachToken = "detach" /* #nosec */ - EventTypeAttachFrom = "attach_from" - EventTypeDetachFrom = "detach_from" - EventTypeTransfer = "transfer" - EventTypeTransferFT = "transfer_ft" - EventTypeTransferNFT = "transfer_nft" - EventTypeTransferFTFrom = "transfer_ft_from" - EventTypeTransferNFTFrom = "transfer_nft_from" - EventTypeOperationTransferNFT = "operation_transfer_nft" - EventTypeApproveCollection = "approve_collection" - EventTypeDisapproveCollection = "disapprove_collection" - EventTypeBurnNFT = "burn_nft" - EventTypeBurnFTFrom = "burn_ft_from" - EventTypeBurnNFTFrom = "burn_nft_from" - EventTypeOperationBurnNFT = "operation_burn_nft" - EventTypeOperationRootChanged = "operation_root_changed" - - AttributeKeyName = "name" - AttributeKeyMeta = "meta" - AttributeKeyContractID = "contract_id" - AttributeKeyTokenID = "token_id" - AttributeKeyOwner = "owner" - AttributeKeyAmount = "amount" - AttributeKeyDecimals = "decimals" - AttributeKeyBaseImgURI = "base_img_uri" - AttributeKeyMintable = "mintable" - AttributeKeyTokenType = "token_type" - AttributeKeyFrom = "from" - AttributeKeyTo = "to" - AttributeKeyPerm = "perm" - AttributeKeyToTokenID = "to_token_id" - AttributeKeyFromTokenID = "from_token_id" - AttributeKeyApprover = "approver" - AttributeKeyProxy = "proxy" - AttributeKeyOldRoot = "old_root_token_id" - AttributeKeyNewRoot = "new_root_token_id" - - AttributeValueCategory = ModuleName -) diff --git a/x/collection/internal/types/expected_keeper.go b/x/collection/internal/types/expected_keeper.go deleted file mode 100644 index 865b6266c3..0000000000 --- a/x/collection/internal/types/expected_keeper.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - auth "github.com/cosmos/cosmos-sdk/x/auth/exported" -) - -type AccountKeeper interface { - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) auth.Account - GetAccount(ctx sdk.Context, addr sdk.AccAddress) auth.Account - SetAccount(ctx sdk.Context, acc auth.Account) -} diff --git a/x/collection/internal/types/key.go b/x/collection/internal/types/key.go deleted file mode 100644 index 8cdac7d26c..0000000000 --- a/x/collection/internal/types/key.go +++ /dev/null @@ -1,96 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - ModuleName = "collection" - - StoreKey = ModuleName - RouterKey = ModuleName -) - -var ( - AccountKeyPrefix = []byte{0x00} - CollectionKeyPrefix = []byte{0x01} - SupplyKeyPrefix = []byte{0x02} - TokenKeyPrefix = []byte{0x03} - TokenTypeKeyPrefix = []byte{0x04} - TokenChildToParentKeyPrefix = []byte{0x05} - TokenParentToChildKeyPrefix = []byte{0x06} - CollectionApprovedKeyPrefix = []byte{0x07} - NextTokenTypeFTKeyPrefix = []byte{0x08} - NextTokenTypeNFTKeyPrefix = []byte{0x09} - NextTokenIDNFTKeyPrefix = []byte{0x0a} - PermKeyPrefix = []byte{0x0b} - AccountOwnNFTKeyPrefix = []byte{0x0c} - TokenTypeMintCountPrefix = []byte{0x0d} - TokenTypeBurnCountPrefix = []byte{0x0e} -) - -func AccountKey(contractID string, acc sdk.AccAddress) []byte { - return append(append(AccountKeyPrefix, []byte(contractID)...), acc...) -} - -func SupplyKey(contractID string) []byte { - return append(SupplyKeyPrefix, []byte(contractID)...) -} - -func CollectionKey(contractID string) []byte { - return append(CollectionKeyPrefix, []byte(contractID)...) -} - -func TokenKey(contractID, tokenID string) []byte { - return append(append(TokenKeyPrefix, []byte(contractID)...), []byte(tokenID)...) -} - -func TokenTypeKey(contractID, tokenType string) []byte { - return append(append(TokenTypeKeyPrefix, []byte(contractID)...), []byte(tokenType)...) -} - -func TokenChildToParentKey(contractID, tokenID string) []byte { - return append(append(TokenChildToParentKeyPrefix, []byte(contractID)...), []byte(tokenID)...) -} - -func TokenParentToChildSubKey(contractID, parent string) []byte { - return append(append(TokenParentToChildKeyPrefix, []byte(contractID)...), []byte(parent)...) -} - -func TokenParentToChildKey(contractID, parent, child string) []byte { - return append(append(append(TokenParentToChildKeyPrefix, []byte(contractID)...), []byte(parent)...), []byte(child)...) -} - -func CollectionApprovedKey(contractID string, proxy sdk.AccAddress, approver sdk.AccAddress) []byte { - return append(CollectionApproversKey(contractID, proxy), approver.Bytes()...) -} - -func CollectionApproversKey(contractID string, proxy sdk.AccAddress) []byte { - return append(append(CollectionApprovedKeyPrefix, []byte(contractID)...), proxy.Bytes()...) -} - -func NextTokenTypeFTKey(contractID string) []byte { - return append(NextTokenTypeFTKeyPrefix, []byte(contractID)...) -} -func NextTokenTypeNFTKey(contractID string) []byte { - return append(NextTokenTypeNFTKeyPrefix, []byte(contractID)...) -} -func NextTokenIDNFTKey(contractID, tokenType string) []byte { - return append(append(NextTokenIDNFTKeyPrefix, []byte(contractID)...), []byte(tokenType)...) -} - -func PermKey(contractID string, addr sdk.AccAddress) []byte { - return append(append(PermKeyPrefix, []byte(contractID)...), addr...) -} - -func AccountOwnNFTKey(contractID string, owner sdk.AccAddress, tokenID string) []byte { - return append(append(append(AccountOwnNFTKeyPrefix, []byte(contractID)...), owner.Bytes()...), []byte(tokenID)...) -} - -func TokenTypeMintCount(contractID, tokenType string) []byte { - return append(append(TokenTypeMintCountPrefix, []byte(contractID)...), []byte(tokenType)...) -} - -func TokenTypeBurnCount(contractID, tokenType string) []byte { - return append(append(TokenTypeBurnCountPrefix, []byte(contractID)...), []byte(tokenType)...) -} diff --git a/x/collection/internal/types/key_test.go b/x/collection/internal/types/key_test.go deleted file mode 100644 index d21a419773..0000000000 --- a/x/collection/internal/types/key_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -func TestKeys(t *testing.T) { - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - contractID1 := "abcdef012" - contractID2 := "abcdef013" - - require.NotEqual(t, CollectionApprovedKey(contractID1, addr1, addr2), CollectionApprovedKey(contractID1, addr2, addr1)) - require.NotEqual(t, CollectionApprovedKey(contractID1, addr1, addr2), CollectionApprovedKey(contractID2, addr1, addr2)) -} diff --git a/x/collection/internal/types/modify.go b/x/collection/internal/types/modify.go deleted file mode 100644 index a0e22b2c6f..0000000000 --- a/x/collection/internal/types/modify.go +++ /dev/null @@ -1,29 +0,0 @@ -package types - -type Change struct { - Field string `json:"field"` - Value string `json:"value"` -} - -func NewChange(field string, value string) Change { - return Change{ - Field: field, - Value: value, - } -} - -type Changes []Change - -func NewChanges(changes ...Change) Changes { - return changes -} - -func NewChangesWithMap(changesMap map[string]string) Changes { - changes := make([]Change, len(changesMap)) - idx := 0 - for k, v := range changesMap { - changes[idx] = Change{Field: k, Value: v} - idx++ - } - return NewChanges(changes...) -} diff --git a/x/collection/internal/types/msgs_collection.go b/x/collection/internal/types/msgs_collection.go deleted file mode 100644 index 9cb1fd55bc..0000000000 --- a/x/collection/internal/types/msgs_collection.go +++ /dev/null @@ -1,51 +0,0 @@ -package types - -import ( - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -var _ sdk.Msg = (*MsgCreateCollection)(nil) - -type MsgCreateCollection struct { - Owner sdk.AccAddress `json:"owner"` - Name string `json:"name"` - Meta string `json:"meta"` - BaseImgURI string `json:"base_img_uri"` -} - -func NewMsgCreateCollection(owner sdk.AccAddress, name, meta, baseImgURI string) MsgCreateCollection { - return MsgCreateCollection{ - Owner: owner, - Name: name, - Meta: meta, - BaseImgURI: baseImgURI, - } -} - -func (msg MsgCreateCollection) ValidateBasic() error { - if msg.Owner.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty") - } - if !ValidateName(msg.Name) { - return sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Name, MaxTokenNameLength, utf8.RuneCountInString(msg.Name)) - } - if !ValidateMeta(msg.Meta) { - return sdkerrors.Wrapf(ErrInvalidMetaLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Meta, MaxTokenMetaLength, utf8.RuneCountInString(msg.Meta)) - } - if !ValidateBaseImgURI(msg.BaseImgURI) { - return sdkerrors.Wrapf(ErrInvalidBaseImgURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.BaseImgURI, MaxBaseImgURILength, utf8.RuneCountInString(msg.BaseImgURI)) - } - return nil -} - -func (MsgCreateCollection) Route() string { return RouterKey } -func (MsgCreateCollection) Type() string { return "create_collection" } -func (msg MsgCreateCollection) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} -func (msg MsgCreateCollection) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Owner} -} diff --git a/x/collection/internal/types/msgs_compossible.go b/x/collection/internal/types/msgs_compossible.go deleted file mode 100644 index 4b5d13d773..0000000000 --- a/x/collection/internal/types/msgs_compossible.go +++ /dev/null @@ -1,255 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgAttach)(nil) -var _ contract.Msg = (*MsgDetach)(nil) -var _ contract.Msg = (*MsgAttachFrom)(nil) -var _ contract.Msg = (*MsgDetachFrom)(nil) - -type MsgAttach struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - ToTokenID string `json:"to_token_id"` - TokenID string `json:"token_id"` -} - -func NewMsgAttach(from sdk.AccAddress, contractID string, toTokenID string, tokenID string) MsgAttach { - return MsgAttach{ - From: from, - ContractID: contractID, - ToTokenID: toTokenID, - TokenID: tokenID, - } -} - -func (msg MsgAttach) MarshalJSON() ([]byte, error) { - type msgAlias MsgAttach - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgAttach) UnmarshalJSON(data []byte) error { - type msgAlias *MsgAttach - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgAttach) Route() string { return RouterKey } - -func (MsgAttach) Type() string { return "attach" } - -func (msg MsgAttach) GetContractID() string { return msg.ContractID } - -func (msg MsgAttach) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - - if err := ValidateTokenID(msg.ToTokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, msg.ToTokenID) - } - - if err := ValidateTokenID(msg.TokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, msg.TokenID) - } - - if msg.ToTokenID == msg.TokenID { - return sdkerrors.Wrapf(ErrCannotAttachToItself, "TokenID: %s", msg.TokenID) - } - - return nil -} - -func (msg MsgAttach) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgAttach) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -type MsgDetach struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` -} - -func NewMsgDetach(from sdk.AccAddress, contractID string, tokenID string) MsgDetach { - return MsgDetach{ - From: from, - ContractID: contractID, - TokenID: tokenID, - } -} - -func (msg MsgDetach) MarshalJSON() ([]byte, error) { - type msgAlias MsgDetach - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgDetach) UnmarshalJSON(data []byte) error { - type msgAlias *MsgDetach - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgDetach) Route() string { return RouterKey } - -func (MsgDetach) Type() string { return "detach" } - -func (msg MsgDetach) GetContractID() string { return msg.ContractID } - -func (msg MsgDetach) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - - if err := ValidateTokenID(msg.TokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, msg.TokenID) - } - - return nil -} - -func (msg MsgDetach) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgDetach) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -type MsgAttachFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - ToTokenID string `json:"to_token_id"` - TokenID string `json:"token_id"` -} - -func NewMsgAttachFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, toTokenID string, tokenID string) MsgAttachFrom { - return MsgAttachFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - ToTokenID: toTokenID, - TokenID: tokenID, - } -} - -func (msg MsgAttachFrom) MarshalJSON() ([]byte, error) { - type msgAlias MsgAttachFrom - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgAttachFrom) UnmarshalJSON(data []byte) error { - type msgAlias *MsgAttachFrom - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgAttachFrom) Route() string { return RouterKey } - -func (MsgAttachFrom) Type() string { return "attach_from" } - -func (msg MsgAttachFrom) GetContractID() string { return msg.ContractID } - -func (msg MsgAttachFrom) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if err := ValidateTokenID(msg.ToTokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, msg.ToTokenID) - } - if err := ValidateTokenID(msg.TokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, msg.TokenID) - } - - if msg.ToTokenID == msg.TokenID { - return sdkerrors.Wrapf(ErrCannotAttachToItself, "TokenID: %s", msg.TokenID) - } - - return nil -} - -func (msg MsgAttachFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgAttachFrom) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Proxy} -} - -type MsgDetachFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - TokenID string `json:"token_id"` -} - -func NewMsgDetachFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, tokenID string) MsgDetachFrom { - return MsgDetachFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - TokenID: tokenID, - } -} - -func (msg MsgDetachFrom) MarshalJSON() ([]byte, error) { - type msgAlias MsgDetachFrom - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgDetachFrom) UnmarshalJSON(data []byte) error { - type msgAlias *MsgDetachFrom - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgDetachFrom) Route() string { return RouterKey } - -func (MsgDetachFrom) Type() string { return "detach_from" } - -func (msg MsgDetachFrom) GetContractID() string { return msg.ContractID } - -func (msg MsgDetachFrom) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if err := ValidateTokenID(msg.TokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, msg.TokenID) - } - - return nil -} - -func (msg MsgDetachFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgDetachFrom) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Proxy} -} diff --git a/x/collection/internal/types/msgs_issue.go b/x/collection/internal/types/msgs_issue.go deleted file mode 100644 index 91c1ddd497..0000000000 --- a/x/collection/internal/types/msgs_issue.go +++ /dev/null @@ -1,117 +0,0 @@ -package types - -import ( - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgIssueFT)(nil) - -type MsgIssueFT struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Name string `json:"name"` - Meta string `json:"meta"` - Amount sdk.Int `json:"amount"` - Mintable bool `json:"mintable"` - Decimals sdk.Int `json:"decimals"` -} - -func NewMsgIssueFT(owner, to sdk.AccAddress, contractID string, name, meta string, amount sdk.Int, decimal sdk.Int, mintable bool) MsgIssueFT { - return MsgIssueFT{ - Owner: owner, - ContractID: contractID, - To: to, - Name: name, - Meta: meta, - Amount: amount, - Mintable: mintable, - Decimals: decimal, - } -} - -func (msg MsgIssueFT) Route() string { return RouterKey } -func (msg MsgIssueFT) Type() string { return "issue_ft" } -func (msg MsgIssueFT) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Owner} } -func (msg MsgIssueFT) GetContractID() string { return msg.ContractID } -func (msg MsgIssueFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgIssueFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if len(msg.Name) == 0 { - return ErrInvalidTokenName - } - if msg.Owner.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "to address cannot be empty") - } - - if msg.Amount.Equal(sdk.NewInt(1)) && msg.Decimals.Equal(sdk.NewInt(0)) && !msg.Mintable { - return ErrInvalidIssueFT - } - - if msg.Decimals.GT(sdk.NewInt(18)) || msg.Decimals.IsNegative() { - return sdkerrors.Wrapf(ErrInvalidTokenDecimals, "Decimals: %s", msg.Decimals) - } - - if !ValidateName(msg.Name) { - return sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Name, MaxTokenNameLength, utf8.RuneCountInString(msg.Name)) - } - if !ValidateMeta(msg.Meta) { - return sdkerrors.Wrapf(ErrInvalidMetaLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Meta, MaxTokenMetaLength, utf8.RuneCountInString(msg.Meta)) - } - return nil -} - -var _ contract.Msg = (*MsgIssueNFT)(nil) - -type MsgIssueNFT struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - Name string `json:"name"` - Meta string `json:"meta"` -} - -func NewMsgIssueNFT(owner sdk.AccAddress, contractID, name, meta string) MsgIssueNFT { - return MsgIssueNFT{ - Owner: owner, - ContractID: contractID, - Name: name, - Meta: meta, - } -} - -func (MsgIssueNFT) Route() string { return RouterKey } -func (MsgIssueNFT) Type() string { return "issue_nft" } -func (msg MsgIssueNFT) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Owner} } -func (msg MsgIssueNFT) GetContractID() string { return msg.ContractID } -func (msg MsgIssueNFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgIssueNFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - if msg.Owner.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty") - } - if !ValidateName(msg.Name) { - return sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Name, MaxTokenNameLength, utf8.RuneCountInString(msg.Name)) - } - if !ValidateMeta(msg.Meta) { - return sdkerrors.Wrapf(ErrInvalidMetaLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Meta, MaxTokenMetaLength, utf8.RuneCountInString(msg.Meta)) - } - return nil -} diff --git a/x/collection/internal/types/msgs_mint.go b/x/collection/internal/types/msgs_mint.go deleted file mode 100644 index 108d80996a..0000000000 --- a/x/collection/internal/types/msgs_mint.go +++ /dev/null @@ -1,327 +0,0 @@ -package types - -import ( - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgMintNFT)(nil) - -type MintNFTParam struct { - Name string `json:"name"` - Meta string `json:"meta"` - TokenType string `json:"token_type"` -} - -func NewMintNFTParam(name, meta, tokenType string) MintNFTParam { - return MintNFTParam{ - Name: name, - Meta: meta, - TokenType: tokenType, - } -} - -type MsgMintNFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - MintNFTParams []MintNFTParam `json:"params"` -} - -func NewMsgMintNFT(from sdk.AccAddress, contractID string, to sdk.AccAddress, mintNFTParams ...MintNFTParam) MsgMintNFT { - return MsgMintNFT{ - From: from, - ContractID: contractID, - To: to, - MintNFTParams: mintNFTParams, - } -} - -func (msg MsgMintNFT) Route() string { return RouterKey } -func (msg MsgMintNFT) Type() string { return "mint_nft" } -func (msg MsgMintNFT) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgMintNFT) GetContractID() string { return msg.ContractID } -func (msg MsgMintNFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgMintNFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from address cannot be empty") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "to address cannot be empty") - } - - if len(msg.MintNFTParams) == 0 { - return sdkerrors.Wrap(ErrEmptyField, "params cannot be empty") - } - for _, mintNFTParam := range msg.MintNFTParams { - if len(mintNFTParam.Name) == 0 { - return ErrInvalidTokenName - } - if !ValidateName(mintNFTParam.Name) { - return sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", mintNFTParam.Name, MaxTokenNameLength, utf8.RuneCountInString(mintNFTParam.Name)) - } - if !ValidateMeta(mintNFTParam.Meta) { - return sdkerrors.Wrapf(ErrInvalidMetaLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", mintNFTParam.Meta, MaxTokenMetaLength, utf8.RuneCountInString(mintNFTParam.Meta)) - } - if err := ValidateTokenTypeNFT(mintNFTParam.TokenType); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, err.Error()) - } - } - - return nil -} - -var _ contract.Msg = (*MsgBurnNFT)(nil) - -type MsgBurnNFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - TokenIDs []string `json:"token_ids"` -} - -func NewMsgBurnNFT(from sdk.AccAddress, contractID string, tokenIDs ...string) MsgBurnNFT { - return MsgBurnNFT{ - From: from, - ContractID: contractID, - TokenIDs: tokenIDs, - } -} - -func (msg MsgBurnNFT) Route() string { return RouterKey } -func (msg MsgBurnNFT) Type() string { return "burn_nft" } -func (msg MsgBurnNFT) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgBurnNFT) GetContractID() string { return msg.ContractID } -func (msg MsgBurnNFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgBurnNFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty") - } - - if len(msg.TokenIDs) == 0 { - return sdkerrors.Wrap(ErrEmptyField, "token_ids cannot be empty") - } - for _, tokenID := range msg.TokenIDs { - if err := ValidateTokenID(tokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, err.Error()) - } - if err := ValidateTokenTypeNFT(tokenID[:TokenTypeLength]); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, err.Error()) - } - } - - return nil -} - -var _ contract.Msg = (*MsgBurnNFTFrom)(nil) - -type MsgBurnNFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - TokenIDs []string `json:"token_ids"` -} - -func NewMsgBurnNFTFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, tokenIDs ...string) MsgBurnNFTFrom { - return MsgBurnNFTFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - TokenIDs: tokenIDs, - } -} - -func (msg MsgBurnNFTFrom) Route() string { return RouterKey } -func (msg MsgBurnNFTFrom) Type() string { return "burn_nft_from" } -func (msg MsgBurnNFTFrom) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Proxy} } -func (msg MsgBurnNFTFrom) GetContractID() string { return msg.ContractID } -func (msg MsgBurnNFTFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgBurnNFTFrom) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if msg.Proxy.Equals(msg.From) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.Proxy.String()) - } - - if len(msg.TokenIDs) == 0 { - return sdkerrors.Wrap(ErrEmptyField, "token_ids cannot be empty") - } - for _, tokenID := range msg.TokenIDs { - if err := ValidateTokenID(tokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, err.Error()) - } - if err := ValidateTokenTypeNFT(tokenID[:TokenTypeLength]); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, err.Error()) - } - } - return nil -} - -var _ contract.Msg = (*MsgMintFT)(nil) - -type MsgMintFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount Coins `json:"amount"` -} - -func NewMsgMintFT(from sdk.AccAddress, contractID string, to sdk.AccAddress, amount ...Coin) MsgMintFT { - return MsgMintFT{ - From: from, - ContractID: contractID, - To: to, - Amount: amount, - } -} -func (MsgMintFT) Route() string { return RouterKey } -func (MsgMintFT) Type() string { return "mint_ft" } -func (msg MsgMintFT) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgMintFT) GetContractID() string { return msg.ContractID } -func (msg MsgMintFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgMintFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - for _, tokenID := range msg.Amount { - if err := ValidateDenom(tokenID.Denom); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id") - } - } - - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from address cannot be empty") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "to address cannot be empty") - } - - return nil -} - -var _ contract.Msg = (*MsgBurnFT)(nil) - -type MsgBurnFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Amount Coins `json:"amount"` -} - -func NewMsgBurnFT(from sdk.AccAddress, contractID string, amount ...Coin) MsgBurnFT { - return MsgBurnFT{ - From: from, - ContractID: contractID, - Amount: amount, - } -} -func (MsgBurnFT) Route() string { return RouterKey } -func (MsgBurnFT) Type() string { return "burn_ft" } -func (msg MsgBurnFT) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgBurnFT) GetContractID() string { return msg.ContractID } -func (msg MsgBurnFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgBurnFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - for _, tokenID := range msg.Amount { - if err := ValidateDenom(tokenID.Denom); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id") - } - } - - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from address cannot be empty") - } - return nil -} - -var _ contract.Msg = (*MsgBurnFTFrom)(nil) - -type MsgBurnFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - Amount Coins `json:"amount"` -} - -func NewMsgBurnFTFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, amount ...Coin) MsgBurnFTFrom { - return MsgBurnFTFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - Amount: amount, - } -} - -func (MsgBurnFTFrom) Route() string { return RouterKey } -func (MsgBurnFTFrom) Type() string { return "burn_ft_from" } -func (msg MsgBurnFTFrom) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Proxy} } -func (msg MsgBurnFTFrom) GetContractID() string { return msg.ContractID } -func (msg MsgBurnFTFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgBurnFTFrom) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if msg.Proxy.Equals(msg.From) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.Proxy.String()) - } - for _, tokenID := range msg.Amount { - if err := ValidateDenom(tokenID.Denom); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id") - } - } - - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - return nil -} diff --git a/x/collection/internal/types/msgs_modify.go b/x/collection/internal/types/msgs_modify.go deleted file mode 100644 index 487fd7ea29..0000000000 --- a/x/collection/internal/types/msgs_modify.go +++ /dev/null @@ -1,67 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgModify)(nil) - -type MsgModify struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - TokenType string `json:"token_type"` - TokenIndex string `json:"token_index"` - Changes Changes `json:"changes"` -} - -func NewMsgModify(owner sdk.AccAddress, contractID, tokenType, tokenIndex string, changes Changes) MsgModify { - return MsgModify{ - Owner: owner, - ContractID: contractID, - TokenType: tokenType, - TokenIndex: tokenIndex, - Changes: changes, - } -} - -func (msg MsgModify) Route() string { return RouterKey } -func (msg MsgModify) Type() string { return "modify_token" } -func (msg MsgModify) GetContractID() string { return msg.ContractID } -func (msg MsgModify) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} -func (msg MsgModify) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Owner} } - -func (msg MsgModify) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - if msg.Owner.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty") - } - - if msg.TokenType != "" { - if err := ValidateTokenType(msg.TokenType); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenType, msg.TokenType) - } - if ValidateTokenTypeFT(msg.TokenType) == nil && msg.TokenIndex == "" { - return sdkerrors.Wrap(ErrTokenTypeFTWithoutIndex, msg.TokenType) - } - } - if msg.TokenIndex != "" && ValidateTokenIndex(msg.TokenIndex) != nil { - return sdkerrors.Wrap(ErrInvalidTokenIndex, msg.TokenIndex) - } - - validator := NewChangesValidator() - if err := validator.SetMode(msg.TokenType, msg.TokenIndex); err != nil { - return err - } - if err := validator.Validate(msg.Changes); err != nil { - return err - } - - return nil -} diff --git a/x/collection/internal/types/msgs_modify_test.go b/x/collection/internal/types/msgs_modify_test.go deleted file mode 100644 index 44d87fe162..0000000000 --- a/x/collection/internal/types/msgs_modify_test.go +++ /dev/null @@ -1,200 +0,0 @@ -package types - -import ( - "testing" - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - ModifyMsgType = "modify_token" -) - -func TestNewMsgModify(t *testing.T) { - msg := AMsgModify().Build() - - require.Equal(t, ModifyMsgType, msg.Type()) - require.Equal(t, ModuleName, msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, msg.Owner, msg.GetSigners()[0]) -} - -func TestMarshalMsgModify(t *testing.T) { - // Given - msg := AMsgModify().Build() - - // When marshal and unmarshal it - msg2 := MsgModify{} - err := ModuleCdc.UnmarshalJSON(msg.GetSignBytes(), &msg2) - require.NoError(t, err) - - // Then they are equal - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenIndex, msg2.TokenIndex) - require.Equal(t, msg.TokenType, msg2.TokenType) - require.Equal(t, msg.Changes, msg2.Changes) - require.Equal(t, msg.Owner, msg2.Owner) -} - -func TestMsgModify_ValidateBasic(t *testing.T) { - t.Log("normal case") - { - msg := AMsgModify().Build() - require.NoError(t, msg.ValidateBasic()) - } - t.Log("empty contractID found") - { - msg := AMsgModify().Contract("").Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: ").Error()) - } - t.Log("empty owner") - { - msg := AMsgModify().Owner(nil).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty").Error()) - } - t.Log("invalid contractID found") - { - msg := AMsgModify().Contract("0123456789001234567890").Build() - require.EqualError(t, - msg.ValidateBasic(), - sdkerrors.Wrapf(contract.ErrInvalidContractID, "ContractID: %s", msg.ContractID).Error()) - } - t.Log("img uri too long") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"base_img_uri": length1001String})). - Build() - - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidBaseImgURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxBaseImgURILength, utf8.RuneCountInString(length1001String)).Error()) - } - t.Log("name too long") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"name": length1001String})).Build() - - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxTokenNameLength, utf8.RuneCountInString(length1001String)).Error()) - } - t.Log("invalid changes field") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"invalid_field": "val"})).Build() - - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidChangesField, "Field: invalid_field").Error()) - } - t.Log("no token uri field") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"name": "new_name"})).Build() - require.NoError(t, msg.ValidateBasic()) - } - t.Log("Test with changes more than max") - { - // Given msg with changes more than max - changeList := make([]Change, MaxChangeFieldsCount+1) - msg := AMsgModify().Changes(changeList).Build() - - // When validate basic, Then error is occurred - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidChangesFieldCount, "You can not change fields more than [%d] at once, current count: [%d]", MaxChangeFieldsCount, len(changeList)).Error()) - } - t.Log("Test with nft token type") - { - msg := AMsgModify().TokenType(defaultTokenType).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidChangesField, "Field: base_img_uri").Error()) - - msg = AMsgModify().TokenType(defaultTokenType). - Changes(NewChangesWithMap(map[string]string{"name": "new_name"})). - Build() - require.NoError(t, msg.ValidateBasic()) - } - t.Log("Test with nft token type and index") - { - msg := AMsgModify().TokenType(defaultTokenType).TokenIndex(defaultTokenIndex).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidChangesField, "Field: base_img_uri").Error()) - - msg = AMsgModify().TokenType(defaultTokenType).TokenIndex(defaultTokenIndex). - Changes(NewChangesWithMap(map[string]string{"name": "new_name"})). - Build() - require.NoError(t, msg.ValidateBasic()) - } - t.Log("Test with ft token type and index") - { - msg := AMsgModify().TokenType(defaultTokenTypeFT).TokenIndex(defaultTokenIndex).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidChangesField, "Field: base_img_uri").Error()) - - msg = AMsgModify().TokenType(defaultTokenTypeFT).TokenIndex(defaultTokenIndex). - Changes(NewChangesWithMap(map[string]string{"name": "new_name"})). - Build() - require.NoError(t, msg.ValidateBasic()) - } - t.Log("Test with ft token type and not index") - { - msg := AMsgModify().TokenType(defaultTokenTypeFT).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrTokenTypeFTWithoutIndex, defaultTokenTypeFT).Error()) - } - t.Log("Test with invalid token type") - { - invalidTokenType := "010101" - msg := AMsgModify().TokenType(invalidTokenType).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenType, invalidTokenType).Error()) - } - t.Log("Test with invalid token index") - { - invalidTokenIndex := "010101" - msg := AMsgModify().TokenIndex(invalidTokenIndex).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenIndex, invalidTokenIndex).Error()) - } - t.Log("Test with token index not token type") - { - msg := AMsgModify().TokenIndex(defaultTokenIndex).Build() - require.EqualError(t, msg.ValidateBasic(), ErrTokenIndexWithoutType.Error()) - } -} - -func AMsgModify() *MsgModifyBuilder { - return &MsgModifyBuilder{ - msgModify: NewMsgModify( - sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()), - defaultContractID, - "", - "", - NewChangesWithMap(map[string]string{ - "name": "new_name", - "base_img_uri": "new_base_img_uri", - }), - ), - } -} - -type MsgModifyBuilder struct { - msgModify MsgModify -} - -func (b *MsgModifyBuilder) Build() MsgModify { - return b.msgModify -} - -func (b *MsgModifyBuilder) Owner(owner sdk.AccAddress) *MsgModifyBuilder { - b.msgModify.Owner = owner - return b -} - -func (b *MsgModifyBuilder) Contract(contractID string) *MsgModifyBuilder { - b.msgModify.ContractID = contractID - return b -} - -func (b *MsgModifyBuilder) TokenType(tokenType string) *MsgModifyBuilder { - b.msgModify.TokenType = tokenType - return b -} - -func (b *MsgModifyBuilder) TokenIndex(tokenIndex string) *MsgModifyBuilder { - b.msgModify.TokenIndex = tokenIndex - return b -} - -func (b *MsgModifyBuilder) Changes(changes Changes) *MsgModifyBuilder { - b.msgModify.Changes = changes - return b -} diff --git a/x/collection/internal/types/msgs_perm.go b/x/collection/internal/types/msgs_perm.go deleted file mode 100644 index 2a641d3de7..0000000000 --- a/x/collection/internal/types/msgs_perm.go +++ /dev/null @@ -1,95 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ sdk.Msg = (*MsgGrantPermission)(nil) - -func NewMsgGrantPermission(from sdk.AccAddress, contractID string, to sdk.AccAddress, perm Permission) MsgGrantPermission { - return MsgGrantPermission{ - From: from, - ContractID: contractID, - To: to, - Permission: perm, - } -} - -type MsgGrantPermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Permission Permission `json:"permission"` -} - -func (MsgGrantPermission) Route() string { return RouterKey } -func (MsgGrantPermission) Type() string { return "grant_perm" } -func (msg MsgGrantPermission) GetContractID() string { return msg.ContractID } -func (msg MsgGrantPermission) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgGrantPermission) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgGrantPermission) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.From.Empty() || msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "addresses cannot be empty") - } - - if msg.From.Equals(msg.To) { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from, to address can not be the same") - } - - return validateAction(msg.Permission.String(), MintAction, BurnAction, IssueAction, ModifyAction) -} - -var _ sdk.Msg = (*MsgRevokePermission)(nil) - -func NewMsgRevokePermission(from sdk.AccAddress, contractID string, perm Permission) MsgRevokePermission { - return MsgRevokePermission{ - From: from, - ContractID: contractID, - Permission: perm, - } -} - -type MsgRevokePermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Permission Permission `json:"permission"` -} - -func (MsgRevokePermission) Route() string { return RouterKey } -func (MsgRevokePermission) Type() string { return "revoke_perm" } -func (msg MsgRevokePermission) GetContractID() string { return msg.ContractID } -func (msg MsgRevokePermission) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgRevokePermission) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgRevokePermission) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "addresses cannot be empty") - } - - return validateAction(msg.Permission.String(), MintAction, BurnAction, IssueAction, ModifyAction) -} -func validateAction(action string, actions ...string) error { - for _, a := range actions { - if action == a { - return nil - } - } - return sdkerrors.Wrap(ErrInvalidPermissionAction, - fmt.Sprintf("permission action should be one of [%s]", strings.Join(actions, ","))) -} diff --git a/x/collection/internal/types/msgs_proxy.go b/x/collection/internal/types/msgs_proxy.go deleted file mode 100644 index 04bc39c451..0000000000 --- a/x/collection/internal/types/msgs_proxy.go +++ /dev/null @@ -1,91 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgApprove)(nil) - -type MsgApprove struct { - Approver sdk.AccAddress `json:"approver"` - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` -} - -func NewMsgApprove(approver sdk.AccAddress, contractID string, proxy sdk.AccAddress) MsgApprove { - return MsgApprove{ - Approver: approver, - ContractID: contractID, - Proxy: proxy, - } -} - -func (msg MsgApprove) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return nil - } - if msg.Approver.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Approver cannot be empty") - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.Approver.Equals(msg.Proxy) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.Approver.String()) - } - return nil -} - -func (MsgApprove) Route() string { return RouterKey } -func (MsgApprove) Type() string { return "approve_collection" } -func (msg MsgApprove) GetContractID() string { return msg.ContractID } -func (msg MsgApprove) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Approver} -} -func (msg MsgApprove) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -var _ contract.Msg = (*MsgDisapprove)(nil) - -type MsgDisapprove struct { - Approver sdk.AccAddress `json:"approver"` - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` -} - -func NewMsgDisapprove(approver sdk.AccAddress, contractID string, proxy sdk.AccAddress) MsgDisapprove { - return MsgDisapprove{ - Approver: approver, - ContractID: contractID, - Proxy: proxy, - } -} - -func (msg MsgDisapprove) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Approver.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Approver cannot be empty") - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.Approver.Equals(msg.Proxy) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.Approver.String()) - } - return nil -} - -func (MsgDisapprove) Route() string { return RouterKey } -func (MsgDisapprove) Type() string { return "disapprove_collection" } -func (msg MsgDisapprove) GetContractID() string { return msg.ContractID } -func (msg MsgDisapprove) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Approver} -} -func (msg MsgDisapprove) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} diff --git a/x/collection/internal/types/msgs_test.go b/x/collection/internal/types/msgs_test.go deleted file mode 100644 index da54cb8d22..0000000000 --- a/x/collection/internal/types/msgs_test.go +++ /dev/null @@ -1,615 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -func TestMsgBasics(t *testing.T) { - cdc := ModuleCdc - - { - msg := NewMsgIssueFT(addr1, addr1, defaultContractID, defaultName, defaultMeta, sdk.NewInt(1), sdk.NewInt(8), true) - require.Equal(t, "issue_ft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgIssueFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Name, msg2.Name) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.Owner, msg2.Owner) - require.Equal(t, msg.Amount, msg.Amount) - require.Equal(t, msg.Decimals, msg2.Decimals) - require.Equal(t, msg.Mintable, msg2.Mintable) - } - { - msg := NewMsgIssueNFT(addr1, defaultContractID, defaultName, defaultMeta) - require.Equal(t, "issue_nft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgIssueNFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.Owner, msg2.Owner) - require.Equal(t, msg.Name, msg2.Name) - } - { - msg := NewMsgMintFT(addr1, defaultContractID, addr1, OneCoin(defaultTokenIDFT)) - require.Equal(t, "mint_ft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgMintFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.Amount, msg2.Amount) - - msg3 := NewMsgMintFT(addr1, defaultContractID, addr1, Coin{"x000000100000000", sdk.NewInt(1)}) - require.EqualError(t, msg3.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id").Error()) - msg4 := NewMsgMintFT(addr1, defaultContractID, addr1, Coin{"vf12e00000000", sdk.NewInt(1)}) - require.EqualError(t, msg4.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id").Error()) - msg5 := NewMsgMintFT(addr1, defaultContractID, addr1, Coin{"!000000100000000", sdk.NewInt(1)}) - require.EqualError(t, msg5.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id").Error()) - } - { - param := NewMintNFTParam(defaultName, defaultMeta, defaultTokenType) - msg := NewMsgMintNFT(addr1, defaultContractID, addr1, param) - require.Equal(t, "mint_nft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgMintNFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.MintNFTParams[0].Name, msg2.MintNFTParams[0].Name) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.MintNFTParams[0].TokenType, msg2.MintNFTParams[0].TokenType) - - falseParam := NewMintNFTParam("", defaultMeta, defaultTokenType) - msg3 := NewMsgMintNFT(addr1, defaultContractID, addr1, falseParam) - require.Error(t, msg3.ValidateBasic()) - - falseParam = NewMintNFTParam(defaultName, defaultMeta, "abc") - msg4 := NewMsgMintNFT(addr1, defaultContractID, addr1, falseParam) - require.Error(t, msg4.ValidateBasic()) - - msg5 := NewMsgMintNFT(addr1, defaultContractID, addr1) - require.Error(t, msg5.ValidateBasic()) - } - { - msg := NewMsgBurnNFT(addr1, defaultContractID, defaultTokenID1) - require.Equal(t, "burn_nft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgBurnNFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.TokenIDs, msg2.TokenIDs) - - msg3 := NewMsgBurnNFT(addr1, defaultContractID) - require.Error(t, msg3.ValidateBasic()) - } - { - addr2 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - msg := NewMsgGrantPermission(addr1, defaultContractID, addr2, NewIssuePermission()) - require.Equal(t, "grant_perm", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgGrantPermission{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.Permission, msg2.Permission) - } - - { - msg := NewMsgRevokePermission(addr1, defaultContractID, NewIssuePermission()) - require.Equal(t, "revoke_perm", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgRevokePermission{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.Permission, msg2.Permission) - } - { - msg := NewMsgTransferFT(addr1, defaultContractID, addr2, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.Equal(t, "transfer_ft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgTransferFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.Amount, msg2.Amount) - } - - { - msg := NewMsgTransferFT(nil, defaultContractID, addr2, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgTransferFT(addr1, defaultContractID, nil, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty").Error()) - - msg = NewMsgTransferFT(addr1, "", addr2, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: ").Error()) - - require.Panics(t, func() { - NewMsgTransferFT(addr1, defaultContractID, addr2, NewCoin("1", sdk.NewInt(defaultAmount))) - }, "") - - require.Panics(t, func() { - NewMsgTransferFT(addr1, defaultContractID, addr2, NewCoin("1", sdk.NewInt(-1*defaultAmount))) - }, "") - } - - { - msg := NewMsgTransferNFT(addr1, defaultContractID, addr2, defaultTokenID1) - require.Equal(t, "transfer_nft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgTransferNFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenIDs, msg2.TokenIDs) - } - - { - msg := NewMsgTransferNFT(nil, defaultContractID, addr2, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgTransferNFT(addr1, defaultContractID, nil, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty").Error()) - - msg = NewMsgTransferNFT(addr1, "", addr2, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: ").Error()) - - msg = NewMsgTransferNFT(addr1, defaultContractID, addr2, "1") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "symbol [1] mismatched to [^[a-f0-9]{16}$]").Error()) - - msg = NewMsgTransferNFT(addr1, defaultContractID, addr2) - require.Error(t, msg.ValidateBasic()) - } - - { - msg := NewMsgTransferFTFrom(addr1, defaultContractID, addr2, addr2, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.Equal(t, "transfer_ft_from", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgTransferFTFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.Amount, msg2.Amount) - } - - { - msg := NewMsgTransferFTFrom(nil, defaultContractID, addr2, addr2, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgTransferFTFrom(addr1, defaultContractID, nil, addr2, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgTransferFTFrom(addr1, defaultContractID, addr2, nil, NewCoin(defaultTokenIDFT, sdk.NewInt(defaultAmount))) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty").Error()) - - require.Panics(t, func() { - NewMsgTransferFT(addr1, defaultContractID, addr2, NewCoin("1", sdk.NewInt(defaultAmount))) - }, "") - - require.Panics(t, func() { - NewMsgTransferFT(addr1, defaultContractID, addr2, NewCoin("1", sdk.NewInt(-1*defaultAmount))) - }, "") - } - // nolint:dupl - { - msg := NewMsgTransferNFTFrom(addr1, defaultContractID, addr2, addr2, defaultTokenID1) - require.Equal(t, "transfer_nft_from", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgTransferNFTFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenIDs, msg2.TokenIDs) - } - - { - msg := NewMsgTransferNFTFrom(nil, defaultContractID, addr2, addr2, defaultTokenIDFT) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgTransferNFTFrom(addr1, defaultContractID, nil, addr2, defaultTokenIDFT) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgTransferNFTFrom(addr1, defaultContractID, addr2, nil, defaultTokenIDFT) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty").Error()) - - msg = NewMsgTransferNFTFrom(addr1, defaultContractID, addr2, addr2, "1") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "symbol [1] mismatched to [^[a-f0-9]{16}$]").Error()) - - msg = NewMsgTransferNFTFrom(addr1, defaultContractID, addr2, addr2) - require.Error(t, msg.ValidateBasic()) - } - - { - msg := NewMsgAttach(addr1, defaultContractID, defaultTokenID1, defaultTokenID2) - require.Equal(t, "attach", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgAttach{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.ToTokenID, msg2.ToTokenID) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenID, msg2.TokenID) - } - - { - msg := NewMsgAttach(nil, defaultContractID, defaultTokenID1, defaultTokenID2) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgAttach(addr1, "s", defaultTokenID1, defaultTokenID2) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: s").Error()) - - msg = NewMsgAttach(addr1, defaultContractID, "1", defaultTokenID2) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "1").Error()) - - msg = NewMsgAttach(addr1, defaultContractID, defaultTokenID1, "2") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "2").Error()) - - msg = NewMsgAttach(addr1, defaultContractID, defaultTokenID1, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrCannotAttachToItself, "TokenID: %s", defaultTokenID1).Error()) - } - - { - msg := NewMsgDetach(addr1, defaultContractID, defaultTokenID1) - require.Equal(t, "detach", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgDetach{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenID, msg2.TokenID) - } - - { - msg := NewMsgDetach(nil, defaultContractID, "item0001") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgDetach(addr1, "s", "item0001") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: s").Error()) - - msg = NewMsgDetach(addr1, defaultContractID, "1") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "1").Error()) - } - // nolint:dupl - { - msg := NewMsgAttachFrom(addr1, defaultContractID, addr2, defaultTokenID1, defaultTokenID2) - require.Equal(t, "attach_from", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgAttachFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.ToTokenID, msg2.ToTokenID) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenID, msg2.TokenID) - } - - { - msg := NewMsgAttachFrom(nil, defaultContractID, addr2, defaultTokenID1, defaultTokenID2) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgAttachFrom(addr1, defaultContractID, nil, defaultTokenID1, defaultTokenID2) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgAttachFrom(addr1, "s", addr2, defaultTokenID1, defaultTokenID2) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: s").Error()) - - msg = NewMsgAttachFrom(addr1, defaultContractID, addr2, "1", defaultTokenID2) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "1").Error()) - - msg = NewMsgAttachFrom(addr1, defaultContractID, addr2, defaultTokenID1, "2") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "2").Error()) - - msg = NewMsgAttachFrom(addr1, defaultContractID, addr2, defaultTokenID1, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrCannotAttachToItself, "TokenID: %s", defaultTokenID1).Error()) - } - // nolint:dupl - { - msg := NewMsgDetachFrom(addr1, defaultContractID, addr2, defaultTokenID1) - require.Equal(t, "detach_from", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgDetachFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenID, msg2.TokenID) - } - - { - msg := NewMsgDetachFrom(nil, defaultContractID, addr2, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgDetachFrom(addr1, defaultContractID, nil, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgDetachFrom(addr1, "s", addr2, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: s").Error()) - - msg = NewMsgDetachFrom(addr1, defaultContractID, addr2, "1") - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "1").Error()) - } - - { - msg := NewMsgApprove(addr1, defaultContractID, addr2) - require.Equal(t, "approve_collection", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgApprove{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.Approver, msg2.Approver) - require.Equal(t, msg.ContractID, msg2.ContractID) - } - - { - msg := NewMsgDisapprove(addr1, defaultContractID, addr2) - require.Equal(t, "disapprove_collection", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgDisapprove{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.Approver, msg2.Approver) - require.Equal(t, msg.ContractID, msg2.ContractID) - } - - { - msg := NewMsgBurnFT(addr1, defaultContractID, OneCoin(defaultTokenIDFT)) - require.Equal(t, "burn_ft", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgBurnFT{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.Amount, msg2.Amount) - } - { - msg := NewMsgBurnFT(addr1, defaultContractID, Coin{"vf12e00000000", sdk.NewInt(1)}) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id").Error()) - msg = NewMsgBurnFT(addr1, defaultContractID, Coin{defaultTokenIDFT, sdk.NewInt(-1)}) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidAmount, "-1:0000000100000000").Error()) - } - { - msg := NewMsgBurnFTFrom(addr1, defaultContractID, addr2, OneCoin(defaultTokenIDFT)) - require.Equal(t, "burn_ft_from", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgBurnFTFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.Amount, msg2.Amount) - } - - { - msg := NewMsgBurnFTFrom(addr1, defaultContractID, addr1, OneCoin(defaultTokenIDFT)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", addr1.String()).Error()) - - msg = NewMsgBurnFTFrom(nil, defaultContractID, addr1, OneCoin(defaultTokenIDFT)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgBurnFTFrom(addr1, defaultContractID, nil, OneCoin(defaultTokenIDFT)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgBurnFTFrom(addr1, defaultContractID, addr2, Coin{"vf12e00000000", sdk.NewInt(1)}) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id").Error()) - msg = NewMsgBurnFTFrom(addr1, defaultContractID, addr2, Coin{defaultTokenIDFT, sdk.NewInt(-1)}) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidAmount, "-1:0000000100000000").Error()) - } - - { - msg := NewMsgBurnNFTFrom(addr1, defaultContractID, addr2, defaultTokenID1) - require.Equal(t, "burn_nft_from", msg.Type()) - require.Equal(t, "collection", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgBurnNFTFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.TokenIDs, msg2.TokenIDs) - } - - { - msg := NewMsgBurnNFTFrom(addr1, defaultContractID, addr1, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", addr1.String()).Error()) - - msg = NewMsgBurnNFTFrom(nil, defaultContractID, addr1, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgBurnNFTFrom(addr1, defaultContractID, nil, defaultTokenID1) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgBurnNFTFrom(addr1, defaultContractID, addr1) - require.Error(t, msg.ValidateBasic()) - } -} diff --git a/x/collection/internal/types/msgs_transfer.go b/x/collection/internal/types/msgs_transfer.go deleted file mode 100644 index 2fe27d6c30..0000000000 --- a/x/collection/internal/types/msgs_transfer.go +++ /dev/null @@ -1,287 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgTransferFT)(nil) -var _ contract.Msg = (*MsgTransferNFT)(nil) -var _ contract.Msg = (*MsgTransferFTFrom)(nil) -var _ contract.Msg = (*MsgTransferNFTFrom)(nil) - -var _ json.Marshaler = (*MsgTransferFT)(nil) -var _ json.Unmarshaler = (*MsgTransferFT)(nil) -var _ json.Marshaler = (*MsgTransferNFT)(nil) -var _ json.Unmarshaler = (*MsgTransferNFT)(nil) -var _ json.Marshaler = (*MsgTransferFTFrom)(nil) -var _ json.Unmarshaler = (*MsgTransferFTFrom)(nil) -var _ json.Marshaler = (*MsgTransferNFTFrom)(nil) -var _ json.Unmarshaler = (*MsgTransferNFTFrom)(nil) - -type MsgTransferFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount Coins `json:"amount"` -} - -func NewMsgTransferFT(from sdk.AccAddress, contractID string, to sdk.AccAddress, amount ...Coin) MsgTransferFT { - return MsgTransferFT{ - From: from, - ContractID: contractID, - To: to, - Amount: amount, - } -} - -func (msg MsgTransferFT) MarshalJSON() ([]byte, error) { - type msgAlias MsgTransferFT - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgTransferFT) UnmarshalJSON(data []byte) error { - type msgAlias *MsgTransferFT - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgTransferFT) Route() string { return RouterKey } - -func (MsgTransferFT) Type() string { return "transfer_ft" } - -func (msg MsgTransferFT) GetContractID() string { return msg.ContractID } - -func (msg MsgTransferFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty") - } - - for _, tokenID := range msg.Amount { - if err := ValidateDenom(tokenID.Denom); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, "invalid token id") - } - } - - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(ErrInvalidAmount, "invalid amount") - } - return nil -} - -func (msg MsgTransferFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgTransferFT) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -type MsgTransferNFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - TokenIDs []string `json:"token_ids"` -} - -func NewMsgTransferNFT(from sdk.AccAddress, contractID string, to sdk.AccAddress, tokenIDs ...string) MsgTransferNFT { - return MsgTransferNFT{ - From: from, - ContractID: contractID, - To: to, - TokenIDs: tokenIDs, - } -} - -func (msg MsgTransferNFT) MarshalJSON() ([]byte, error) { - type msgAlias MsgTransferNFT - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgTransferNFT) UnmarshalJSON(data []byte) error { - type msgAlias *MsgTransferNFT - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgTransferNFT) Route() string { return RouterKey } - -func (MsgTransferNFT) Type() string { return "transfer_nft" } - -func (msg MsgTransferNFT) GetContractID() string { return msg.ContractID } - -func (msg MsgTransferNFT) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty") - } - - if len(msg.TokenIDs) == 0 { - return sdkerrors.Wrap(ErrEmptyField, "token_ids cannot be empty") - } - for _, tokenID := range msg.TokenIDs { - if err := ValidateTokenID(tokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, err.Error()) - } - } - - return nil -} - -func (msg MsgTransferNFT) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgTransferNFT) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -type MsgTransferFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - To sdk.AccAddress `json:"to"` - Amount Coins `json:"amount"` -} - -func NewMsgTransferFTFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, to sdk.AccAddress, amount ...Coin) MsgTransferFTFrom { - return MsgTransferFTFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - To: to, - Amount: amount, - } -} - -func (msg MsgTransferFTFrom) MarshalJSON() ([]byte, error) { - type msgAlias MsgTransferFTFrom - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgTransferFTFrom) UnmarshalJSON(data []byte) error { - type msgAlias *MsgTransferFTFrom - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgTransferFTFrom) Route() string { return RouterKey } - -func (MsgTransferFTFrom) Type() string { return "transfer_ft_from" } - -func (msg MsgTransferFTFrom) GetContractID() string { return msg.ContractID } - -func (msg MsgTransferFTFrom) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty") - } - if msg.From.Equals(msg.Proxy) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.From.String()) - } - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(ErrInvalidAmount, "invalid amount") - } - return nil -} - -func (msg MsgTransferFTFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgTransferFTFrom) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Proxy} -} - -type MsgTransferNFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - To sdk.AccAddress `json:"to"` - TokenIDs []string `json:"token_ids"` -} - -func NewMsgTransferNFTFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, to sdk.AccAddress, tokenIDs ...string) MsgTransferNFTFrom { - return MsgTransferNFTFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - To: to, - TokenIDs: tokenIDs, - } -} - -func (msg MsgTransferNFTFrom) MarshalJSON() ([]byte, error) { - type msgAlias MsgTransferNFTFrom - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgTransferNFTFrom) UnmarshalJSON(data []byte) error { - type msgAlias *MsgTransferNFTFrom - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgTransferNFTFrom) Route() string { return RouterKey } - -func (MsgTransferNFTFrom) Type() string { return "transfer_nft_from" } - -func (msg MsgTransferNFTFrom) GetContractID() string { return msg.ContractID } - -func (msg MsgTransferNFTFrom) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty") - } - if msg.From.Equals(msg.Proxy) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.From.String()) - } - - if len(msg.TokenIDs) == 0 { - return sdkerrors.Wrap(ErrEmptyField, "token_ids cannot be empty") - } - for _, tokenID := range msg.TokenIDs { - if err := ValidateTokenID(tokenID); err != nil { - return sdkerrors.Wrap(ErrInvalidTokenID, err.Error()) - } - } - return nil -} - -func (msg MsgTransferNFTFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgTransferNFTFrom) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Proxy} -} diff --git a/x/collection/internal/types/params.go b/x/collection/internal/types/params.go deleted file mode 100644 index da8e5fe0cf..0000000000 --- a/x/collection/internal/types/params.go +++ /dev/null @@ -1,87 +0,0 @@ -package types - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/params/subspace" -) - -const ( - DefaultParamspace = ModuleName - - DefaultMaxComposableDepth uint64 = 20 - DefaultMaxComposableWidth uint64 = 20 -) - -var ( - KeyMaxComposableDepth = []byte("MaxComposableDepth") - KeyMaxComposableWidth = []byte("MaxComposableWidth") -) - -var _ subspace.ParamSet = &Params{} - -type Params struct { - MaxComposableDepth uint64 `json:"max_composable_depth" yaml:"max_composable_depth"` - MaxComposableWidth uint64 `json:"max_composable_width" yaml:"max_composable_width"` -} - -func NewParams(maxComposableDepth, maxComposableWidth uint64) Params { - return Params{ - MaxComposableDepth: maxComposableDepth, - MaxComposableWidth: maxComposableWidth, - } -} - -func (p *Params) ParamSetPairs() subspace.ParamSetPairs { - return subspace.ParamSetPairs{ - params.NewParamSetPair(KeyMaxComposableDepth, &p.MaxComposableDepth, validateMaxComposableDepth), - params.NewParamSetPair(KeyMaxComposableWidth, &p.MaxComposableWidth, validateMaxComposableWidth), - } -} - -func (p Params) Validate() error { - if err := validateMaxComposableDepth(p.MaxComposableDepth); err != nil { - return err - } - - if err := validateMaxComposableWidth(p.MaxComposableWidth); err != nil { - return err - } - - return nil -} - -func validateMaxComposableDepth(i interface{}) error { - v, ok := i.(uint64) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v == 0 { - return fmt.Errorf("invalid max composable depth: %d", v) - } - - return nil -} - -func validateMaxComposableWidth(i interface{}) error { - v, ok := i.(uint64) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v == 0 { - return fmt.Errorf("invalid max composable width: %d", v) - } - - return nil -} - -func ParamKeyTable() subspace.KeyTable { - return subspace.NewKeyTable().RegisterParamSet(&Params{}) -} - -func DefaultParams() Params { - return NewParams(DefaultMaxComposableDepth, DefaultMaxComposableWidth) -} diff --git a/x/collection/internal/types/params_test.go b/x/collection/internal/types/params_test.go deleted file mode 100644 index e73ad2e0dc..0000000000 --- a/x/collection/internal/types/params_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestNewParams(t *testing.T) { - params := NewParams(10, 20) - require.Equal(t, uint64(10), params.MaxComposableDepth) - require.Equal(t, uint64(20), params.MaxComposableWidth) -} - -func TestValidate(t *testing.T) { - require.NoError(t, NewParams(20, 20).Validate()) - require.Error(t, NewParams(0, 20).Validate()) - require.Error(t, NewParams(20, 0).Validate()) -} - -func TestDefaultParams(t *testing.T) { - params := DefaultParams() - require.Equal(t, DefaultMaxComposableDepth, params.MaxComposableDepth) - require.Equal(t, DefaultMaxComposableWidth, params.MaxComposableWidth) -} diff --git a/x/collection/internal/types/perm.go b/x/collection/internal/types/perm.go deleted file mode 100644 index 2710a3a326..0000000000 --- a/x/collection/internal/types/perm.go +++ /dev/null @@ -1,145 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - MintAction = "mint" - BurnAction = "burn" - IssueAction = "issue" - ModifyAction = "modify" -) - -type Permission string - -func NewMintPermission() Permission { - return MintAction -} - -func NewBurnPermission() Permission { - return BurnAction -} - -func NewIssuePermission() Permission { - return IssueAction -} - -func NewModifyPermission() Permission { - return ModifyAction -} - -func (p Permission) Equal(p2 Permission) bool { - return p == p2 -} -func (p Permission) String() string { - return string(p) -} - -func (p Permission) Validate() bool { - if p == MintAction { - return true - } - if p == BurnAction { - return true - } - if p == IssueAction { - return true - } - if p == ModifyAction { - return true - } - return false -} - -type Permissions []Permission - -func NewPermissions(perms ...Permission) Permissions { - pms := Permissions{} - for _, perm := range perms { - pms.AddPermission(perm) - } - return pms -} - -func (pms *Permissions) GetPermissions() []Permission { - return []Permission(*pms) -} - -func (pms *Permissions) RemoveElement(idx int) { - *pms = append((*pms)[:idx], (*pms)[idx+1:]...) -} - -func (pms *Permissions) AddPermission(p Permission) { - for _, pin := range *pms { - if pin.Equal(p) { - return - } - } - *pms = append(*pms, p) -} - -func (pms *Permissions) RemovePermission(p Permission) { - for idx, pin := range *pms { - if pin.Equal(p) { - pms.RemoveElement(idx) - return - } - } -} - -func (pms Permissions) HasPermission(p Permission) bool { - for _, pin := range pms { - if pin.Equal(p) { - return true - } - } - return false -} -func (pms Permissions) String() string { - return fmt.Sprintf("%#v", pms) -} - -type AccountPermissionI interface { - GetAddress() sdk.AccAddress - HasPermission(Permission) bool - AddPermission(Permission) - RemovePermission(Permission) - String() string - GetPermissions() Permissions -} - -type AccountPermission struct { - Address sdk.AccAddress - Permissions Permissions -} - -func NewAccountPermission(addr sdk.AccAddress) AccountPermissionI { - return &AccountPermission{ - Address: addr, - } -} - -func (ap *AccountPermission) String() string { - return fmt.Sprintf("%#v", ap) -} - -func (ap *AccountPermission) GetPermissions() Permissions { - return ap.Permissions.GetPermissions() -} - -func (ap *AccountPermission) GetAddress() sdk.AccAddress { - return ap.Address -} - -func (ap *AccountPermission) HasPermission(p Permission) bool { - return ap.Permissions.HasPermission(p) -} -func (ap *AccountPermission) AddPermission(p Permission) { - ap.Permissions.AddPermission(p) -} -func (ap *AccountPermission) RemovePermission(p Permission) { - ap.Permissions.RemovePermission(p) -} diff --git a/x/collection/internal/types/perm_test.go b/x/collection/internal/types/perm_test.go deleted file mode 100644 index 480bdd70fc..0000000000 --- a/x/collection/internal/types/perm_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestPermission(t *testing.T) { - issuePerm := NewIssuePermission() - mintPerm := NewMintPermission() - burnPerm := NewBurnPermission() - modifyPerm := NewModifyPermission() - - require.True(t, issuePerm.Validate()) - require.True(t, mintPerm.Validate()) - require.True(t, burnPerm.Validate()) - require.True(t, modifyPerm.Validate()) - - require.True(t, mintPerm.Equal(mintPerm)) - require.False(t, mintPerm.Equal(burnPerm)) - require.False(t, mintPerm.Equal(modifyPerm)) - require.False(t, mintPerm.Equal(issuePerm)) -} diff --git a/x/collection/internal/types/querier.go b/x/collection/internal/types/querier.go deleted file mode 100644 index 7de81c6000..0000000000 --- a/x/collection/internal/types/querier.go +++ /dev/null @@ -1,86 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - QuerierRoute = ModuleName - QueryBalances = "balances" - QueryBalance = "balance" - QueryTokens = "tokens" - QueryTokensWithTokenType = "tokensWithTokenType" - QueryTokenTypes = "tokentypes" - QueryPerms = "perms" - QueryCollections = "collections" - QuerySupply = "supply" - QueryMint = "mint" - QueryBurn = "burn" - QueryNFTCount = "nftcount" - QueryNFTMint = "nftmint" - QueryNFTBurn = "nftburn" - QueryParent = "parent" - QueryRoot = "root" - QueryChildren = "children" - QueryIsApproved = "approved" - QueryApprovers = "approver" -) - -type NodeQuerier interface { - QueryWithData(path string, data []byte) ([]byte, int64, error) - WithHeight(height int64) context.CLIContext -} - -type QueryTokenIDParams struct { - TokenID string `json:"token_id"` -} - -func NewQueryTokenIDParams(tokenID string) QueryTokenIDParams { - return QueryTokenIDParams{TokenID: tokenID} -} - -type QueryTokenTypeParams struct { - TokenType string `json:"token_type"` -} - -func NewQueryTokenTypeParams(tokenType string) QueryTokenTypeParams { - return QueryTokenTypeParams{TokenType: tokenType} -} - -type QueryTokenIDAccAddressParams struct { - TokenID string `json:"token_id"` - Addr sdk.AccAddress `json:"addr"` -} - -func NewQueryTokenIDAccAddressParams(tokenID string, addr sdk.AccAddress) QueryTokenIDAccAddressParams { - return QueryTokenIDAccAddressParams{TokenID: tokenID, Addr: addr} -} - -type QueryAccAddressParams struct { - Addr sdk.AccAddress `json:"addr"` -} - -func NewQueryAccAddressParams(addr sdk.AccAddress) QueryAccAddressParams { - return QueryAccAddressParams{Addr: addr} -} - -type QueryIsApprovedParams struct { - Proxy sdk.AccAddress `json:"proxy"` - Approver sdk.AccAddress `json:"approver"` -} - -func NewQueryIsApprovedParams(proxy sdk.AccAddress, approver sdk.AccAddress) QueryIsApprovedParams { - return QueryIsApprovedParams{ - Proxy: proxy, - Approver: approver, - } -} - -type QueryProxyParams struct { - Proxy sdk.AccAddress `json:"proxy"` -} - -func NewQueryApproverParams(proxy sdk.AccAddress) QueryProxyParams { - return QueryProxyParams{Proxy: proxy} -} diff --git a/x/collection/internal/types/supply.go b/x/collection/internal/types/supply.go deleted file mode 100644 index 7caf01eb60..0000000000 --- a/x/collection/internal/types/supply.go +++ /dev/null @@ -1,108 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" -) - -type Supply interface { - GetContractID() string - GetTotalSupply() Coins - SetTotalSupply(total Coins) Supply - GetTotalMint() Coins - GetTotalBurn() Coins - - Inflate(amount Coins) Supply - Deflate(amount Coins) Supply - - String() string - ValidateBasic() error -} - -var _ Supply = (*BaseSupply)(nil) - -type BaseSupply struct { - ContractID string `json:"contract_id"` - TotalSupply Coins `json:"total_supply"` - TotalMint Coins `json:"total_mint"` - TotalBurn Coins `json:"total_burn"` -} - -func (supply BaseSupply) GetContractID() string { - return supply.ContractID -} - -func (supply BaseSupply) SetTotalSupply(total Coins) Supply { - supply.TotalSupply = total - supply.TotalMint = total - supply.TotalBurn = NewCoins() - return supply -} - -func (supply BaseSupply) GetTotalSupply() Coins { - return supply.TotalSupply -} - -func (supply BaseSupply) GetTotalMint() Coins { - return supply.TotalMint -} - -func (supply BaseSupply) GetTotalBurn() Coins { - return supply.TotalBurn -} - -func NewSupply(contractID string, total Coins) Supply { - return BaseSupply{ContractID: contractID, TotalSupply: total, TotalMint: total, TotalBurn: NewCoins()} -} - -func DefaultSupply(contractID string) Supply { - return NewSupply(contractID, NewCoins()) -} - -func (supply BaseSupply) Inflate(amount Coins) Supply { - supply.TotalSupply = supply.TotalSupply.Add(amount...) - supply.TotalMint = supply.TotalMint.Add(amount...) - supply.checkInvariant() - return supply -} - -func (supply BaseSupply) Deflate(amount Coins) Supply { - supply.TotalSupply = supply.TotalSupply.Sub(amount) - supply.TotalBurn = supply.TotalBurn.Add(amount...) - supply.checkInvariant() - return supply -} - -func (supply BaseSupply) String() string { - b, err := json.Marshal(supply) - if err != nil { - panic(err) - } - return string(b) -} - -func (supply BaseSupply) ValidateBasic() error { - if !supply.TotalSupply.IsValid() { - return fmt.Errorf("invalid total supply: %s", supply.TotalSupply.String()) - } - if !supply.TotalMint.IsValid() { - return fmt.Errorf("invalid total mint: %s", supply.TotalMint.String()) - } - if !supply.TotalBurn.IsValid() { - return fmt.Errorf("invalid total burn: %s", supply.TotalBurn.String()) - } - return nil -} - -// panic if totalSupply != totalMint - totalBurn -func (supply BaseSupply) checkInvariant() { - if !supply.TotalSupply.IsEqual(supply.TotalMint.Sub(supply.TotalBurn)) { - panic(fmt.Sprintf( - "Collection [%v]'s total supply [%v] does not match with total mint [%v] - total burn [%v]", - supply.GetContractID(), - supply.TotalSupply, - supply.TotalMint, - supply.TotalBurn, - )) - } -} diff --git a/x/collection/internal/types/supply_test.go b/x/collection/internal/types/supply_test.go deleted file mode 100644 index 749566adbc..0000000000 --- a/x/collection/internal/types/supply_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/stretchr/testify/require" -) - -func TestSupply(t *testing.T) { - var supply Supply - supply = DefaultSupply(defaultTokenIDFT) - - // create default - require.Equal(t, defaultTokenIDFT, supply.GetContractID()) - require.Equal(t, NewCoins(), supply.GetTotalSupply()) - require.Equal(t, NewCoins(), supply.GetTotalMint()) - require.Equal(t, NewCoins(), supply.GetTotalBurn()) - - // set total supply - initialSupply := NewCoins(NewCoin(defaultTokenIDFT, sdk.NewInt(3))) - supply = supply.SetTotalSupply(initialSupply) - require.Equal(t, initialSupply, supply.GetTotalSupply()) - require.Equal(t, initialSupply, supply.GetTotalMint()) - require.Equal(t, NewCoins(), supply.GetTotalBurn()) - - // inflate - toInflate := NewCoins(NewCoin(defaultTokenIDFT, sdk.NewInt(2))) - supply = supply.Inflate(toInflate) - require.Equal(t, initialSupply.Add(toInflate...), supply.GetTotalSupply()) - require.Equal(t, initialSupply.Add(toInflate...), supply.GetTotalMint()) - require.Equal(t, NewCoins(), supply.GetTotalBurn()) - - // deflate - toDeflate := NewCoins(NewCoin(defaultTokenIDFT, sdk.NewInt(4))) - supply = supply.Deflate(toDeflate) - require.Equal(t, initialSupply.Add(toInflate...).Sub(toDeflate), supply.GetTotalSupply()) - require.Equal(t, initialSupply.Add(toInflate...), supply.GetTotalMint()) - require.Equal(t, toDeflate, supply.GetTotalBurn()) - - // total - ts, err1 := json.Marshal(NewCoins(NewCoin(defaultTokenIDFT, sdk.NewInt(1)))) - require.NoError(t, err1) - tm, err2 := json.Marshal(NewCoins(NewCoin(defaultTokenIDFT, sdk.NewInt(5)))) - require.NoError(t, err2) - tb, err3 := json.Marshal(NewCoins(NewCoin(defaultTokenIDFT, sdk.NewInt(4)))) - require.NoError(t, err3) - expected := fmt.Sprintf( - `{"contract_id":"%s","total_supply":%v,"total_mint":%v,"total_burn":%v}`, - defaultTokenIDFT, - string(ts), - string(tm), - string(tb), - ) - require.Equal(t, expected, supply.String()) -} - -func TestSupplyMarshalYAML(t *testing.T) { - supply := DefaultSupply(defaultContractID) - coins := NewCoins(NewCoin(defaultTokenIDFT, sdk.OneInt())) - supply = supply.Inflate(coins) - - bzCoins, err := json.Marshal(coins) - require.NoError(t, err) - - expected := fmt.Sprintf( - `{"contract_id":"%s","total_supply":%s,"total_mint":%s,"total_burn":%s}`, - defaultContractID, - string(bzCoins), - string(bzCoins), - []Coin{}, - ) - - require.Equal(t, expected, supply.String()) -} diff --git a/x/collection/internal/types/symbol.go b/x/collection/internal/types/symbol.go deleted file mode 100644 index fadd1edd88..0000000000 --- a/x/collection/internal/types/symbol.go +++ /dev/null @@ -1,40 +0,0 @@ -package types - -import ( - "fmt" - "regexp" -) - -const ( - /* #nosec */ - reTokenIDString = `[a-f0-9]{16}` - /* #nosec */ - reTokenTypeString = `[a-f0-9]{8}` - /* #nosec */ - reTokenTypeFTString = `0[a-f0-9]{7}` - /* #nosec */ - reTokenTypeNFTString = `[a-f1-9][a-f0-9]{7}` - /* #nosec */ - reTokenIndexString = `[a-f0-9]{8}` -) - -var ( - reTokenID = regexp.MustCompile(fmt.Sprintf(`^%s$`, reTokenIDString)) - reTokenType = regexp.MustCompile(fmt.Sprintf(`^%s$`, reTokenTypeString)) - reTokenTypeFT = regexp.MustCompile(fmt.Sprintf(`^%s$`, reTokenTypeFTString)) - reTokenTypeNFT = regexp.MustCompile(fmt.Sprintf(`^%s$`, reTokenTypeNFTString)) - reTokenIndex = regexp.MustCompile(fmt.Sprintf(`^%s$`, reTokenIndexString)) -) - -func ValidateReg(symbol string, reg *regexp.Regexp) error { - if !reg.MatchString(symbol) { - return fmt.Errorf("symbol [%s] mismatched to [%s]", symbol, reg.String()) - } - return nil -} - -func ValidateTokenID(tokenID string) error { return ValidateReg(tokenID, reTokenID) } -func ValidateTokenType(tokenType string) error { return ValidateReg(tokenType, reTokenType) } -func ValidateTokenTypeFT(tokenType string) error { return ValidateReg(tokenType, reTokenTypeFT) } -func ValidateTokenTypeNFT(tokenType string) error { return ValidateReg(tokenType, reTokenTypeNFT) } -func ValidateTokenIndex(index string) error { return ValidateReg(index, reTokenIndex) } diff --git a/x/collection/internal/types/token.go b/x/collection/internal/types/token.go deleted file mode 100644 index 10041dabc6..0000000000 --- a/x/collection/internal/types/token.go +++ /dev/null @@ -1,128 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Token interface { - GetName() string - SetName(name string) - GetContractID() string - GetTokenID() string - GetTokenType() string - GetTokenIndex() string - String() string - GetMeta() string - SetMeta(meta string) -} - -type FT interface { - Token - GetMintable() bool - GetDecimals() sdk.Int -} - -type NFT interface { - Token - GetOwner() sdk.AccAddress - SetOwner(sdk.AccAddress) -} - -var _ Token = (*BaseNFT)(nil) - -type BaseNFT struct { - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` - Owner sdk.AccAddress `json:"owner"` - Name string `json:"name"` - Meta string `json:"meta"` -} - -func NewNFT(contractID, tokenID, name, meta string, owner sdk.AccAddress) NFT { - return &BaseNFT{ - ContractID: contractID, - TokenID: tokenID, - Owner: owner, - Name: name, - Meta: meta, - } -} -func (t BaseNFT) GetName() string { return t.Name } -func (t BaseNFT) GetContractID() string { return t.ContractID } -func (t BaseNFT) GetOwner() sdk.AccAddress { return t.Owner } -func (t BaseNFT) GetTokenID() string { return t.TokenID } -func (t BaseNFT) GetTokenType() string { return t.TokenID[:TokenTypeLength] } -func (t BaseNFT) GetTokenIndex() string { return t.TokenID[TokenTypeLength:] } -func (t *BaseNFT) SetName(name string) { - t.Name = name -} -func (t *BaseNFT) SetOwner(owner sdk.AccAddress) { - t.Owner = owner -} -func (t BaseNFT) String() string { - b, err := json.Marshal(t) - if err != nil { - panic(err) - } - return string(b) -} -func (t BaseNFT) GetMeta() string { return t.Meta } -func (t *BaseNFT) SetMeta(meta string) { - t.Meta = meta -} - -var _ Token = (*BaseFT)(nil) -var _ FT = (*BaseFT)(nil) - -type BaseFT struct { - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` - Decimals sdk.Int `json:"decimals"` - Mintable bool `json:"mintable"` - Name string `json:"name"` - Meta string `json:"meta"` -} - -func NewFT(contractID, tokenID, name, meta string, decimals sdk.Int, mintable bool) FT { - return &BaseFT{ - ContractID: contractID, - TokenID: tokenID, - Decimals: decimals, - Mintable: mintable, - Name: name, - Meta: meta, - } -} -func (t BaseFT) GetName() string { return t.Name } -func (t BaseFT) GetContractID() string { return t.ContractID } -func (t BaseFT) GetMintable() bool { return t.Mintable } -func (t BaseFT) GetDecimals() sdk.Int { return t.Decimals } -func (t BaseFT) GetTokenID() string { return t.TokenID } -func (t BaseFT) GetTokenType() string { return t.TokenID[:TokenTypeLength] } -func (t BaseFT) GetTokenIndex() string { return t.TokenID[TokenTypeLength:] } -func (t *BaseFT) SetName(name string) { - t.Name = name -} -func (t BaseFT) String() string { - b, err := json.Marshal(t) - if err != nil { - panic(err) - } - return string(b) -} -func (t BaseFT) GetMeta() string { return t.Meta } -func (t *BaseFT) SetMeta(meta string) { - t.Meta = meta -} - -type Tokens []Token - -func (ts Tokens) String() string { - b, err := json.Marshal(ts) - if err != nil { - panic(err) - } - return string(b) -} diff --git a/x/collection/internal/types/token_test.go b/x/collection/internal/types/token_test.go deleted file mode 100644 index 2677317b31..0000000000 --- a/x/collection/internal/types/token_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestUnmarshalFT(t *testing.T) { - // Given a FT - token := NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true) - var token2 BaseFT - - // When marshal and unmarshal the FT - bz, err := ModuleCdc.MarshalJSON(token) - require.NoError(t, err) - err = ModuleCdc.UnmarshalJSON(bz, &token2) - require.NoError(t, err) - - // Then the properties are same - r := require.New(t) - r.EqualValues(defaultName, token.GetName(), token2.GetName()) - r.Equal(defaultContractID, token.GetContractID(), token2.GetContractID()) - r.Equal(defaultTokenIDFT, token.GetTokenID(), token2.GetTokenID()) - r.Equal(defaultTokenIDFT[:TokenTypeLength], token.GetTokenType(), token2.GetTokenType()) - r.Equal(defaultTokenIDFT[TokenTypeLength:], token.GetTokenIndex(), token2.GetTokenIndex()) - r.Equal(int64(defaultDecimals), token.GetDecimals().Int64(), token2.GetDecimals().Int64()) - r.Equal(true, token.GetMintable(), token2.GetMintable()) - - r.Equal(`{"contract_id":"abcdef01","token_id":"0000000100000000","decimals":"6","mintable":true,"name":"name","meta":"{}"}`, token.String()) -} - -func TestUnmarshalNFT(t *testing.T) { - // Given a NFT - token := NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1) - var token2 BaseNFT - - // When marshal and unmarshal the FT - bz, err := ModuleCdc.MarshalJSON(token) - require.NoError(t, err) - err = ModuleCdc.UnmarshalJSON(bz, &token2) - require.NoError(t, err) - - // Then the properties are same - r := require.New(t) - r.Equal(defaultName, token.GetName(), token2.GetName()) - r.Equal(defaultContractID, token.GetContractID(), token2.GetContractID()) - r.Equal(defaultTokenID1, token.GetTokenID(), token2.GetTokenID()) - r.Equal(defaultTokenID1[:TokenTypeLength], token.GetTokenType(), token2.GetTokenType()) - r.Equal(defaultTokenID1[TokenTypeLength:], token.GetTokenIndex(), token2.GetTokenIndex()) - r.Equal(addr1, token.GetOwner(), token2.GetOwner()) -} - -func TestSetName(t *testing.T) { - // Given a FT, NFT - tokenFT := NewFT(defaultContractID, defaultTokenIDFT, defaultName, defaultMeta, sdk.NewInt(defaultDecimals), true) - tokenNFT := NewNFT(defaultContractID, defaultTokenID1, defaultName, defaultMeta, addr1) - - tokenFT.SetName("new_name") - tokenNFT.SetName("new_name") - tokenFT.SetMeta("new_meta") - tokenNFT.SetMeta("new_meta") - - // When change name, Then they are changed - require.Equal(t, "new_name", tokenFT.GetName()) - require.Equal(t, "new_name", tokenNFT.GetName()) - require.Equal(t, "new_meta", tokenFT.GetMeta()) - require.Equal(t, "new_meta", tokenNFT.GetMeta()) - - // Set empty name - tokenFT.SetName("") - tokenNFT.SetName("") - - require.Equal(t, "", tokenFT.GetName()) - require.Equal(t, "", tokenNFT.GetName()) -} diff --git a/x/collection/internal/types/token_type.go b/x/collection/internal/types/token_type.go deleted file mode 100644 index d51da1b48f..0000000000 --- a/x/collection/internal/types/token_type.go +++ /dev/null @@ -1,69 +0,0 @@ -package types - -import ( - "encoding/json" -) - -const ( - TokenTypeLength = 8 - SmallestAlphanum = "0" - FungibleFlag = SmallestAlphanum - ReservedEmpty = "00000000" - SmallestFTType = "00000001" - ReservedEmptyNFT = "10000000" - SmallestNFTType = "10000001" - SmallestTokenIndex = "00000001" -) - -type TokenType interface { - GetName() string - SetName(string) - GetMeta() string - SetMeta(string) - GetContractID() string - GetTokenType() string - String() string -} - -type BaseTokenType struct { - ContractID string `json:"contract_id"` - TokenType string `json:"token_type"` - Name string `json:"name"` - Meta string `json:"meta"` -} - -func NewBaseTokenType(contractID, tokenType, name, meta string) TokenType { - return &BaseTokenType{ - ContractID: contractID, - TokenType: tokenType, - Name: name, - Meta: meta, - } -} -func (t BaseTokenType) GetName() string { return t.Name } -func (t *BaseTokenType) SetName(name string) { - t.Name = name -} -func (t BaseTokenType) GetContractID() string { return t.ContractID } -func (t BaseTokenType) GetTokenType() string { return t.TokenType } -func (t BaseTokenType) String() string { - b, err := json.Marshal(t) - if err != nil { - panic(err) - } - return string(b) -} -func (t BaseTokenType) GetMeta() string { return t.Meta } -func (t *BaseTokenType) SetMeta(meta string) { - t.Meta = meta -} - -type TokenTypes []TokenType - -func (ts TokenTypes) String() string { - b, err := json.Marshal(ts) - if err != nil { - panic(err) - } - return string(b) -} diff --git a/x/collection/internal/types/token_type_test.go b/x/collection/internal/types/token_type_test.go deleted file mode 100644 index 006e2fe09c..0000000000 --- a/x/collection/internal/types/token_type_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestTokenType(t *testing.T) { - tokenType := NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - - require.Equal(t, `{"contract_id":"abcdef01","token_type":"10000001","name":"name","meta":"{}"}`, tokenType.String()) - - var tokenType2 TokenType - bz, err := ModuleCdc.MarshalJSON(tokenType) - require.NoError(t, err) - err = ModuleCdc.UnmarshalJSON(bz, &tokenType2) - require.NoError(t, err) - - require.Equal(t, defaultName, tokenType2.GetName()) - require.Equal(t, defaultContractID, tokenType2.GetContractID()) - require.Equal(t, defaultTokenType, tokenType2.GetTokenType()) - - require.Equal(t, tokenType.GetName(), tokenType2.GetName()) - require.Equal(t, tokenType.GetContractID(), tokenType2.GetContractID()) - require.Equal(t, tokenType.GetTokenType(), tokenType2.GetTokenType()) - - require.Equal(t, `{"contract_id":"abcdef01","token_type":"10000001","name":"name","meta":"{}"}`, tokenType.String()) - - tokenType3 := NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - tokenType3.SetName("testname") - require.Equal(t, defaultName, tokenType.GetName()) - require.Equal(t, "testname", tokenType3.GetName()) - - tokenType4 := NewBaseTokenType(defaultContractID, defaultTokenType, defaultName, defaultMeta) - tokenType4.SetMeta("testmeta") - require.Equal(t, defaultMeta, tokenType.GetMeta()) - require.Equal(t, "testmeta", tokenType4.GetMeta()) -} diff --git a/x/collection/internal/types/validators.go b/x/collection/internal/types/validators.go deleted file mode 100644 index 42dd763106..0000000000 --- a/x/collection/internal/types/validators.go +++ /dev/null @@ -1,133 +0,0 @@ -package types - -import ( - "unicode/utf8" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - MaxBaseImgURILength = 1000 - MaxTokenNameLength = 20 - MaxChangeFieldsCount = 100 - MaxTokenMetaLength = 1000 -) - -var ( - CollectionModifiableFields = ModifiableFields{ - AttributeKeyName: true, - AttributeKeyBaseImgURI: true, - AttributeKeyMeta: true, - } - TokenTypeModifiableFields = ModifiableFields{ - AttributeKeyName: true, - AttributeKeyMeta: true, - } - TokenModifiableFields = ModifiableFields{ - AttributeKeyName: true, - AttributeKeyMeta: true, - } -) - -type ModifiableFields map[string]bool - -func ValidateName(name string) bool { - return utf8.RuneCountInString(name) <= MaxTokenNameLength -} - -func ValidateBaseImgURI(baseImgURI string) bool { - return utf8.RuneCountInString(baseImgURI) <= MaxBaseImgURILength -} -func ValidateMeta(meta string) bool { - return utf8.RuneCountInString(meta) <= MaxTokenMetaLength -} - -type ChangesValidator struct { - modifiableFields ModifiableFields - handlers map[string]func(value string) error -} - -func NewChangesValidator() *ChangesValidator { - hs := make(map[string]func(value string) error) - hs[AttributeKeyName] = func(value string) error { - if !ValidateName(value) { - return sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", value, MaxTokenNameLength, utf8.RuneCountInString(value)) - } - return nil - } - hs[AttributeKeyBaseImgURI] = func(value string) error { - if !ValidateBaseImgURI(value) { - return sdkerrors.Wrapf(ErrInvalidBaseImgURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", value, MaxBaseImgURILength, utf8.RuneCountInString(value)) - } - return nil - } - hs[AttributeKeyMeta] = func(value string) error { - if !ValidateMeta(value) { - return sdkerrors.Wrapf(ErrInvalidMetaLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", value, MaxTokenMetaLength, utf8.RuneCountInString(value)) - } - return nil - } - return &ChangesValidator{ - handlers: hs, - } -} - -func (c *ChangesValidator) Validate(changes Changes) error { - if len(changes) == 0 { - return ErrEmptyChanges - } - - if len(changes) > MaxChangeFieldsCount { - return sdkerrors.Wrapf(ErrInvalidChangesFieldCount, "You can not change fields more than [%d] at once, current count: [%d]", MaxChangeFieldsCount, len(changes)) - } - - checkedFields := map[string]bool{} - for _, change := range changes { - if !c.modifiableFields[change.Field] { - return sdkerrors.Wrapf(ErrInvalidChangesField, "Field: %s", change.Field) - } - if checkedFields[change.Field] { - return sdkerrors.Wrapf(ErrDuplicateChangesField, "Field: %s", change.Field) - } - - validateHandler, ok := c.handlers[change.Field] - if !ok { - return sdkerrors.Wrapf(ErrInvalidChangesField, "Field: %s", change.Field) - } - - if err := validateHandler(change.Value); err != nil { - return err - } - checkedFields[change.Field] = true - } - return nil -} - -func (c *ChangesValidator) SetMode(tokenType, tokenIndex string) error { - if tokenType != "" { - if tokenIndex == "" { - c.forTokenType() - } else { - c.forToken() - } - } else { - if tokenIndex == "" { - c.forCollection() - } else { - return ErrTokenIndexWithoutType - } - } - return nil -} - -func (c *ChangesValidator) forCollection() { - c.modifiableFields = CollectionModifiableFields -} - -func (c *ChangesValidator) forTokenType() { - c.modifiableFields = TokenTypeModifiableFields -} - -func (c *ChangesValidator) forToken() { - c.modifiableFields = TokenModifiableFields -} diff --git a/x/collection/internal/types/validators_test.go b/x/collection/internal/types/validators_test.go deleted file mode 100644 index 8a3e728189..0000000000 --- a/x/collection/internal/types/validators_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package types - -import ( - "strings" - "testing" - "unicode/utf8" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" -) - -var length1001String = strings.Repeat("Eng글자日本語はスゲ", 91) // 11 * 91 = 1001 - -func TestValidateName(t *testing.T) { - t.Log("Given valid name") - { - var length20String = strings.Repeat("Eng글자日本語はス", 2) // 10 * 2 = 20 - require.True(t, ValidateName(length20String)) - } - t.Log("Given invalid name") - { - var length21String = strings.Repeat("Eng글자日本", 3) // 7 * 3 = 21 - require.False(t, ValidateName(length21String)) - } -} - -func TestValidateBaseImgURI(t *testing.T) { - t.Log("Given valid base_img_uri") - { - var length990String = strings.Repeat("Eng글자日本語はスゲ", 90) // 11 * 90 = 990 - require.True(t, ValidateBaseImgURI(length990String)) - } - t.Log("Given invalid base_img_uri") - { - require.False(t, ValidateBaseImgURI(length1001String)) - } -} - -func TestValidateChangesForCollection(t *testing.T) { - // Given ChangesValidator for collection - validator := NewChangesValidator() - err := validator.SetMode("", "") - require.NoError(t, err) - - t.Log("Test with valid changes") - { - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - "base_img_uri": "new_base_uri", - }) - - require.Nil(t, validator.Validate(changes)) - } - t.Log("Test with empty changes") - { - changes := Changes{} - require.EqualError(t, validator.Validate(changes), ErrEmptyChanges.Error()) - } - t.Log("Test with base_img_uri too long") - { - length1001String := strings.Repeat("Eng글자日本語はスゲ", 91) // 11 * 91 = 1001 - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - "base_img_uri": length1001String, - }) - - require.EqualError( - t, - validator.Validate(changes), - sdkerrors.Wrapf(ErrInvalidBaseImgURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxBaseImgURILength, utf8.RuneCountInString(length1001String)).Error(), - ) - } - t.Log("Test with invalid changes field") - { - // Given changes with invalid fields - changes := NewChanges( - NewChange("invalid_field", "value"), - ) - - // Then error is occurred - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrapf(ErrInvalidChangesField, "Field: invalid_field").Error()) - } - t.Log("Test with changes more than max") - { - // Given changes more than max - changeList := make([]Change, MaxChangeFieldsCount+1) - changes := Changes(changeList) - - // Then error is occurred - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrapf(ErrInvalidChangesFieldCount, "You can not change fields more than [%d] at once, current count: [%d]", MaxChangeFieldsCount, len(changeList)).Error()) - } - t.Log("Test with duplicate fields") - { - // Given changes with duplicate fields - changes := NewChanges( - NewChange("name", "value"), - NewChange("name", "value2"), - ) - - // Then error is occurred - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrapf(ErrDuplicateChangesField, "Field: name").Error()) - } -} - -func TestValidateChangesForTokenType(t *testing.T) { - // Given ChangesValidator for token type - validator := NewChangesValidator() - err := validator.SetMode(defaultTokenType, "") - require.NoError(t, err) - - t.Log("Test with valid changes") - { - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - }) - - require.Nil(t, validator.Validate(changes)) - } - t.Log("Test with base_img_uri") - { - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - "base_img_uri": "new_base_uri", - }) - - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrap(ErrInvalidChangesField, "Field: base_img_uri").Error()) - } -} - -func TestValidateChangesForToken(t *testing.T) { - // Given ChangesValidator for token - validator := NewChangesValidator() - err := validator.SetMode(defaultTokenType, defaultTokenIndex) - require.NoError(t, err) - - t.Log("Test with valid changes") - { - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - }) - - require.Nil(t, validator.Validate(changes)) - } - t.Log("Test with base_img_uri") - { - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - "base_img_uri": "new_base_uri", - }) - - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrap(ErrInvalidChangesField, "Field: base_img_uri").Error()) - } -} - -func TestValidateChangesForTokenWithoutType(t *testing.T) { - validator := NewChangesValidator() - require.EqualError(t, validator.SetMode("", defaultTokenIndex), ErrTokenIndexWithoutType.Error()) -} diff --git a/x/collection/module.go b/x/collection/module.go deleted file mode 100644 index 77903edaf2..0000000000 --- a/x/collection/module.go +++ /dev/null @@ -1,155 +0,0 @@ -package collection - -import ( - "encoding/json" - "math/rand" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/x/upgrade" - "github.com/line/lbm-sdk/v2/x/collection/internal/legacy" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/line/lbm-sdk/v2/x/collection/client/cli" - "github.com/line/lbm-sdk/v2/x/collection/client/rest" - "github.com/line/lbm-sdk/v2/x/collection/internal/handler" - "github.com/line/lbm-sdk/v2/x/collection/internal/keeper" - "github.com/line/lbm-sdk/v2/x/collection/internal/querier" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// app module basics object -type AppModuleBasic struct{} - -// module name -func (AppModuleBasic) Name() string { return ModuleName } - -// register module codec -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } - -// default genesis state -func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) -} - -// module validate genesis -func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := ModuleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - -// register rest routes -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr) -} - -// get the root tx command of this module -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetTxCmd(cdc) -} - -// get the root query command of this module -func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetQueryCmd(cdc) -} - -func (AppModuleBasic) GetUpgradeHandler(version string) upgrade.UpgradeHandler { - return legacy.UpgradeHandler(version) -} - -// ___________________________ -// app module -type AppModule struct { - AppModuleBasic - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// module name -func (AppModule) Name() string { return ModuleName } - -// register invariants -// TODO: should this module need invariants? -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// module message route name -func (AppModule) Route() string { return RouterKey } - -// module handler -func (am AppModule) NewHandler() sdk.Handler { return handler.NewHandler(am.keeper) } - -// module querier route name -func (AppModule) QuerierRoute() string { return RouterKey } - -// module querier -func (am AppModule) NewQuerierHandler() sdk.Querier { - return querier.NewQuerier(am.keeper) -} - -// module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - ModuleCdc.MustUnmarshalJSON(data, &genesisState) - InitGenesis(ctx, am.keeper, genesisState) - return []abci.ValidatorUpdate{} -} - -// module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return ModuleCdc.MustMarshalJSON(gs) -} - -// module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ____________________________________________________________________________ - -// AppModuleSimulation functions - -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simState.GenState[ModuleName] = simState.Cdc.MustMarshalJSON(DefaultGenesisState()) -} - -func (AppModule) ProposalContents(module.SimulationState) []simulation.WeightedProposalContent { - return nil -} - -func (AppModule) RandomizedParams(*rand.Rand) []simulation.ParamChange { - return nil -} - -func (AppModule) RegisterStoreDecoder(sdk.StoreDecoderRegistry) { -} - -func (AppModule) WeightedOperations(module.SimulationState) []simulation.WeightedOperation { - return nil -} diff --git a/x/collection/spec/01_concept.md b/x/collection/spec/01_concept.md deleted file mode 100644 index bee5c528cf..0000000000 --- a/x/collection/spec/01_concept.md +++ /dev/null @@ -1,2 +0,0 @@ -# Concept -TBD diff --git a/x/collection/spec/02_keepers.md b/x/collection/spec/02_keepers.md deleted file mode 100644 index bddc31f1af..0000000000 --- a/x/collection/spec/02_keepers.md +++ /dev/null @@ -1,2 +0,0 @@ -# Keepers -TBD diff --git a/x/collection/spec/03_messages.md b/x/collection/spec/03_messages.md deleted file mode 100644 index 2896b06048..0000000000 --- a/x/collection/spec/03_messages.md +++ /dev/null @@ -1,454 +0,0 @@ -# Messages - -## MsgIssue - -**Issue token messages are to create a new token on Link Chain** -- The new contract id is generated while issuer issues and the issue permission is granted to the issuer -- An issuer who granted issue permission can issue collective tokens -- Mint permission is granted to the token issuer when the token is mintable -- The identifier for the collective token is defined by the concatenation of the contract_id and the token id - -### MsgCreate -```golang -type MsgCreateCollection struct { - Owner sdk.AccAddress `json:"owner"` - Name string `json:"name"` - Meta string `json:"meta"` - BaseImgURI string `json:"base_img_uri"` -} -``` - -### MsgIssueFT -```golang -type MsgIssueFT struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Name string `json:"name"` - Meta string `json:"meta"` - Amount sdk.Int `json:"amount"` - Mintable bool `json:"mintable"` - Decimals sdk.Int `json:"decimals"` -} -``` - - -### MsgIssueNFT -```golang -type MsgIssueNFT struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - Name string `json:"name"` - Meta string `json:"meta"` -} -``` - - -## Mint - -**Mint message is to increase the total supply of the token** -- Signer(From) of this message must have permission -- Minted token is added to the `To` account - -### MsgMintFT - -```golang -type MsgMintFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount Coins `json:"amount"` -} - -type Coin struct { - Denom string `json:"token_id"` - Amount sdk.Int `json:"amount"` -} - -type Coins []Coin -``` - - -### MsgMintNFT -```golang -type MintNFTParam struct { - Name string `json:"name"` - Meta string `json:"meta"` - TokenType string `json:"token_type"` -} - -type MsgMintNFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - MintNFTParams []MintNFTParam `json:"params"` -} -``` - -## Burn -**Burn message is to decrease the total supply of the token** -- Signer(From) of this message must have the amount of the tokens -- Token is subtracted from the `From` account - -### MsgBurnFT - -```golang -type MsgBurnFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Amount Coins `json:"amount"` -} -``` - -### MsgBurnNFT -```golang -type MsgBurnNFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - TokenIDs []string `json:"token_ids"` -} -``` - -### MsgBurnFTFrom - -```golang -type MsgBurnFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - Amount Coins `json:"amount"` -} -``` - -### MsgBurnNFTFrom -```golang -type MsgBurnNFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - TokenIDs []string `json:"token_ids"` -} -``` - -## MsgGrantPermission - -```golang -type MsgGrantPermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Permission Permission `json:"permission"` -} -``` - -**Grant Permission is to give a permission to the `To` account** -- `From` account must has the permission - -## MsgRevokePermission - -```golang -type MsgRevokePermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Permission Permission `json:"permission"` -} -``` - -**Revoke Permission is to dump a permission from the `From` account** -- `From` account must has the permission - - -## MsgTransferFT -```golang -type MsgTransferFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount Coins `json:"amount"` -} -``` - -**TransferFT message is to transfer a collective non-reserved fungible token** -- Signer of this message must have the amount of the tokens -- Token is subtracted from the `From` account -- Token is added to the `To` account - - -## MsgTransferNFT - -```golang -type MsgTransferNFT struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - TokenIDs []string `json:"token_ids"` -} -``` - -**TransferNFT message is to transfer a collective non-fungible token** -- Signer of this message must have the token -- Token is subtracted from the `From` account -- Token is added to the `To` account - - -## MsgTransferFTFrom - -```golang -type MsgTransferFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - To sdk.AccAddress `json:"to"` - Amount Coins `json:"amount"` -} -``` - -**TransferFTFrom message is for `Proxy` to transfer a collective non-reserved fungible token owned by `From`** -- Signer(`Proxy`) of this message must have been approved for the collection -- Token is subtracted from the `From` account -- Token is added to the `To` account - - -## MsgTransferNFTFrom - -```golang -type MsgTransferNFTFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - To sdk.AccAddress `json:"to"` - TokenIDs []string `json:"token_ids"` -} -``` - -**TransferNFT message is for `Proxy` to transfer a collective non-fungible token owned by `From`** -- Signer(`Proxy`) of this message must have been approved for the collection -- Token is subtracted from the `From` account -- Token is added to the `To` account - - -## MsgAttach - -```golang -type MsgAttach struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - ToTokenID string `json:"to_token_id"` - TokenID string `json:"token_id"` -} -``` - -**Attach message is to attach a non-fungible token to another non-fungible token** -- Signer(`From`) of this message must have the token -- The token having `TokenID` is attached to the token having `ToTokenID` -- If the owner of the `ToToken` is different with `From`, the owner of the Token is changed to the owner of `ToToken` -- Cannot attach a child token of some other to any token - - -## MsgDetach - -```golang -type MsgDetach struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - TokenID string `json:"token_id"` -} -``` - -**Detach message is to detach a non-fungible token from another parent token** -- Signer of this message must have the token -- Cannot detach a non-child token from any token - - -## MsgAttachFrom - -```golang -type MsgAttachFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - ToTokenID string `json:"to_token_id"` - TokenID string `json:"token_id"` -} -``` - -**Attach message is for a proxy to attach a non-fungible token to another non-fungible token** -- Signer(Proxy) of this message must have been approved by From having the token -- The token having TokenID is attached to the token having ToTokenID -- If the owner of the ToToken is different with From, the owner of the Token is changed to the owner of ToToken -- Cannot attach a child token of some other to any token - - -## MsgDetachFrom - -```golang -type MsgDetachFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - TokenID string `json:"token_id"` -} -``` - -**Detach message is for a proxy to detach a non-fungible token from another parent token** -- Signer(`Proxy`) of this message must have been approved by From having the token -- Cannot detach a non-child token from any token - - -## MsgApprove - -```golang -type MsgApprove struct { - Approver sdk.AccAddress `json:"approver"` - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` -} -``` - -**Approve message is to approve a proxy to transfer, attach/detach tokens of a collection** -- `Approver` is the signer - - -## MsgDisapprove - -```golang -type MsgDisapprove struct { - Approver sdk.AccAddress `json:"approver"` - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` -} -``` - -**Disapprove message is to withdraw proxy's approval for a collection** -- `Approver` is the signer - -## MsgModify - -```golang -type MsgModify struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - TokenType string `json:"token_type"` - TokenIndex string `json:"token_index"` - Changes linktype.Changes `json:"changes"` -} -``` - -**Modify message is to modify fields of collection, token type, CFT or CNFT** -- `Owner` is the signer - -# Syntax -| Message/Attributes | Tag | Type | -| ---- | ---- | ---- | -| Message | collection/MsgCreate | github.com/line/link/x/collection/internal/types.MsgCreateCollection | - | Attributes | owner | []uint8 | - | Attributes | name | string | - | Attributes | meta | string | - | Attributes | base_img_uri | string | -| Message | collection/MsgIssueFT | github.com/line/link/x/collection/internal/types.MsgIssueFT | - | Attributes | owner | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | name | string | - | Attributes | meta | string | - | Attributes | amount | github.com/cosmos/cosmos-sdk/types.Int | - | Attributes | mintable | bool | - | Attributes | decimals | github.com/cosmos/cosmos-sdk/types.Int | -| Message | collection/MsgIssueNFT | github.com/line/link/x/collection/internal/types.MsgIssueNFT | - | Attributes | owner | []uint8 | - | Attributes | contract_id | string | - | Attributes | name | string | - | Attributes | meta | string | -| Message | collection/MsgMintNFT | github.com/line/link/x/collection/internal/types.MsgMintNFT | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | params | []github.com/line/link/x/collection/internal/types.MintNFTParam | -| Message | collection/MsgBurnNFT | github.com/line/link/x/collection/internal/types.MsgBurnNFT | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | token_ids | []string | -| Message | collection/MsgBurnNFTFrom | github.com/line/link/x/collection/internal/types.MsgBurnNFTFrom | - | Attributes | proxy | []uint8 | - | Attributes | contract_id | string | - | Attributes | from | []uint8 | - | Attributes | token_ids | []string | -| Message | collection/MsgModify | github.com/line/link/x/collection/internal/types.MsgModify | - | Attributes | owner | []uint8 | - | Attributes | contract_id | string | - | Attributes | token_type | string | - | Attributes | token_index | string | - | Attributes | changes | []github.com/line/link/types.Change | -| Message | collection/MsgMintFT | github.com/line/link/x/collection/internal/types.MsgMintFT | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | amount | []github.com/line/link/x/collection/internal/types.Coin | -| Message | collection/MsgBurnFT | github.com/line/link/x/collection/internal/types.MsgBurnFT | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | amount | []github.com/line/link/x/collection/internal/types.Coin | -| Message | collection/MsgBurnFTFrom | github.com/line/link/x/collection/internal/types.MsgBurnFTFrom | - | Attributes | proxy | []uint8 | - | Attributes | contract_id | string | - | Attributes | from | []uint8 | - | Attributes | amount | []github.com/line/link/x/collection/internal/types.Coin | -| Message | collection/MsgGrantPermission | github.com/line/link/x/collection/internal/types.MsgGrantPermission | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | permission | github.com/line/link/x/collection/internal/types.Permission | -| Message | collection/MsgRevokePermission | github.com/line/link/x/collection/internal/types.MsgRevokePermission | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | permission | github.com/line/link/x/collection/internal/types.Permission | -| Message | collection/MsgTransferFT | github.com/line/link/x/collection/internal/types.MsgTransferFT | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | amount | []github.com/line/link/x/collection/internal/types.Coin | -| Message | collection/MsgTransferNFT | github.com/line/link/x/collection/internal/types.MsgTransferNFT | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | token_ids | []string | -| Message | collection/MsgTransferFTFrom | github.com/line/link/x/collection/internal/types.MsgTransferFTFrom | - | Attributes | proxy | []uint8 | - | Attributes | contract_id | string | - | Attributes | from | []uint8 | - | Attributes | to | []uint8 | - | Attributes | amount | []github.com/line/link/x/collection/internal/types.Coin | -| Message | collection/MsgTransferNFTFrom | github.com/line/link/x/collection/internal/types.MsgTransferNFTFrom | - | Attributes | proxy | []uint8 | - | Attributes | contract_id | string | - | Attributes | from | []uint8 | - | Attributes | to | []uint8 | - | Attributes | token_ids | []string | -| Message | collection/MsgAttach | github.com/line/link/x/collection/internal/types.MsgAttach | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to_token_id | string | - | Attributes | token_id | string | -| Message | collection/MsgDetach | github.com/line/link/x/collection/internal/types.MsgDetach | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | token_id | string | -| Message | collection/MsgAttachFrom | github.com/line/link/x/collection/internal/types.MsgAttachFrom | - | Attributes | proxy | []uint8 | - | Attributes | contract_id | string | - | Attributes | from | []uint8 | - | Attributes | to_token_id | string | - | Attributes | token_id | string | -| Message | collection/MsgDetachFrom | github.com/line/link/x/collection/internal/types.MsgDetachFrom | - | Attributes | proxy | []uint8 | - | Attributes | contract_id | string | - | Attributes | from | []uint8 | - | Attributes | token_id | string | -| Message | collection/MsgApprove | github.com/line/link/x/collection/internal/types.MsgApprove | - | Attributes | approver | []uint8 | - | Attributes | contract_id | string | - | Attributes | proxy | []uint8 | -| Message | collection/MsgDisapprove | github.com/line/link/x/collection/internal/types.MsgDisapprove | - | Attributes | approver | []uint8 | - | Attributes | contract_id | string | - | Attributes | proxy | []uint8 | diff --git a/x/collection/spec/04_events.md b/x/collection/spec/04_events.md deleted file mode 100644 index d19ccd2743..0000000000 --- a/x/collection/spec/04_events.md +++ /dev/null @@ -1,275 +0,0 @@ -# Events -**Not fully documented yet** -The token module emits the following events: - - -### MsgCreate -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | collection | -| message | sender | {ownerAddress} | -| message | action | create_collection | -| grant_perm | to | {ownerAddress} | -| grant_perm | contract_id | {symbol} | -| grant_perm | perm | issue | -| grant_perm | perm | mint | -| grant_perm | perm | burn | -| grant_perm | perm | modify | -| create_collection| contract_id | {contractID} | -| create_collection| name | {name} | -| create_collection| owner | {ownerAddress} | - -### MsgIssueFT -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | collection | -| message | sender | {ownerAddress} | -| message | action | issue_ft | -| issue_ft | contract_id | {contractID} | -| issue_ft | name | {name} | -| issue_ft | token_id | {tokenID} | -| issue_ft | owner | {ownerAddress} | -| issue_ft | to | {toAddress} | -| issue_ft | amount | {amount} | -| issue_ft | mintable | {mintable} | -| issue_ft | decimals | {decimals} | - -### MsgMintFT -| Type | Attribute Key | Attribute Value | -|------------------|----------------|------------------------------| -| message | module | collection | -| message | sender | {ownerAddress} | -| message | action | mint_ft | -| mint_ft | contract_id | {contractID} | -| mint_ft | amount | {amount}{contractID}{tokenID}| -| mint_ft | from | {fromAddress} | -| mint_ft | to | {toAddress} | - -### MsgBurnFT -| Type | Attribute Key | Attribute Value | -|------------------|----------------|------------------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | burn_ft | -| burn_ft | contract_id | {contractID} | -| burn_ft | from | {fromAddress} | -| burn_ft | amount | {amount}{contractID}{tokenID}| - -### MsgBurnFTFrom -| Type | Attribute Key | Attribute Value | -|------------------|----------------|------------------------------| -| message | module | collection | -| message | sender | {proxyAddress} | -| message | action | burn_ft | -| burn_ft_from | contract_id | {contractID} | -| burn_ft_from | proxy | {proxyAddress} | -| burn_ft_from | from | {fromAddress} | -| burn_ft_from | amount | {amount}{contractID}{tokenID}| - -### MsgIssueNFT -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | issue_nft | -| issue_nft | contract_id | {contractID} | -| issue_nft | token_type | {tokentype} | - -### MsgMintNFT -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | mint_nft | -| mint_nft | contract_id | {contractID} | -| mint_nft | name | {name} | -| mint_nft | token_id | {tokenID} | -| mint_nft | from | {fromAddress} | -| mint_nft | to | {toAddress} | - -### MsgBurnNFT -| Type | Attribute Key | Attribute Value | -|--------------------|----------------|------------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | burn_nft | -| burn_nft | from | {fromAddress} | -| burn_nft | contract_id | {contractID} | -| burn_nft | token_id | {token_id} | -| operation_burn_nft | token_id | {token_id} | - -### MsgBurnNFTFrom -| Type | Attribute Key | Attribute Value | -|--------------------|----------------|------------------------| -| message | module | collection | -| message | sender | {proxyAddress} | -| message | action | burn_nft _from | -| burn_nft_from | contract_id | {contractID} | -| burn_nft_from | proxy | {proxyAddress} | -| burn_nft_from | from | {fromAddress} | -| burn_nft_from | token_id | {token_id} | -| operation_burn_nft | token_id | {token_id} | - -### MsgGrantPermission -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | grant_permission | -| grant_perm | from | {fromAddress} | -| grant_perm | to | {toAddress} | -| grant_perm | contract_id | {resource} | -| grant_perm | perm | issue/mint/burn/modify | - -### MsgRevokePermission -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | revoke_permission | -| revoke_perm | from | {fromAddress} | -| revoke_perm | contract_id | {resource} | -| revoke_perm | perm | issue/mint/burn/modify | - -### MsgTransferFT -| Type | Attribute Key | Attribute Value | -|------------------|----------------|-------------------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | transfer_ft | -| transfer_ft | contract_id | {contractID} | -| transfer_ft | from | {fromAddress} | -| transfer_ft | to | {toAddress} | -| transfer_ft | amount | {amount}{contractID}{tokenID} | - -### MsgTransferFTFrom -| Type | Attribute Key | Attribute Value | -|-------------------|----------------|-------------------------------| -| message | module | collection | -| message | sender | {proxyAddress} | -| message | action | transfer_ft_from | -| transfer_ft_from | contract_id | {contractID} | -| transfer_ft_from | proxy | {proxyAddress} | -| transfer_ft_from | from | {fromAddress} | -| transfer_ft_from | to | {toAddress} | -| transfer_ft_from | amount | {amount}{contractID}{tokenID} | - -### MsgTransferNFT -| Type | Attribute Key | Attribute Value | -|------------------------|----------------|-----------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | transfer_nft | -| transfer_nft | contract_id | {contractID} | -| transfer_nft | from | {fromAddress} | -| transfer_nft | to | {toAddress} | -| transfer_nft | token_id | {tokenID} | -| operation_transfer_nft | token_id | {tokenID} | - -### MsgTransferNFTFrom -| Type | Attribute Key | Attribute Value | -|------------------------|----------------|-----------------------| -| message | module | collection | -| message | sender | {proxyAddress} | -| message | action | transfer_nft_from | -| transfer_nft_from | contract_id | {contractID} | -| transfer_nft_from | proxy | {proxyAddress} | -| transfer_nft_from | from | {fromAddress} | -| transfer_nft_from | to | {toAddress} | -| transfer_nft_from | token_id | {tokenID} | -| operation_transfer_nft | token_id | {tokenID} | - -### MsgAttach -| Type | Attribute Key | Attribute Value | -|------------------------|-------------------|------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | attach | -| attach | contract_id | {contractID} | -| attach | from | {fromAddress} | -| attach | to_token_id | {toTokenID} | -| attach | token_id | {tokenID} | -| attach | old_root_token_id | {oldRootTokenID} | -| attach | new_root_token_id | {newRootTokenID} | -| operation_root_changed | token_id | {tokenID} | - -### MsgDetach -| Type | Attribute Key | Attribute Value | -|------------------------|-------------------|------------------| -| message | module | collection | -| message | sender | {fromAddress} | -| message | action | detach | -| detach | contract_id | {contractID} | -| detach | from | {fromAddress} | -| detach | from_token_id | {fromTokenID} | -| detach | token_id | {tokenID} | -| detach | old_root_token_id | {oldRootTokenID} | -| detach | new_root_token_id | {newRootTokenID} | -| operation_root_changed | token_id | {tokenID} | - -### MsgAttachFrom -| Type | Attribute Key | Attribute Value | -|------------------------|-------------------|------------------| -| message | module | collection | -| message | sender | {proxyAddress} | -| message | action | attach_from | -| attach_from | contract_id | {contractID} | -| attach_from | proxy | {proxyAddress} | -| attach_from | from | {fromAddress} | -| attach_from | to_token_id | {toTokenID} | -| attach_from | token_id | {tokenID} | -| attach_from | old_root_token_id | {oldRootTokenID} | -| attach_from | new_root_token_id | {newRootTokenID} | -| operation_root_changed | token_id | {tokenID} | - -### MsgDetachFrom -| Type | Attribute Key | Attribute Value | -|------------------------|-------------------|------------------| -| message | module | collection | -| message | sender | {proxyAddress} | -| message | action | detach_from | -| detach_from | contract_id | {contractID} | -| detach_from | proxy | {proxyAddress} | -| detach_from | from | {fromAddress} | -| detach_from | from_token_id | {fromTokenID} | -| detach_from | token_id | {tokenID} | -| detach_from | old_root_token_id | {oldRootTokenID} | -| detach_from | new_root_token_id | {newRootTokenID} | -| operation_root_changed | token_id | {tokenID} | - -### MsgApprove -| Type | Attribute Key | Attribute Value | -|--------------------|----------------|------------------------| -| message | module | collection | -| message | sender | {approverAddress} | -| message | action | approve_collection | -| approve_collection | contract_id | {contractID} | -| approve_collection | approver | {approverAddress} | -| approve_collection | proxy | {proxyAddress} | - -### MsgDisapprove -| Type | Attribute Key | Attribute Value | -|-----------------------|----------------|-----------------------| -| message | module | collection | -| message | sender | {approverAddress} | -| message | action | disapprove_collection | -| disapprove_collection | contract_id | {contractID} | -| disapprove_collection | approver | {approverAddress} | -| disapprove_collection | proxy | {proxyAddress} | - -### MsgModify -| Type | Attribute Key | Attribute Value | -|-----------------------|----------------|-----------------------| -| message | module | collection | -| message | sender | {ownerAddress} | -| message | action | modify_collection | -| message | action | modify_token_type | -| message | action | modify_token | -| modify_collection | contract_id | {contract_id} | -| modify_collection | {modifiedField}| {modifiedValue} | -| modify_token_type | contract_id | {contract_id} | -| modify_token_type | token_type | {token_type} | -| modify_token_type | {modifiedField}| {modifiedValue} | -| modify_token | contract_id | {contract_id} | -| modify_token | token_id | {token_id} | -| modify_token | {modifiedField}| {modifiedValue} | diff --git a/x/collection/spec/README.md b/x/collection/spec/README.md deleted file mode 100644 index e0c31c380d..0000000000 --- a/x/collection/spec/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Token module specification - - - -## Abstract - -This document specifies the token module of the Link Network. - -## Contents - -1. **[Concept](01_concept.md)** -2. **[Keepers](02_keepers.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** diff --git a/x/contract/alias.go b/x/contract/alias.go deleted file mode 100644 index 90ba47dbf9..0000000000 --- a/x/contract/alias.go +++ /dev/null @@ -1,24 +0,0 @@ -package contract - -import ( - "github.com/line/lbm-sdk/v2/x/contract/internal/keeper" - "github.com/line/lbm-sdk/v2/x/contract/internal/types" -) - -const ( - ModuleName = types.ModuleName - StoreKey = types.StoreKey - SampleContractID = "abcde012" -) - -type ( - Msg = types.ContractMsg - Keeper = keeper.ContractKeeper - CtxKey = types.CtxKey -) - -var ( - ErrInvalidContractID = types.ErrInvalidContractID - ErrContractNotExist = types.ErrContractNotExist - NewContractKeeper = keeper.NewContractKeeper -) diff --git a/x/contract/internal/keeper/keeper.go b/x/contract/internal/keeper/keeper.go deleted file mode 100644 index 39fc2651a2..0000000000 --- a/x/contract/internal/keeper/keeper.go +++ /dev/null @@ -1,106 +0,0 @@ -package keeper - -import ( - "encoding/binary" - "fmt" - "hash/fnv" - "regexp" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/contract/internal/types" -) - -/*** - -Actual generated contractID values from genesis - -9be17165 -678c146a -3336b76f -fee15a74 -ca8bfd79 -9636a07e -61e14383 -2d8be688 -f936898d -c4e12c92 -... - -*/ - -const ( - IDRegExprString = "[a-f0-9]{8}" -) - -var ( - IDRegExpr = regexp.MustCompile(fmt.Sprintf("^%s$", IDRegExprString)) -) - -type ContractKeeper interface { - NewContractID(ctx sdk.Context) string - HasContractID(ctx sdk.Context, contractID string) bool - DeleteContractID(ctx sdk.Context, contractID string) -} - -func NewContractKeeper(cdc *codec.Codec, storeKey sdk.StoreKey) ContractKeeper { - return BaseContractKeeper{ - storeKey: storeKey, - cdc: cdc, - } -} - -type BaseContractKeeper struct { - storeKey sdk.StoreKey - cdc *codec.Codec -} - -var _ ContractKeeper = (*BaseContractKeeper)(nil) - -func VerifyContractID(contractID string) bool { - return IDRegExpr.MatchString(contractID) -} - -func (k BaseContractKeeper) NewContractID(ctx sdk.Context) string { - store := ctx.KVStore(k.storeKey) - - nextCount := uint64(0) - if store.Has(types.LastContractCountStoreKey()) { - b := store.Get(types.LastContractCountStoreKey()) - k.cdc.MustUnmarshalBinaryBare(b, &nextCount) - nextCount++ - } - var id string - hash := fnv.New32() - for ok := false; !ok; { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, nextCount) - _, err := hash.Write(b) - if err != nil { - panic("hash should not fail") - } - id = fmt.Sprintf("%x", hash.Sum32()) - if len(id) < 8 { - id = "00000000"[len(id):] + id - } - if store.Has(types.ContractIDStoreKey(id)) { - nextCount++ - } else { - ok = true - } - } - - store.Set(types.LastContractCountStoreKey(), k.cdc.MustMarshalBinaryBare(nextCount)) - store.Set(types.ContractIDStoreKey(id), k.cdc.MustMarshalBinaryBare(nextCount)) - return id -} - -func (k BaseContractKeeper) HasContractID(ctx sdk.Context, contractID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.ContractIDStoreKey(contractID)) -} - -func (k BaseContractKeeper) DeleteContractID(ctx sdk.Context, contractID string) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.ContractIDStoreKey(contractID)) -} diff --git a/x/contract/internal/keeper/keeper_test.go b/x/contract/internal/keeper/keeper_test.go deleted file mode 100644 index 3cdd3c9d0c..0000000000 --- a/x/contract/internal/keeper/keeper_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/contract/internal/types" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" -) - -type testInput struct { - cdc *codec.Codec - ctx sdk.Context - keeper ContractKeeper -} - -func newTestCodec() *codec.Codec { - cdc := codec.New() - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - return cdc -} - -func setupTestInput(t *testing.T) testInput { - keyContract := sdk.NewKVStoreKey(types.StoreKey) - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyContract, sdk.StoreTypeIAVL, db) - err := ms.LoadLatestVersion() - require.NoError(t, err) - - cdc := newTestCodec() - - keeper := NewContractKeeper(cdc, keyContract) - ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) - return testInput{cdc: cdc, ctx: ctx, keeper: keeper} -} - -func TestKeeper(t *testing.T) { - testInput := setupTestInput(t) - _, ctx, keeper := testInput.cdc, testInput.ctx, testInput.keeper - for i := 0; i < 10000; i++ { - contractID := keeper.NewContractID(ctx) - require.True(t, VerifyContractID(contractID)) - } -} diff --git a/x/contract/internal/types/errors.go b/x/contract/internal/types/errors.go deleted file mode 100644 index d1aa1dc912..0000000000 --- a/x/contract/internal/types/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package types - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -var ( - ErrInvalidContractID = sdkerrors.Register(ModuleName, 1, "invalid contractID") - ErrContractNotExist = sdkerrors.Register(ModuleName, 2, "contract does not exist") -) diff --git a/x/contract/internal/types/types.go b/x/contract/internal/types/types.go deleted file mode 100644 index 92089cbbf9..0000000000 --- a/x/contract/internal/types/types.go +++ /dev/null @@ -1,31 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - ModuleName = "contract" - - StoreKey = ModuleName -) - -var ( - LastContractCountStoreKeyPrefix = []byte{0x01} - ContractIDStoreKeyPrefix = []byte{0x02} -) - -func LastContractCountStoreKey() []byte { - return LastContractCountStoreKeyPrefix -} - -func ContractIDStoreKey(contractID string) []byte { - return append(ContractIDStoreKeyPrefix, []byte(contractID)...) -} - -type ContractMsg interface { - sdk.Msg - GetContractID() string -} - -type CtxKey struct{} diff --git a/x/contract/validator.go b/x/contract/validator.go deleted file mode 100644 index 5285289660..0000000000 --- a/x/contract/validator.go +++ /dev/null @@ -1,14 +0,0 @@ -package contract - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract/internal/keeper" - "github.com/line/lbm-sdk/v2/x/contract/internal/types" -) - -func ValidateContractIDBasic(contract Msg) error { - if !keeper.VerifyContractID(contract.GetContractID()) { - return sdkerrors.Wrapf(types.ErrInvalidContractID, "ContractID: %s", contract.GetContractID()) - } - return nil -} diff --git a/x/genesis/alias.go b/x/genesis/alias.go deleted file mode 100644 index 66609344c4..0000000000 --- a/x/genesis/alias.go +++ /dev/null @@ -1,21 +0,0 @@ -package genesis - -import ( - "github.com/line/lbm-sdk/v2/x/genesis/internal/keeper" - "github.com/line/lbm-sdk/v2/x/genesis/internal/types" -) - -const ( - ModuleName = types.ModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey -) - -type ( - Keeper = keeper.Keeper -) - -var ( - ModuleCdc = types.ModuleCdc - NewKeeper = keeper.NewKeeper -) diff --git a/x/genesis/genesis.go b/x/genesis/genesis.go deleted file mode 100644 index 4a66c333a0..0000000000 --- a/x/genesis/genesis.go +++ /dev/null @@ -1,28 +0,0 @@ -package genesis - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// nolint:golint -type GenesisState struct { - GenesisMessage string `json:"genesis_message"` -} - -func NewGenesisState(genesisMessage string) GenesisState { - return GenesisState{GenesisMessage: genesisMessage} -} - -func DefaultGenesisState() GenesisState { - return NewGenesisState("In the beginning God created the heavens and the earth.") -} - -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { - keeper.SetGenesisMessage(ctx, data.GenesisMessage) -} - -func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { - return NewGenesisState(keeper.GetGenesisMessage(ctx)) -} - -func ValidateGenesis(data GenesisState) error { return nil } diff --git a/x/genesis/internal/keeper/keeper.go b/x/genesis/internal/keeper/keeper.go deleted file mode 100644 index acd962cd4f..0000000000 --- a/x/genesis/internal/keeper/keeper.go +++ /dev/null @@ -1,33 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/genesis/internal/types" -) - -func NewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey) Keeper { - return Keeper{ - storeKey: storeKey, - cdc: cdc, - } -} - -type Keeper struct { - storeKey sdk.StoreKey - cdc *codec.Codec -} - -func (k Keeper) SetGenesisMessage(ctx sdk.Context, genesisMessage string) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GenesisKeyPrefix, []byte(genesisMessage)) -} - -func (k Keeper) GetGenesisMessage(ctx sdk.Context) string { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.GenesisKeyPrefix) - if bz == nil { - return "" - } - return string(bz) -} diff --git a/x/genesis/internal/types/codec.go b/x/genesis/internal/types/codec.go deleted file mode 100644 index 9029d3aed9..0000000000 --- a/x/genesis/internal/types/codec.go +++ /dev/null @@ -1,10 +0,0 @@ -package types - -import "github.com/cosmos/cosmos-sdk/codec" - -var ModuleCdc *codec.Codec - -func init() { - ModuleCdc = codec.New() - ModuleCdc.Seal() -} diff --git a/x/genesis/internal/types/types.go b/x/genesis/internal/types/types.go deleted file mode 100644 index ffde251b0e..0000000000 --- a/x/genesis/internal/types/types.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -const ( - ModuleName = "genesis" - StoreKey = ModuleName - RouterKey = ModuleName -) - -var ( - GenesisKeyPrefix = []byte{0x01} -) diff --git a/x/genesis/module.go b/x/genesis/module.go deleted file mode 100644 index 7bd03009b7..0000000000 --- a/x/genesis/module.go +++ /dev/null @@ -1,111 +0,0 @@ -package genesis - -import ( - "encoding/json" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/line/lbm-sdk/v2/x/genesis/internal/keeper" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// app module basics object -type AppModuleBasic struct{} - -// module name -func (AppModuleBasic) Name() string { return ModuleName } - -// register module codec -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} - -// default genesis state -func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) -} - -// module validate genesis -func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := ModuleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - -// register rest routes -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { -} - -// get the root tx command of this module -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return nil } - -// get the root query command of this module -func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return nil } - -// ___________________________ -// app module -type AppModule struct { - AppModuleBasic - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// module name -func (AppModule) Name() string { return ModuleName } - -// register invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// module message route name -func (AppModule) Route() string { return RouterKey } - -// module handler -func (am AppModule) NewHandler() sdk.Handler { return nil } - -// module querier route name -func (AppModule) QuerierRoute() string { return RouterKey } - -// module querier -func (am AppModule) NewQuerierHandler() sdk.Querier { return nil } - -// module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - ModuleCdc.MustUnmarshalJSON(data, &genesisState) - InitGenesis(ctx, am.keeper, genesisState) - return []abci.ValidatorUpdate{} -} - -// module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return ModuleCdc.MustMarshalJSON(gs) -} - -// module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/token/alias.go b/x/token/alias.go deleted file mode 100644 index 32dd5aa0aa..0000000000 --- a/x/token/alias.go +++ /dev/null @@ -1,63 +0,0 @@ -package token - -import ( - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/querier" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -const ( - ModuleName = types.ModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - EncodeRouterKey = types.EncodeRouterKey -) - -type ( - MsgIssue = types.MsgIssue - MsgTransfer = types.MsgTransfer - MsgMint = types.MsgMint - MsgBurn = types.MsgBurn - MsgModify = types.MsgModify - - Account = types.Account - Token = types.Token - Permissions = types.Permissions - Keeper = keeper.Keeper - Permission = types.Permission - - EncodeHandler = types.EncodeHandler - EncodeQuerier = types.EncodeQuerier -) - -var ( - NewMsgIssue = types.NewMsgIssue - NewMsgMint = types.NewMsgMint - NewMsgBurn = types.NewMsgBurn - NewMsgBurnFrom = types.NewMsgBurnFrom - NewMsgTransfer = types.NewMsgTransfer - NewMsgApprove = types.NewMsgApprove - NewMsgTransferFrom = types.NewMsgTransferFrom - NewMsgModify = types.NewMsgModify - NewChangesWithMap = types.NewChangesWithMap - NewMsgGrantPermission = types.NewMsgGrantPermission - NewMsgRevokePermission = types.NewMsgRevokePermission - ModuleCdc = types.ModuleCdc - RegisterCodec = types.RegisterCodec - NewToken = types.NewToken - NewKeeper = keeper.NewKeeper - NewQuerier = querier.NewQuerier - - NewMintPermission = types.NewMintPermission - NewBurnPermission = types.NewBurnPermission - NewModifyPermission = types.NewModifyPermission - - // NewMsgEncodeHandler = keeper.NewMsgEncodeHandler - // NewQueryEncoder = querier.NewQueryEncoder - - NewChanges = types.NewChanges - NewChange = types.NewChange - - ErrTokenNotExist = types.ErrTokenNotExist - ErrInsufficientBalance = types.ErrInsufficientBalance -) diff --git a/x/token/client/cli/query.go b/x/token/client/cli/query.go deleted file mode 100644 index 7e23659dff..0000000000 --- a/x/token/client/cli/query.go +++ /dev/null @@ -1,197 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/line/lbm-sdk/v2/x/token/client/internal/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/spf13/cobra" -) - -func GetQueryCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the token module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - cmd.AddCommand( - GetTokenCmd(cdc), - GetBalanceCmd(cdc), - GetTotalCmd(cdc), - GetPermsCmd(cdc), - GetIsApprovedCmd(cdc), - GetApproversCmd(cdc), - ) - - return cmd -} - -func GetTokenCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "token [contract_id]", - Short: "Query token with its contract_id", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - token, height, err := retriever.GetToken(cliCtx, contractID) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - - return cliCtx.PrintOutput(token) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetBalanceCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "balance [contract_id] [addr]", - Short: "Query balance of the account", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - addr, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - supply, height, err := retriever.GetAccountBalance(cliCtx, contractID, addr) - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(supply) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetTotalCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "total [supply|mint|burn] [contract_id] ", - Short: "Query total supply/mint/burn of token", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - target := args[0] - contractID := args[1] - - supply, height, err := retriever.GetTotal(cliCtx, contractID, target) - - if err != nil { - return err - } - - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(supply) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetPermsCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "perm [addr] [contract_id]", - Short: "Get Permission of the Account", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - contractID := args[1] - pms, height, err := retriever.GetAccountPermission(cliCtx, contractID, addr) - if err != nil { - return err - } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(pms) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetIsApprovedCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "approved [contract_id] [proxy] [approver]", - Short: "Query whether a proxy is approved by approver on a token", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - - proxy, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - approver, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - approved, height, err := retriever.IsApproved(cliCtx, contractID, proxy, approver) - if err != nil { - return err - } - - return cliCtx.WithHeight(height).PrintOutput(approved) - }, - } - - return flags.GetCommands(cmd)[0] -} - -func GetApproversCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "approvers [contract_id] [proxy]", - Short: "Query approvers by the proxy", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - retriever := clienttypes.NewRetriever(cliCtx) - - contractID := args[0] - - proxy, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - approvers, height, err := retriever.GetApprovers(cliCtx, contractID, proxy) - if err != nil { - return err - } - - return cliCtx.WithHeight(height).PrintOutput(approvers) - }, - } - - return flags.GetCommands(cmd)[0] -} diff --git a/x/token/client/cli/tx.go b/x/token/client/cli/tx.go deleted file mode 100644 index 580ff0bde5..0000000000 --- a/x/token/client/cli/tx.go +++ /dev/null @@ -1,364 +0,0 @@ -package cli - -import ( - "bufio" - "errors" - "strconv" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/spf13/viper" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" -) - -var ( - flagTotalSupply = "total-supply" - flagDecimals = "decimals" - flagMintable = "mintable" - flagMeta = "meta" - flagImageURI = "image-uri" -) - -const ( - DefaultDecimals = 8 - DefaultTotalSupply = 1 -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *codec.Codec) *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Token transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - txCmd.AddCommand( - IssueTxCmd(cdc), - TransferTxCmd(cdc), - MintTxCmd(cdc), - BurnTxCmd(cdc), - GrantPermTxCmd(cdc), - RevokePermTxCmd(cdc), - ModifyTokenCmd(cdc), - TransferFromTxCmd(cdc), - ApproveTokenTxCmd(cdc), - BurnFromTxCmd(cdc), - ) - return txCmd -} - -func IssueTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "issue [from_key_or_address] [to] [name] [symbol]", - Short: "Create and sign an issue token tx", - Long: ` -[Issue a token command] -To query or send the token, you should remember the contract id - - -[Fungible Token] -linkcli tx token issue [from_key_or_address] [to] [name] [symbol] ---decimals=[decimals] ---mintable=[mintable] ---total-supply=[initial amount of the token] ---meta=[metadata for the token] ---image-uri=[image uri for the token] -`, - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - from := cliCtx.FromAddress - to, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - name := args[2] - symbol := args[3] - supply := viper.GetInt64(flagTotalSupply) - decimals := viper.GetInt64(flagDecimals) - mintable := viper.GetBool(flagMintable) - meta := viper.GetString(flagMeta) - imageURI := viper.GetString(flagImageURI) - - if decimals < 0 || decimals > 18 { - return errors.New("invalid decimals. 0 <= decimals <= 18") - } - - msg := types.NewMsgIssue(from, to, name, symbol, meta, imageURI, sdk.NewInt(supply), sdk.NewInt(decimals), mintable) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - cmd.Flags().Int64(flagTotalSupply, DefaultTotalSupply, "total supply") - cmd.Flags().Int64(flagDecimals, DefaultDecimals, "set decimals") - cmd.Flags().Bool(flagMintable, false, "set mintable") - cmd.Flags().String(flagMeta, "", "set meta") - cmd.Flags().String(flagImageURI, "", "set img-uri") - - return flags.PostCommands(cmd)[0] -} - -func TransferTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer [from_key_or_address] [to_address] [contract_id] [amount]", - Short: "Create and sign a tx transferring non-reserved fungible tokens", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - to, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - amount, ok := sdk.NewIntFromString(args[3]) - if !ok { - return sdkerrors.Wrap(types.ErrInvalidAmount, args[3]) - } - - msg := types.NewMsgTransfer(cliCtx.GetFromAddress(), to, args[2], amount) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - cmd = flags.PostCommands(cmd)[0] - - return cmd -} - -func MintTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "mint [from_key_or_address] [contract_id] [to] [amount]", - Short: "Create and sign a mint token tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - amount, err := strconv.Atoi(args[3]) - if err != nil { - return err - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgMint(cliCtx.GetFromAddress(), contractID, to, sdk.NewInt(int64(amount))) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func BurnTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "burn [from_key_or_address] [contract_id] [amount]", - Short: "Create and sign a burn token tx", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - amount, ok := sdk.NewIntFromString(args[2]) - if !ok { - return sdkerrors.Wrap(types.ErrInvalidAmount, args[4]) - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgBurn(cliCtx.GetFromAddress(), contractID, amount) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func GrantPermTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "grant [from_key_or_address] [contract_id] [to] [action]", - Short: "Create and sign a grant permission for token tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - to, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - perm := types.Permission(args[3]) - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgGrantPermission(cliCtx.GetFromAddress(), contractID, to, perm) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func RevokePermTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "revoke [from_key_or_address] [contract_id] [action]", - Short: "Create and sign a revoke permission for token tx", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - perm := types.Permission(args[2]) - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgRevokePermission(cliCtx.GetFromAddress(), contractID, perm) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func ModifyTokenCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "modify [owner_address] [contract_id] [field] [new_value]", - Short: "Create and sign a modify token tx", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - contractID := args[1] - field := args[2] - newValue := args[3] - - msg := types.NewMsgModify( - cliCtx.FromAddress, - contractID, - types.NewChanges(types.NewChange(field, newValue)), - ) - err := msg.ValidateBasic() - if err != nil { - return err - } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} - -func TransferFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer-from [proxy_key_or_address] [contract_id] [from_address] [to_address] [amount]", - Short: "Create and sign a tx transferring tokens by approved proxy", - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - to, err := sdk.AccAddressFromBech32(args[3]) - if err != nil { - return err - } - - amount, ok := sdk.NewIntFromString(args[4]) - if !ok { - return sdkerrors.Wrap(types.ErrInvalidAmount, args[4]) - } - - msg := types.NewMsgTransferFrom(cliCtx.GetFromAddress(), contractID, from, to, amount) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - cmd = flags.PostCommands(cmd)[0] - - return cmd -} - -func ApproveTokenTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "approve [approver_key_or_address] [contract_id] [proxy_address]", - Short: "Create and sign a tx approve all token operations of a token to a proxy", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - - contractID := args[1] - - proxy, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgApprove(cliCtx.GetFromAddress(), contractID, proxy) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} -func BurnFromTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "burn-from [proxy_key_or_address] [contract_id] [from_address] [amount]", - Short: "Create and sign a burn token tx by approved proxy", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInputAndFrom(inBuf, args[0]).WithCodec(cdc) - contractID := args[1] - from, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - amount, ok := sdk.NewIntFromString(args[3]) - if !ok { - return errors.New("invalid amount") - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.NewMsgBurnFrom(cliCtx.GetFromAddress(), contractID, from, amount) - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - return flags.PostCommands(cmd)[0] -} diff --git a/x/token/client/internal/types/retriever.go b/x/token/client/internal/types/retriever.go deleted file mode 100644 index 6fa335cf0d..0000000000 --- a/x/token/client/internal/types/retriever.go +++ /dev/null @@ -1,124 +0,0 @@ -package types - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -type Retriever struct { - querier types.NodeQuerier -} - -func NewRetriever(querier types.NodeQuerier) Retriever { - return Retriever{querier: querier} -} - -func (r Retriever) query(path, contractID string, data []byte) ([]byte, int64, error) { - return r.querier.QueryWithData(fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, path, contractID), data) -} - -func (r Retriever) GetAccountPermission(ctx context.CLIContext, contractID string, addr sdk.AccAddress) (types.Permissions, int64, error) { - var pms types.Permissions - bs, err := ctx.Codec.MarshalJSON(types.NewQueryContractIDAccAddressParams(addr)) - if err != nil { - return pms, 0, err - } - - res, height, err := r.query(types.QueryPerms, contractID, bs) - if err != nil { - return pms, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &pms); err != nil { - return pms, height, err - } - - return pms, height, nil -} - -func (r Retriever) GetAccountBalance(ctx context.CLIContext, contractID string, addr sdk.AccAddress) (sdk.Int, int64, error) { - var supply sdk.Int - bs, err := ctx.Codec.MarshalJSON(types.NewQueryContractIDAccAddressParams(addr)) - if err != nil { - return supply, 0, err - } - - res, height, err := r.query(types.QueryBalance, contractID, bs) - if err != nil { - return supply, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &supply); err != nil { - return supply, height, err - } - - return supply, height, nil -} -func (r Retriever) GetTotal(ctx context.CLIContext, contractID string, target string) (sdk.Int, int64, error) { - var total sdk.Int - - res, height, err := r.query(target, contractID, nil) - if err != nil { - return total, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &total); err != nil { - return total, height, err - } - - return total, height, nil -} - -func (r Retriever) GetToken(ctx context.CLIContext, contractID string) (types.Token, int64, error) { - var token types.Token - - res, height, err := r.query(types.QueryTokens, contractID, nil) - if err != nil { - return token, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &token); err != nil { - return token, height, err - } - return token, height, nil -} - -func (r Retriever) IsApproved(ctx context.CLIContext, contractID string, proxy sdk.AccAddress, approver sdk.AccAddress) (approved bool, height int64, err error) { - bs, err := types.ModuleCdc.MarshalJSON(types.NewQueryIsApprovedParams(proxy, approver)) - if err != nil { - return false, 0, err - } - - res, height, err := r.query(types.QueryIsApproved, contractID, bs) - if err != nil { - return false, 0, err - } - - err = ctx.Codec.UnmarshalJSON(res, &approved) - if err != nil { - return false, 0, err - } - - return approved, height, nil -} - -func (r Retriever) GetApprovers(ctx context.CLIContext, contractID string, proxy sdk.AccAddress) (accAdds []sdk.AccAddress, height int64, err error) { - bs, err := ctx.Codec.MarshalJSON(types.NewQueryApproverParams(proxy)) - if err != nil { - return accAdds, 0, err - } - - res, height, err := r.query(types.QueryApprovers, contractID, bs) - if err != nil { - return accAdds, height, err - } - - if err := ctx.Codec.UnmarshalJSON(res, &accAdds); err != nil { - return accAdds, height, err - } - - return accAdds, height, nil -} diff --git a/x/token/client/rest/query.go b/x/token/client/rest/query.go deleted file mode 100644 index 74f0e713d5..0000000000 --- a/x/token/client/rest/query.go +++ /dev/null @@ -1,206 +0,0 @@ -package rest - -import ( - "fmt" - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/line/lbm-sdk/v2/x/token/client/internal/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/types/rest" -) - -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/token/{contract_id}/supply", QueryTotalRequestHandlerFn(cliCtx, types.QuerySupply)).Methods("GET") - r.HandleFunc("/token/{contract_id}/mint", QueryTotalRequestHandlerFn(cliCtx, types.QueryMint)).Methods("GET") - r.HandleFunc("/token/{contract_id}/burn", QueryTotalRequestHandlerFn(cliCtx, types.QueryBurn)).Methods("GET") - r.HandleFunc("/token/{contract_id}/accounts/{address}/balance", QueryBalanceRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/token/{contract_id}/accounts/{address}/permissions", QueryPermRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/token/{contract_id}/token", QueryTokenRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/token/{contract_id}/accounts/{address}/proxies/{approver}", QueryIsApprovedRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/token/{contract_id}/accounts/{address}/approvers", QueryApproversRequestHandlerFn(cliCtx)).Methods("GET") -} - -func QueryTokenRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - token, height, err := retriever.GetToken(cliCtx, contractID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, token) - } -} - -func QueryBalanceRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - addr, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - supply, height, err := retriever.GetAccountBalance(cliCtx, contractID, addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, supply) - } -} - -func QueryTotalRequestHandlerFn(cliCtx context.CLIContext, target string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - total, height, err := retriever.GetTotal(cliCtx, contractID, target) - - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, total) - } -} - -func QueryPermRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - addr, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("address cannot parsed: %s", err)) - return - } - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - pms, height, err := retriever.GetAccountPermission(cliCtx, contractID, addr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, pms) - } -} - -func QueryIsApprovedRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - - proxy, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("proxy[%s] cannot parsed: %s", proxy.String(), err)) - return - } - - approver, err := sdk.AccAddressFromBech32(vars["approver"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("approver[%s] cannot parsed: %s", approver.String(), err)) - return - } - - contractID := vars["contract_id"] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - approved, height, err := retriever.IsApproved(cliCtx, contractID, proxy, approver) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, approved) - } -} - -func QueryApproversRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - contractID := vars["contract_id"] - - proxy, err := sdk.AccAddressFromBech32(vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("proxy[%s] cannot parsed: %s", proxy.String(), err)) - return - } - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - retriever := clienttypes.NewRetriever(cliCtx) - - approvers, height, err := retriever.GetApprovers(cliCtx, contractID, proxy) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - - rest.PostProcessResponse(w, cliCtx, approvers) - } -} diff --git a/x/token/genesis.go b/x/token/genesis.go deleted file mode 100644 index 4c8d2b80a0..0000000000 --- a/x/token/genesis.go +++ /dev/null @@ -1,28 +0,0 @@ -package token - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type GenesisState struct { - Tokens []Token `json:"tokens"` - // TODO: approvals -} - -func NewGenesisState(tokens []Token) GenesisState { - return GenesisState{Tokens: tokens} -} - -func DefaultGenesisState() GenesisState { return NewGenesisState(nil) } - -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { - // TODO: fill it with permission -} - -func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { - return NewGenesisState(keeper.GetAllTokens(ctx)) -} - -func ValidateGenesis(data GenesisState) error { return nil } - -// TODO: validate diff --git a/x/token/internal/handler/handler.go b/x/token/internal/handler/handler.go deleted file mode 100644 index c01c33e8fc..0000000000 --- a/x/token/internal/handler/handler.go +++ /dev/null @@ -1,61 +0,0 @@ -package handler - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func NewHandler(keeper keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - if msg, ok := msg.(contract.Msg); ok { - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, msg.GetContractID())) - err := handleMsgContract(ctx, keeper, msg) - if err != nil { - return nil, err - } - } - if _, ok := msg.(types.MsgIssue); ok { - contractID := keeper.NewContractID(ctx) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, contractID)) - } - if ctx.Context().Value(contract.CtxKey{}) == nil { - panic("contract id does not set") - } - switch msg := msg.(type) { - case types.MsgIssue: - return handleMsgIssue(ctx, keeper, msg) - case types.MsgMint: - return handleMsgMint(ctx, keeper, msg) - case types.MsgBurn: - return handleMsgBurn(ctx, keeper, msg) - case types.MsgBurnFrom: - return handleMsgBurnFrom(ctx, keeper, msg) - case types.MsgTransfer: - return handleMsgTransfer(ctx, keeper, msg) - case types.MsgGrantPermission: - return handleMsgGrant(ctx, keeper, msg) - case types.MsgRevokePermission: - return handleMsgRevoke(ctx, keeper, msg) - case types.MsgModify: - return handleMsgModify(ctx, keeper, msg) - case types.MsgTransferFrom: - return handleMsgTransferFrom(ctx, keeper, msg) - case types.MsgApprove: - return handleMsgApprove(ctx, keeper, msg) - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized Msg type: %T", msg) - } - } -} -func handleMsgContract(ctx sdk.Context, keeper keeper.Keeper, msg contract.Msg) error { - if !keeper.HasContractID(ctx) { - return sdkerrors.Wrapf(contract.ErrContractNotExist, "contract id: %s", msg.GetContractID()) - } - return nil -} diff --git a/x/token/internal/handler/handler_test.go b/x/token/internal/handler/handler_test.go deleted file mode 100644 index 1eb155b23d..0000000000 --- a/x/token/internal/handler/handler_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package handler - -import ( - "context" - "os" - "strings" - "testing" - - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/contract" - testCommon "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -var ( - ms store.CommitMultiStore - ctx sdk.Context - k testCommon.Keeper -) - -func setup() { - println("setup") - ctx, ms, k = testCommon.TestKeeper() -} - -func TestMain(m *testing.M) { - setup() - ret := m.Run() - os.Exit(ret) -} - -func cacheKeeper() (sdk.Context, sdk.Handler) { - msCache := ms.CacheMultiStore() - ctx = ctx.WithMultiStore(msCache) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID)) - return ctx, NewHandler(k) -} - -func verifyEventFunc(t *testing.T, expected sdk.Events, actual sdk.Events) { - require.Equal(t, sdk.StringifyEvents(expected.ToABCIEvents()).String(), sdk.StringifyEvents(actual.ToABCIEvents()).String()) -} - -const ( - defaultName = "name" - defaultContractID = "9be17165" - defaultSymbol = "BTC" - defaultImageURI = "image-uri" - defaultMeta = "{}" - defaultDecimals = 6 - defaultAmount = 1000 - defaultCoin = "link" -) - -var ( - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) -) - -func TestHandlerUnrecognized(t *testing.T) { - ctx, h := cacheKeeper() - - _, err := h(ctx, sdk.NewTestMsg()) - require.Error(t, err) - require.True(t, strings.Contains(err.Error(), "unrecognized Msg type")) -} diff --git a/x/token/internal/handler/issue.go b/x/token/internal/handler/issue.go deleted file mode 100644 index ea3ba2aa0f..0000000000 --- a/x/token/internal/handler/issue.go +++ /dev/null @@ -1,29 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func handleMsgIssue(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgIssue) (*sdk.Result, error) { - contractI := ctx.Context().Value(contract.CtxKey{}) - if contractI == nil { - panic("contract id does not set") - } - token := types.NewToken(contractI.(string), msg.Name, msg.Symbol, msg.Meta, msg.ImageURI, msg.Decimals, msg.Mintable) - err := keeper.IssueToken(ctx, token, msg.Amount, msg.Owner, msg.To) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/token/internal/handler/issue_test.go b/x/token/internal/handler/issue_test.go deleted file mode 100644 index 528c462408..0000000000 --- a/x/token/internal/handler/issue_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package handler - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func GetMadeContractID(events sdk.Events) string { - for _, event := range events.ToABCIEvents() { - for _, attr := range event.Attributes { - if string(attr.Key) == types.AttributeKeyContractID { - return string(attr.Value) - } - } - } - return "" -} - -func TestHandleMsgIssue(t *testing.T) { - ctx, h := cacheKeeper() - - t.Log("Issue Token") - { - msg := types.NewMsgIssue(addr1, addr1, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - contractID := GetMadeContractID(res.Events) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", types.ModifyAction)), - sdk.NewEvent("issue", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("issue", sdk.NewAttribute("name", defaultName)), - sdk.NewEvent("issue", sdk.NewAttribute("symbol", defaultSymbol)), - sdk.NewEvent("issue", sdk.NewAttribute("owner", addr1.String())), - sdk.NewEvent("issue", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("issue", sdk.NewAttribute("amount", sdk.NewInt(defaultAmount).String())), - sdk.NewEvent("issue", sdk.NewAttribute("mintable", "true")), - sdk.NewEvent("issue", sdk.NewAttribute("decimals", sdk.NewInt(defaultDecimals).String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "mint")), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", "burn")), - } - verifyEventFunc(t, e, res.Events) - } - - t.Log("Issue Token Again Expect Success") - { - msg := types.NewMsgIssue(addr1, addr1, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - _, err := h(ctx, msg) - require.NoError(t, err) - } -} diff --git a/x/token/internal/handler/mintburn.go b/x/token/internal/handler/mintburn.go deleted file mode 100644 index 72a98e99b3..0000000000 --- a/x/token/internal/handler/mintburn.go +++ /dev/null @@ -1,56 +0,0 @@ -// nolint:dupl -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func handleMsgMint(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgMint) (*sdk.Result, error) { - err := keeper.MintToken(ctx, msg.Amount, msg.From, msg.To) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgBurn(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgBurn) (*sdk.Result, error) { - err := keeper.BurnToken(ctx, msg.Amount, msg.From) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgBurnFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgBurnFrom) (*sdk.Result, error) { - err := keeper.BurnTokenFrom(ctx, msg.Proxy, msg.From, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/token/internal/handler/mintburn_test.go b/x/token/internal/handler/mintburn_test.go deleted file mode 100644 index e3485c6189..0000000000 --- a/x/token/internal/handler/mintburn_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package handler - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestHandleMsgMint(t *testing.T) { - ctx, h := cacheKeeper() - - t.Log("Prepare Token Issued") - { - k.NewContractID(ctx) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - err := k.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1) - require.NoError(t, err) - } - - t.Log("Burn Tokens") - { - msg := types.NewMsgMint(addr1, defaultContractID, addr1, sdk.NewInt(defaultAmount)) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("mint", sdk.NewAttribute("contract_id", defaultContractID)), - sdk.NewEvent("mint", sdk.NewAttribute("amount", sdk.NewInt(defaultAmount).String())), - sdk.NewEvent("mint", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("mint", sdk.NewAttribute("to", addr1.String())), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleMsgBurn(t *testing.T) { - ctx, h := cacheKeeper() - - t.Log("Prepare Token Issued") - { - k.NewContractID(ctx) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - err := k.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1) - require.NoError(t, err) - } - - t.Log("Mint Tokens") - { - msg := types.NewMsgBurn(addr1, defaultContractID, sdk.NewInt(defaultAmount)) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("burn", sdk.NewAttribute("contract_id", defaultContractID)), - sdk.NewEvent("burn", sdk.NewAttribute("amount", sdk.NewInt(defaultAmount).String())), - sdk.NewEvent("burn", sdk.NewAttribute("from", addr1.String())), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleMsgBurnFTFrom(t *testing.T) { - ctx, h := cacheKeeper() - - t.Log("Prepare Token Issued") - { - k.NewContractID(ctx) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - err := k.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1) - require.NoError(t, err) - } - - t.Log("fail to burn when addr2 is not approved ") - { - burnMsg := types.NewMsgBurnFrom(addr2, defaultContractID, addr1, sdk.NewInt(100)) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - - t.Log("Approve addr2") - { - msgApprove := types.NewMsgApprove(addr1, defaultContractID, addr2) - _, err := h(ctx, msgApprove) - require.NoError(t, err) - } - - t.Log("give permission to addr2") - { - permission := types.NewBurnPermission() - msg := types.NewMsgGrantPermission(addr1, defaultContractID, addr2, permission) - require.NoError(t, msg.ValidateBasic()) - _, err := h(ctx, msg) - require.NoError(t, err) - } - - t.Log("Error when invalid user") - { - burnMsg := types.NewMsgBurnFrom(addr2, defaultContractID, addr2, sdk.NewInt(100)) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - - t.Log("fail to burn over the being supplied") - { - burnMsg := types.NewMsgBurnFrom(addr2, defaultContractID, addr1, sdk.NewInt(1001)) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - - t.Log("fail to burn when invalid ContractID") - { - burnMsg := types.NewMsgBurnFrom(addr2, "abcd11234", addr1, sdk.NewInt(1000)) - _, err := h(ctx, burnMsg) - require.Error(t, err) - } - - t.Log("Succeed to burn") - { - burnMsg := types.NewMsgBurnFrom(addr2, defaultContractID, addr1, sdk.NewInt(100)) - res, err := h(ctx, burnMsg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("burn_from", sdk.NewAttribute("contract_id", defaultContractID)), - sdk.NewEvent("burn_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("burn_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("burn_from", sdk.NewAttribute("amount", sdk.NewInt(100).String())), - } - verifyEventFunc(t, e, res.Events) - } -} diff --git a/x/token/internal/handler/modify.go b/x/token/internal/handler/modify.go deleted file mode 100644 index 0f5167040c..0000000000 --- a/x/token/internal/handler/modify.go +++ /dev/null @@ -1,23 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func handleMsgModify(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgModify) (*sdk.Result, error) { - err := keeper.ModifyToken(ctx, msg.Owner, msg.Changes) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/token/internal/handler/modify_test.go b/x/token/internal/handler/modify_test.go deleted file mode 100644 index 1750398303..0000000000 --- a/x/token/internal/handler/modify_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestHandleMsgModify(t *testing.T) { - ctx, h := cacheKeeper() - - contractID := contract.SampleContractID - const ( - modifiedTokenName = "modifiedTokenName" - modifiedImgURI = "modifiedImgURI" - modifiedMeta = "modifiedMeta" - ) - // Given MsgModify - msg := types.NewMsgModify(addr1, contractID, types.NewChanges( - types.NewChange("name", modifiedTokenName), - types.NewChange("img_uri", modifiedImgURI), - types.NewChange("meta", modifiedMeta), - )) - - t.Log("Test with nonexistent token") - { - // When handle MsgModify - _, err := h(ctx, msg) - - // Then response is error - require.Error(t, err) - } - - t.Log("Test modify token") - { - // Given issued token - res, err := h(ctx, types.NewMsgIssue(addr1, addr1, defaultName, defaultContractID, defaultMeta, defaultImageURI, - sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true)) - require.NoError(t, err) - contractID := GetMadeContractID(res.Events) - - msg := types.NewMsgModify(addr1, contractID, types.NewChanges( - types.NewChange("name", modifiedTokenName), - types.NewChange("img_uri", modifiedImgURI), - types.NewChange("meta", modifiedMeta), - )) - - // When handle MsgModify - res, err = h(ctx, msg) - - // Then response is success - require.NoError(t, err) - // And events are returned - expectedEvents := sdk.Events{ - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute(types.AttributeKeyContractID, defaultContractID)), - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute("name", modifiedTokenName)), - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute("img_uri", modifiedImgURI)), - sdk.NewEvent(types.EventTypeModifyToken, sdk.NewAttribute("meta", modifiedMeta)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory)), - sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String())), - } - verifyEventFunc(t, expectedEvents, res.Events) - } -} diff --git a/x/token/internal/handler/perm.go b/x/token/internal/handler/perm.go deleted file mode 100644 index b3d007b7b6..0000000000 --- a/x/token/internal/handler/perm.go +++ /dev/null @@ -1,40 +0,0 @@ -// nolint:dupl -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func handleMsgGrant(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgGrantPermission) (*sdk.Result, error) { - err := keeper.GrantPermission(ctx, msg.From, msg.To, msg.Permission) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgRevoke(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgRevokePermission) (*sdk.Result, error) { - err := keeper.RevokePermission(ctx, msg.From, msg.Permission) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - }) - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/token/internal/handler/perm_test.go b/x/token/internal/handler/perm_test.go deleted file mode 100644 index db8e2e2c20..0000000000 --- a/x/token/internal/handler/perm_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package handler - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestHandleMsgGrant(t *testing.T) { - ctx, h := cacheKeeper() - - t.Log("Prepare Token Issued") - { - k.NewContractID(ctx) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - err := k.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1) - require.NoError(t, err) - } - - permission := types.NewMintPermission() - t.Log("Invalid contract id") - { - msg := types.NewMsgGrantPermission(addr1, "1234567890", addr2, permission) - require.Error(t, msg.ValidateBasic()) - } - t.Log("Grant Permission") - { - msg := types.NewMsgGrantPermission(addr1, defaultContractID, addr2, permission) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("grant_perm", sdk.NewAttribute("contract_id", defaultContractID)), - sdk.NewEvent("grant_perm", sdk.NewAttribute("perm", permission.String())), - } - verifyEventFunc(t, e, res.Events) - } -} - -func TestHandleMsgRevoke(t *testing.T) { - ctx, h := cacheKeeper() - - t.Log("Prepare Token Issued") - { - k.NewContractID(ctx) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - err := k.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1) - require.NoError(t, err) - } - - permission := types.NewMintPermission() - t.Log("Invalid contract id") - { - msg := types.NewMsgRevokePermission(addr1, "1234567890", permission) - require.Error(t, msg.ValidateBasic()) - } - t.Log("Revoke Permission") - { - msg := types.NewMsgRevokePermission(addr1, defaultContractID, permission) - require.NoError(t, msg.ValidateBasic()) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("contract_id", defaultContractID)), - sdk.NewEvent("revoke_perm", sdk.NewAttribute("perm", permission.String())), - } - verifyEventFunc(t, e, res.Events) - } -} diff --git a/x/token/internal/handler/proxy.go b/x/token/internal/handler/proxy.go deleted file mode 100644 index b07b7933e6..0000000000 --- a/x/token/internal/handler/proxy.go +++ /dev/null @@ -1,24 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func handleMsgApprove(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgApprove) (*sdk.Result, error) { - err := keeper.SetApproved(ctx, msg.Proxy, msg.Approver) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Approver.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/token/internal/handler/proxy_test.go b/x/token/internal/handler/proxy_test.go deleted file mode 100644 index d3865b1a72..0000000000 --- a/x/token/internal/handler/proxy_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package handler - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestHandleApprove(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - msgIssue := types.NewMsgIssue(addr1, addr1, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - res, err := h(ctx, msgIssue) - require.NoError(t, err) - - contractID = GetMadeContractID(res.Events) - - msgMint := types.NewMsgMint(addr1, contractID, addr1, sdk.NewInt(defaultAmount)) - _, err = h(ctx, msgMint) - require.NoError(t, err) - } - - msg := types.NewMsgTransferFrom(addr2, contractID, addr1, addr2, sdk.NewInt(defaultAmount)) - _, err := h(ctx, msg) - require.Error(t, err) - - { - msgApprove := types.NewMsgApprove(addr1, contractID, addr2) - _, err := h(ctx, msgApprove) - require.NoError(t, err) - } - - msg = types.NewMsgTransferFrom(addr2, contractID, addr1, addr2, sdk.NewInt(defaultAmount)) - res, err := h(ctx, msg) - require.NoError(t, err) - - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("amount", sdk.NewInt(defaultAmount).String())), - } - verifyEventFunc(t, e, res.Events) -} diff --git a/x/token/internal/handler/transfer.go b/x/token/internal/handler/transfer.go deleted file mode 100644 index acd3529a9e..0000000000 --- a/x/token/internal/handler/transfer.go +++ /dev/null @@ -1,41 +0,0 @@ -package handler - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func handleMsgTransfer(ctx sdk.Context, k keeper.Keeper, msg types.MsgTransfer) (*sdk.Result, error) { - err := k.Transfer(ctx, msg.From, msg.To, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} - -func handleMsgTransferFrom(ctx sdk.Context, keeper keeper.Keeper, msg types.MsgTransferFrom) (*sdk.Result, error) { - err := keeper.TransferFrom(ctx, msg.Proxy, msg.From, msg.To, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proxy.String()), - ), - ) - - return &sdk.Result{Events: ctx.EventManager().Events()}, nil -} diff --git a/x/token/internal/handler/transfer_test.go b/x/token/internal/handler/transfer_test.go deleted file mode 100644 index 8aee1d7c61..0000000000 --- a/x/token/internal/handler/transfer_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package handler - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestHandleMsgTransfer(t *testing.T) { - ctx, h := cacheKeeper() - - t.Log("Prepare Token Issued") - { - k.NewContractID(ctx) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - err := k.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1) - require.NoError(t, err) - } - - t.Log("Transfer Token") - { - msg := types.NewMsgTransfer(addr1, addr2, defaultContractID, sdk.NewInt(10)) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr1.String())), - sdk.NewEvent("transfer", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer", sdk.NewAttribute("contract_id", defaultContractID)), - sdk.NewEvent("transfer", sdk.NewAttribute("amount", sdk.NewInt(10).String())), - } - verifyEventFunc(t, e, res.Events) - } - t.Log("Transfer Coin. Expect Fail") - { - msg := types.NewMsgTransfer(addr1, addr2, defaultCoin, sdk.NewInt(10)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(contract.ErrInvalidContractID, "ContractID: %s", defaultCoin).Error()) - _, err := h(ctx, msg) - require.Error(t, err) - } -} - -func TestHandleTransferFrom(t *testing.T) { - ctx, h := cacheKeeper() - - var contractID string - { - msgIssue := types.NewMsgIssue(addr1, addr1, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultAmount), sdk.NewInt(defaultDecimals), true) - res, err := h(ctx, msgIssue) - require.NoError(t, err) - - contractID = GetMadeContractID(res.Events) - - msgApprove := types.NewMsgApprove(addr1, contractID, addr2) - _, err = h(ctx, msgApprove) - require.NoError(t, err) - } - - msg := types.NewMsgTransferFrom(addr2, contractID, addr1, addr2, sdk.NewInt(defaultAmount)) - res, err := h(ctx, msg) - require.NoError(t, err) - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("module", "token")), - sdk.NewEvent("message", sdk.NewAttribute("sender", addr2.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("contract_id", contractID)), - sdk.NewEvent("transfer_from", sdk.NewAttribute("proxy", addr2.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("from", addr1.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("to", addr2.String())), - sdk.NewEvent("transfer_from", sdk.NewAttribute("amount", sdk.NewInt(defaultAmount).String())), - } - verifyEventFunc(t, e, res.Events) -} diff --git a/x/token/internal/keeper/account.go b/x/token/internal/keeper/account.go deleted file mode 100644 index 02a9fabc4a..0000000000 --- a/x/token/internal/keeper/account.go +++ /dev/null @@ -1,79 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -type AccountKeeper interface { - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) - GetOrNewAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) - SetAccount(ctx sdk.Context, acc types.Account) error - UpdateAccount(ctx sdk.Context, acc types.Account) error -} - -func (k Keeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) { - acc = types.NewBaseAccountWithAddress(k.getContractID(ctx), addr) - if err = k.SetAccount(ctx, acc); err != nil { - return nil, err - } - return acc, nil -} - -func (k Keeper) SetAccount(ctx sdk.Context, acc types.Account) error { - store := ctx.KVStore(k.storeKey) - accKey := types.AccountKey(acc.GetContractID(), acc.GetAddress()) - if store.Has(accKey) { - return sdkerrors.Wrap(types.ErrAccountExist, acc.GetAddress().String()) - } - store.Set(accKey, k.cdc.MustMarshalBinaryBare(acc)) - - // Set Account if not exists yet - account := k.accountKeeper.GetAccount(ctx, acc.GetAddress()) - if account == nil { - account = k.accountKeeper.NewAccountWithAddress(ctx, acc.GetAddress()) - k.accountKeeper.SetAccount(ctx, account) - } - return nil -} - -func (k Keeper) UpdateAccount(ctx sdk.Context, acc types.Account) error { - store := ctx.KVStore(k.storeKey) - accKey := types.AccountKey(acc.GetContractID(), acc.GetAddress()) - if !store.Has(accKey) { - return sdkerrors.Wrap(types.ErrAccountNotExist, acc.GetAddress().String()) - } - store.Set(accKey, k.cdc.MustMarshalBinaryBare(acc)) - return nil -} - -func (k Keeper) GetOrNewAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) { - acc, err = k.GetAccount(ctx, addr) - if err != nil { - acc, err = k.NewAccountWithAddress(ctx, addr) - if err != nil { - return nil, err - } - } - return acc, nil -} - -func (k Keeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) (acc types.Account, err error) { - store := ctx.KVStore(k.storeKey) - accKey := types.AccountKey(k.getContractID(ctx), addr) - if !store.Has(accKey) { - return nil, sdkerrors.Wrap(types.ErrAccountNotExist, addr.String()) - } - bz := store.Get(accKey) - return k.mustDecodeAccount(bz), nil -} - -func (k Keeper) mustDecodeAccount(bz []byte) (acc types.Account) { - err := k.cdc.UnmarshalBinaryBare(bz, &acc) - if err != nil { - panic(err) - } - return -} diff --git a/x/token/internal/keeper/account_test.go b/x/token/internal/keeper/account_test.go deleted file mode 100644 index 118ccf2e68..0000000000 --- a/x/token/internal/keeper/account_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func verifyAccountFunc(t *testing.T, expected types.Account, actual types.Account) { - require.Equal(t, expected.GetContractID(), actual.GetContractID()) - require.Equal(t, expected.GetAddress(), actual.GetAddress()) - require.Equal(t, expected.GetBalance(), actual.GetBalance()) -} - -func TestKeeper_SetAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - expected := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, expected)) - } - t.Log("Compare Account") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.AccountKey(expected.GetContractID(), addr1)) - actual := keeper.mustDecodeAccount(bz) - verifyAccountFunc(t, expected, actual) - } -} - -func TestKeeper_GetAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Account") - expected := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.AccountKey(expected.GetContractID(), addr1), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Account") - { - actual, err := keeper.GetAccount(ctx, addr1) - require.NoError(t, err) - verifyAccountFunc(t, expected, actual) - } -} - -func TestKeeper_UpdateAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Update Account") - var expected types.Account - expected = types.NewBaseAccountWithAddress(defaultContractID, addr1) - expected = expected.SetBalance(sdk.OneInt()) - { - require.NoError(t, keeper.UpdateAccount(ctx, expected)) - } - t.Log("Compare Account") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.AccountKey(acc.GetContractID(), addr1)) - actual := keeper.mustDecodeAccount(bz) - verifyAccountFunc(t, expected, actual) - } -} - -func TestKeeper_GetOrNewAccount(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Account") - expected := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.AccountKey(expected.GetContractID(), addr1), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Account addr1") - { - actual, err := keeper.GetOrNewAccount(ctx, addr1) - require.NoError(t, err) - verifyAccountFunc(t, expected, actual) - } - - expected = types.NewBaseAccountWithAddress(defaultContractID, addr2) - t.Log("Get Account addr2") - { - actual, err := keeper.GetOrNewAccount(ctx, addr2) - require.NoError(t, err) - verifyAccountFunc(t, expected, actual) - } -} diff --git a/x/token/internal/keeper/bank.go b/x/token/internal/keeper/bank.go deleted file mode 100644 index 9f1bff8e31..0000000000 --- a/x/token/internal/keeper/bank.go +++ /dev/null @@ -1,107 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -// For the Token module -type BankKeeper interface { - GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdk.Int - SetBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) error - HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) bool - - SubtractBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) (sdk.Int, error) - AddBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) (sdk.Int, error) - Send(ctx sdk.Context, from, to sdk.AccAddress, amt sdk.Int) error -} - -var _ BankKeeper = (*Keeper)(nil) - -func (k Keeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdk.Int { - acc, err := k.GetAccount(ctx, addr) - if err != nil { - return sdk.ZeroInt() - } - return acc.GetBalance() -} - -func (k Keeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) error { - acc, err := k.GetAccount(ctx, addr) - if err != nil { - return err - } - acc = acc.SetBalance(amt) - err = k.UpdateAccount(ctx, acc) - if err != nil { - return err - } - return nil -} - -func (k Keeper) HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) bool { - return k.GetBalance(ctx, addr).GTE(amt) -} - -func (k Keeper) Send(ctx sdk.Context, from, to sdk.AccAddress, amt sdk.Int) error { - if amt.IsNegative() { - return sdkerrors.Wrap(types.ErrInvalidAmount, "send amount must be positive") - } - - _, err := k.SubtractBalance(ctx, from, amt) - if err != nil { - return err - } - - _, err = k.AddBalance(ctx, to, amt) - if err != nil { - return err - } - return nil -} - -func (k Keeper) SubtractBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) (sdk.Int, error) { - return k.subtractBalance(ctx, addr, amt) -} -func (k Keeper) subtractBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) (sdk.Int, error) { - acc, err := k.GetAccount(ctx, addr) - if err != nil { - return sdk.ZeroInt(), sdkerrors.Wrapf(types.ErrInsufficientBalance, fmt.Sprintf("insufficient account funds for token [%s]; 0 < %s", k.getContractID(ctx), amt)) - } - oldBalance := acc.GetBalance() - newBalance := oldBalance.Sub(amt) - if newBalance.IsNegative() { - return amt, sdkerrors.Wrapf(types.ErrInsufficientBalance, "insufficient account funds for token [%s]; %s < %s", k.getContractID(ctx), oldBalance, amt) - } - acc = acc.SetBalance(newBalance) - err = k.UpdateAccount(ctx, acc) - if err != nil { - return amt, err - } - return newBalance, nil -} - -func (k Keeper) AddBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) (sdk.Int, error) { - return k.addBalance(ctx, addr, amt) -} - -func (k Keeper) addBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Int) (sdk.Int, error) { - acc, err := k.GetOrNewAccount(ctx, addr) - if err != nil { - return amt, err - } - oldBalance := acc.GetBalance() - newBalance := oldBalance.Add(amt) - if newBalance.IsNegative() { - return amt, sdkerrors.Wrapf(types.ErrInsufficientBalance, "insufficient account funds for token [%s]; %s < %s", k.getContractID(ctx), oldBalance, amt) - } - acc = acc.SetBalance(newBalance) - err = k.UpdateAccount(ctx, acc) - if err != nil { - return amt, err - } - return newBalance, nil -} diff --git a/x/token/internal/keeper/bank_test.go b/x/token/internal/keeper/bank_test.go deleted file mode 100644 index 195f3d8fcb..0000000000 --- a/x/token/internal/keeper/bank_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func TestKeeper_GetBalance(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Get Balance") - { - balance := keeper.GetBalance(ctx, addr1) - require.Equal(t, balance.Int64(), acc.GetBalance().Int64()) - } -} - -func TestKeeper_HasBalance(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - var acc types.Account - acc = types.NewBaseAccountWithAddress(defaultContractID, addr1) - acc = acc.SetBalance(sdk.NewInt(defaultAmount)) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Has Balance") - { - require.True(t, keeper.HasBalance(ctx, addr1, sdk.NewInt(defaultAmount))) - } -} - -func TestKeeper_SetBalance(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Set Balance") - { - require.NoError(t, keeper.SetBalance(ctx, addr1, sdk.NewInt(defaultAmount))) - } - t.Log("Get Balance") - { - balance := keeper.GetBalance(ctx, addr1) - require.Equal(t, sdk.NewInt(defaultAmount).Int64(), balance.Int64()) - } -} - -func TestKeeper_AddBalance(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Add Balance") - { - added, err := keeper.AddBalance(ctx, addr1, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount).Int64(), added.Int64()) - } - t.Log("Get Balance") - { - balance := keeper.GetBalance(ctx, addr1) - require.Equal(t, sdk.NewInt(defaultAmount).Int64(), balance.Int64()) - } -} - -func TestKeeper_SubtractBalance(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Set Balance") - { - require.NoError(t, keeper.SetBalance(ctx, addr1, sdk.NewInt(defaultAmount))) - } - t.Log("Subtract Balance") - { - sub, err := keeper.SubtractBalance(ctx, addr1, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - require.Equal(t, sdk.ZeroInt().Int64(), sub.Int64()) - } - t.Log("Get Balance") - { - balance := keeper.GetBalance(ctx, addr1) - require.Equal(t, sdk.ZeroInt().Int64(), balance.Int64()) - } -} - -func TestKeeper_SendToken(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Set Balance") - { - require.NoError(t, keeper.SetBalance(ctx, addr1, sdk.NewInt(defaultAmount))) - } - t.Log("Send Balance") - { - require.NoError(t, keeper.Send(ctx, addr1, addr2, sdk.NewInt(defaultAmount))) - } - { - require.EqualError(t, keeper.Send(ctx, addr3, addr2, sdk.NewInt(1)), sdkerrors.Wrapf(types.ErrInsufficientBalance, "insufficient account funds for token [9be17165]; 0 < 1").Error()) - } - t.Log("Get Balance") - { - require.Equal(t, sdk.ZeroInt().Int64(), keeper.GetBalance(ctx, addr1).Int64()) - require.Equal(t, sdk.NewInt(defaultAmount).Int64(), keeper.GetBalance(ctx, addr2).Int64()) - } -} diff --git a/x/token/internal/keeper/blacklist.go b/x/token/internal/keeper/blacklist.go deleted file mode 100644 index 368430b070..0000000000 --- a/x/token/internal/keeper/blacklist.go +++ /dev/null @@ -1,19 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) SetBlackList(ctx sdk.Context, addr sdk.AccAddress, action string) { - store := ctx.KVStore(k.storeKey) - - // value is just a key w/o the module prefix - v := addr.String() + ":" + action - store.Set(types.BlacklistKey(addr, action), []byte(v)) -} - -func (k Keeper) IsBlacklisted(ctx sdk.Context, addr sdk.AccAddress, action string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.BlacklistKey(addr, action)) -} diff --git a/x/token/internal/keeper/blacklist_test.go b/x/token/internal/keeper/blacklist_test.go deleted file mode 100644 index 95b07672f4..0000000000 --- a/x/token/internal/keeper/blacklist_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestKeeper_SetBlackList(t *testing.T) { - ctx := cacheKeeper() - keeper.SetBlackList(ctx, addr1, "every") - require.True(t, keeper.IsBlacklisted(ctx, addr1, "every")) -} - -func TestKeeper_IsBlacklisted(t *testing.T) { - ctx := cacheKeeper() - keeper.SetBlackList(ctx, addr1, "every") - require.True(t, keeper.IsBlacklisted(ctx, addr1, "every")) - require.False(t, keeper.IsBlacklisted(ctx, addr2, "every")) - require.False(t, keeper.IsBlacklisted(ctx, addr1, "every2")) -} diff --git a/x/token/internal/keeper/burn.go b/x/token/internal/keeper/burn.go deleted file mode 100644 index a5130ab3ba..0000000000 --- a/x/token/internal/keeper/burn.go +++ /dev/null @@ -1,70 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) BurnToken(ctx sdk.Context, amount sdk.Int, from sdk.AccAddress) error { - err := k.isBurnable(ctx, from, from, amount) - if err != nil { - return err - } - - err = k.BurnSupply(ctx, from, amount) - if err != nil { - return err - } - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnToken, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - ), - }) - return nil -} - -func (k Keeper) BurnTokenFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, amount sdk.Int) error { - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrTokenNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - err := k.isBurnable(ctx, proxy, from, amount) - if err != nil { - return err - } - - err = k.BurnSupply(ctx, from, amount) - if err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeBurnTokenFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - ), - }) - return nil -} - -func (k Keeper) isBurnable(ctx sdk.Context, permissionOwner, tokenOwner sdk.AccAddress, amount sdk.Int) error { - if !k.HasBalance(ctx, tokenOwner, amount) { - return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "%v has not enough coins for %v", tokenOwner.String(), amount) - } - if !amount.IsPositive() { - return sdkerrors.Wrap(types.ErrInvalidAmount, amount.String()) - } - - perm := types.NewBurnPermission() - if !k.HasPermission(ctx, permissionOwner, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", permissionOwner.String(), perm.String()) - } - return nil -} diff --git a/x/token/internal/keeper/burn_test.go b/x/token/internal/keeper/burn_test.go deleted file mode 100644 index 6e4027a875..0000000000 --- a/x/token/internal/keeper/burn_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_BurnTokens(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.IssueToken(ctx, token, sdk.NewInt(defaultAmount+defaultAmount), addr1, addr1)) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount+defaultAmount), supply.Int64()) - } - t.Log("Balance of Account") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount+defaultAmount), supply.Int64()) - } - - t.Log("Burn Tokens by addr1") - { - err := keeper.BurnToken(ctx, sdk.NewInt(defaultAmount), addr1) - require.NoError(t, err) - } - t.Log("Burn 0 Token by addr1") - { - err := keeper.BurnToken(ctx, sdk.NewInt(0), addr1) - require.Error(t, err) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.Equal(t, int64(defaultAmount), supply.Int64()) - require.NoError(t, err) - } - t.Log("Balance of Account 1") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } -} - -func TestKeeper_BurnTokenFrom(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.IssueToken(ctx, token, sdk.NewInt(defaultAmount+defaultAmount), addr1, addr1)) - } - t.Log("set permission for proxy") - { - keeper.AddPermission(ctx, addr2, types.NewBurnPermission()) - } - t.Log("approve") - { - require.NoError(t, keeper.SetApproved(ctx, addr2, addr1)) - } - t.Log("Burn Tokens by proxy") - { - err := keeper.BurnTokenFrom(ctx, addr2, addr1, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - } - t.Log("check Balance of Account 1") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } -} - -func TestKeeper_BurnTokensWithoutPermissions(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1)) - } - - t.Log("Transfer Enough Token") - { - err := keeper.Transfer(ctx, addr1, addr2, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - } - - t.Log("Burn Tokens by addr2. Expect Fail") - { - err := keeper.BurnToken(ctx, sdk.NewInt(defaultAmount), addr2) - require.Error(t, err) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2.String(), types.NewBurnPermission().String()).Error()) - } -} diff --git a/x/token/internal/keeper/hooks.go b/x/token/internal/keeper/hooks.go deleted file mode 100644 index a4df903b9f..0000000000 --- a/x/token/internal/keeper/hooks.go +++ /dev/null @@ -1,11 +0,0 @@ -package keeper - -// Hooks wrapper struct for safety box keeper -type Hooks struct { - k Keeper -} - -// Return the wrapper struct -func (k Keeper) Hooks() *Hooks { - return &Hooks{k} -} diff --git a/x/token/internal/keeper/issue.go b/x/token/internal/keeper/issue.go deleted file mode 100644 index 92f08edd30..0000000000 --- a/x/token/internal/keeper/issue.go +++ /dev/null @@ -1,70 +0,0 @@ -package keeper - -import ( - "strconv" - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) IssueToken(ctx sdk.Context, token types.Token, amount sdk.Int, owner, to sdk.AccAddress) error { - if !types.ValidateImageURI(token.GetImageURI()) { - return sdkerrors.Wrapf(types.ErrInvalidImageURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", token.GetImageURI(), types.MaxImageURILength, utf8.RuneCountInString(token.GetImageURI())) - } - err := k.SetToken(ctx, token) - if err != nil { - return err - } - - err = k.MintSupply(ctx, to, amount) - if err != nil { - return err - } - - modifyTokenURIPermission := types.NewModifyPermission() - k.AddPermission(ctx, owner, modifyTokenURIPermission) - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeIssueToken, - sdk.NewAttribute(types.AttributeKeyContractID, token.GetContractID()), - sdk.NewAttribute(types.AttributeKeyName, token.GetName()), - sdk.NewAttribute(types.AttributeKeySymbol, token.GetSymbol()), - sdk.NewAttribute(types.AttributeKeyOwner, owner.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyMintable, strconv.FormatBool(token.GetMintable())), - sdk.NewAttribute(types.AttributeKeyDecimals, token.GetDecimals().String()), - ), - sdk.NewEvent( - types.EventTypeGrantPermToken, - sdk.NewAttribute(types.AttributeKeyTo, owner.String()), - sdk.NewAttribute(types.AttributeKeyContractID, token.GetContractID()), - sdk.NewAttribute(types.AttributeKeyPerm, modifyTokenURIPermission.String()), - ), - }) - - if token.GetMintable() { - mintPerm := types.NewMintPermission() - k.AddPermission(ctx, owner, mintPerm) - burnPerm := types.NewBurnPermission() - k.AddPermission(ctx, owner, burnPerm) - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeGrantPermToken, - sdk.NewAttribute(types.AttributeKeyTo, owner.String()), - sdk.NewAttribute(types.AttributeKeyContractID, token.GetContractID()), - sdk.NewAttribute(types.AttributeKeyPerm, mintPerm.String()), - ), - sdk.NewEvent( - types.EventTypeGrantPermToken, - sdk.NewAttribute(types.AttributeKeyTo, owner.String()), - sdk.NewAttribute(types.AttributeKeyContractID, token.GetContractID()), - sdk.NewAttribute(types.AttributeKeyPerm, burnPerm.String()), - ), - }) - } - - return nil -} diff --git a/x/token/internal/keeper/issue_test.go b/x/token/internal/keeper/issue_test.go deleted file mode 100644 index d7e1baddfb..0000000000 --- a/x/token/internal/keeper/issue_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package keeper - -import ( - "strings" - "testing" - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_IssueToken(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue Token") - expected := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.IssueToken(ctx, expected, sdk.NewInt(defaultAmount), addr1, addr1)) - } - t.Log("Get Token") - { - actual, err := keeper.GetToken(ctx) - require.NoError(t, err) - verifyTokenFunc(t, expected, actual) - } - t.Log("Permission") - { - require.True(t, keeper.HasPermission(ctx, addr1, types.NewModifyPermission())) - require.True(t, keeper.HasPermission(ctx, addr1, types.NewMintPermission())) - require.True(t, keeper.HasPermission(ctx, addr1, types.NewBurnPermission())) - } - t.Log("Permission only addr1 has the permissions") - { - require.False(t, keeper.HasPermission(ctx, addr2, types.NewModifyPermission())) - require.False(t, keeper.HasPermission(ctx, addr2, types.NewMintPermission())) - require.False(t, keeper.HasPermission(ctx, addr2, types.NewBurnPermission())) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } - t.Log("Balance of Account") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } -} - -func TestKeeper_IssueTokenNotMintable(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue a Token Not Mintable") - expected := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), false) - { - require.NoError(t, keeper.IssueToken(ctx, expected, sdk.NewInt(defaultAmount), addr1, addr1)) - } - { - actual, err := keeper.GetToken(ctx) - require.NoError(t, err) - verifyTokenFunc(t, expected, actual) - } - t.Log("Permission only addr1 has no mint/burn permissions") - { - require.True(t, keeper.HasPermission(ctx, addr1, types.NewModifyPermission())) - require.False(t, keeper.HasPermission(ctx, addr1, types.NewMintPermission())) - require.False(t, keeper.HasPermission(ctx, addr1, types.NewBurnPermission())) - } -} - -func TestKeeper_IssueTokenTooLongTokenURI(t *testing.T) { - ctx := cacheKeeper() - - length1001String := strings.Repeat("Eng글자日本語はスゲ", 91) // 11 * 91 = 1001 - - t.Log("issue a token with too long token uri") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, length1001String, sdk.NewInt(defaultDecimals), true) - require.EqualError(t, keeper.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1), sdkerrors.Wrapf(types.ErrInvalidImageURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, types.MaxImageURILength, utf8.RuneCountInString(length1001String)).Error()) - } -} diff --git a/x/token/internal/keeper/keeper.go b/x/token/internal/keeper/keeper.go deleted file mode 100644 index 0a602c1783..0000000000 --- a/x/token/internal/keeper/keeper.go +++ /dev/null @@ -1,57 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/tendermint/tendermint/libs/log" -) - -type Keeper struct { - accountKeeper types.AccountKeeper - storeKey sdk.StoreKey - contractKeeper contract.Keeper - cdc *codec.Codec -} - -func NewKeeper(cdc *codec.Codec, accountKeeper types.AccountKeeper, contractKeeper contract.Keeper, storeKey sdk.StoreKey) Keeper { - return Keeper{ - accountKeeper: accountKeeper, - storeKey: storeKey, - contractKeeper: contractKeeper, - cdc: cdc, - } -} - -func (k Keeper) NewContractID(ctx sdk.Context) string { - return k.contractKeeper.NewContractID(ctx) -} -func (k Keeper) HasContractID(ctx sdk.Context) bool { - return k.contractKeeper.HasContractID(ctx, k.getContractID(ctx)) -} -func (k Keeper) getContractID(ctx sdk.Context) string { - contractI := ctx.Context().Value(contract.CtxKey{}) - if contractI == nil { - panic("contract id does not set on the context") - } - return contractI.(string) -} - -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -func (k Keeper) UnmarshalJSON(bz []byte, ptr interface{}) error { - return k.cdc.UnmarshalJSON(bz, ptr) -} - -func (k Keeper) MarshalJSON(o interface{}) ([]byte, error) { - return k.cdc.MarshalJSON(o) -} - -func (k Keeper) MarshalJSONIndent(o interface{}) ([]byte, error) { - return k.cdc.MarshalJSONIndent(o, "", " ") -} diff --git a/x/token/internal/keeper/keeper_test.go b/x/token/internal/keeper/keeper_test.go deleted file mode 100644 index 56689dad01..0000000000 --- a/x/token/internal/keeper/keeper_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package keeper - -import ( - "context" - "os" - "testing" - - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - defaultName = "name" - defaultSymbol = "BTC" - defaultContractID = "9be17165" - anotherContractID = "56171eb9" - defaultMeta = "{}" - defaultImageURI = "image-uri" - defaultDecimals = 6 - defaultAmount = 1000 -) - -var ( - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr3 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) -) - -var ( - ms store.CommitMultiStore - ctx sdk.Context - keeper Keeper -) - -func setup() { - println("setup") - ctx, ms, keeper = TestKeeper() -} - -func TestMain(m *testing.M) { - setup() - ret := m.Run() - os.Exit(ret) -} - -func cacheKeeper() sdk.Context { - msCache := ms.CacheMultiStore() - ctx = ctx.WithMultiStore(msCache) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID)) - return ctx -} - -func verifyTokenFunc(t *testing.T, expected types.Token, actual types.Token) { - require.Equal(t, expected.GetContractID(), actual.GetContractID()) - require.Equal(t, expected.GetName(), actual.GetName()) - require.Equal(t, expected.GetImageURI(), actual.GetImageURI()) - require.Equal(t, expected.GetDecimals(), actual.GetDecimals()) - require.Equal(t, expected.GetMintable(), actual.GetMintable()) -} - -func TestKeeper_MarshalJSONLogger(t *testing.T) { - ctx := cacheKeeper() - dummy := struct { - Key string - Value string - }{ - Key: "key", - Value: "value", - } - bz, err := keeper.MarshalJSON(dummy) - require.NoError(t, err) - - dummy2 := struct { - Key string - Value string - }{} - - err = keeper.UnmarshalJSON(bz, &dummy2) - require.NoError(t, err) - require.Equal(t, dummy.Key, dummy2.Key) - require.Equal(t, dummy.Value, dummy2.Value) - logger := keeper.Logger(ctx) - logger.Info("test", dummy, dummy2) -} diff --git a/x/token/internal/keeper/mint.go b/x/token/internal/keeper/mint.go deleted file mode 100644 index 73b5f69be0..0000000000 --- a/x/token/internal/keeper/mint.go +++ /dev/null @@ -1,45 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) MintToken(ctx sdk.Context, amount sdk.Int, from, to sdk.AccAddress) error { - token, err := k.GetToken(ctx) - if err != nil { - return err - } - if err := k.isMintable(ctx, token, from, amount); err != nil { - return err - } - err = k.MintSupply(ctx, to, amount) - if err != nil { - return err - } - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeMintToken, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - ), - }) - return nil -} - -func (k Keeper) isMintable(ctx sdk.Context, token types.Token, from sdk.AccAddress, amount sdk.Int) error { - if !token.GetMintable() { - return sdkerrors.Wrapf(types.ErrTokenNotMintable, "ContractID: %s", token.GetContractID()) - } - if !amount.IsPositive() { - return sdkerrors.Wrap(types.ErrInvalidAmount, amount.String()) - } - perm := types.NewMintPermission() - if !k.HasPermission(ctx, from, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", from.String(), perm.String()) - } - return nil -} diff --git a/x/token/internal/keeper/mint_test.go b/x/token/internal/keeper/mint_test.go deleted file mode 100644 index 5904bb154b..0000000000 --- a/x/token/internal/keeper/mint_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_MintTokens(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1)) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } - t.Log("Balance of Account") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } - - t.Log("Mint Tokens addr1 -> addr1") - { - err := keeper.MintToken(ctx, sdk.NewInt(defaultAmount), addr1, addr1) - require.NoError(t, err) - } - t.Log("Mint 0 Token") - { - err := keeper.MintToken(ctx, sdk.NewInt(0), addr1, addr1) - require.Error(t, err) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.Equal(t, int64(defaultAmount+defaultAmount), supply.Int64()) - require.NoError(t, err) - } - t.Log("Balance of Account 1") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount+defaultAmount), supply.Int64()) - } - t.Log("Mint Tokens addr1 -> addr2") - { - err := keeper.MintToken(ctx, sdk.NewInt(defaultAmount), addr1, addr2) - require.NoError(t, err) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.Equal(t, int64(defaultAmount+defaultAmount+defaultAmount), supply.Int64()) - require.NoError(t, err) - } - t.Log("Balance of Account 1") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount+defaultAmount), supply.Int64()) - } - t.Log("Balance of Account 2") - { - supply := keeper.GetBalance(ctx, addr2) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } -} - -func TestKeeper_MintTokensWithoutPermissions(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1)) - } - - t.Log("Mint Tokens by addr2. Expect Fail") - { - err := keeper.MintToken(ctx, sdk.NewInt(defaultAmount), addr2, addr2) - require.Error(t, err) - require.EqualError(t, err, sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr2.String(), types.NewMintPermission().String()).Error()) - } -} diff --git a/x/token/internal/keeper/modify.go b/x/token/internal/keeper/modify.go deleted file mode 100644 index a9ef10e14e..0000000000 --- a/x/token/internal/keeper/modify.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) ModifyToken(ctx sdk.Context, owner sdk.AccAddress, changes types.Changes) error { - token, err := k.GetToken(ctx) - if err != nil { - return err - } - - tokenModifyPerm := types.NewModifyPermission() - if !k.HasPermission(ctx, owner, tokenModifyPerm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", owner.String(), tokenModifyPerm.String()) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyToken, - sdk.NewAttribute(types.AttributeKeyContractID, token.GetContractID()), - ), - }) - - for _, change := range changes { - switch change.Field { - case types.AttributeKeyName: - token.SetName(change.Value) - case types.AttributeKeyMeta: - token.SetMeta(change.Value) - case types.AttributeKeyImageURI: - token.SetImageURI(change.Value) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeModifyToken, - sdk.NewAttribute(change.Field, change.Value), - ), - }) - } - err = k.UpdateToken(ctx, token) - if err != nil { - return err - } - return nil -} diff --git a/x/token/internal/keeper/modify_test.go b/x/token/internal/keeper/modify_test.go deleted file mode 100644 index adc5092964..0000000000 --- a/x/token/internal/keeper/modify_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestModifyTokenName(t *testing.T) { - const modifiedTokenName = "modifiedTokenName" - const modifiedMeta = "modifiedMeta" - const modifiedImageURI = "modifiedImageURI" - changes := types.NewChanges( - types.NewChange("name", modifiedTokenName), - types.NewChange("meta", modifiedMeta), - types.NewChange("img_uri", modifiedImageURI), - ) - - ctx := cacheKeeper() - token := aToken(defaultContractID) - tokenWithoutPerm := aToken(defaultContractID + "2") - modifyPermission := types.NewModifyPermission() - - // Given Token And Permission - require.NoError(t, keeper.SetToken(ctx, token)) - keeper.AddPermission(ctx, addr1, modifyPermission) - - t.Log("Test to modify token") - { - // When modify token name - require.NoError(t, keeper.ModifyToken(ctx, addr1, changes)) - - // Then token name is modified - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenKey(token.GetContractID())) - actual := keeper.mustDecodeToken(bz) - require.Equal(t, modifiedTokenName, actual.GetName()) - } - t.Log("Test with nonexistent contract") - { - // Given nonexistent contractID - nonExistentcontractID := "abcd1234" - - // When modify token name with invalid contractID, Then error is occurred - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, nonExistentcontractID)) - require.EqualError(t, keeper.ModifyToken(ctx2, addr1, changes), - sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s", nonExistentcontractID).Error()) - } - t.Log("Test without permission") - { - // Given Token without Permission - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, defaultContractID+"2")) - require.NoError(t, keeper.SetToken(ctx2, tokenWithoutPerm)) - invalidPerm := types.NewModifyPermission() - - // When modify token name with invalid permission, Then error is occurred - require.EqualError(t, keeper.ModifyToken(ctx2, addr1, changes), - sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr1.String(), invalidPerm.String()).Error()) - } -} - -func aToken(contractID string) types.Token { - return types.NewToken(contractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) -} diff --git a/x/token/internal/keeper/msg_encoder.go b/x/token/internal/keeper/msg_encoder.go deleted file mode 100644 index 0478f0f86f..0000000000 --- a/x/token/internal/keeper/msg_encoder.go +++ /dev/null @@ -1,134 +0,0 @@ -package keeper - -// import ( -// "encoding/json" - -// sdk "github.com/cosmos/cosmos-sdk/types" -// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -// "github.com/line/lbm-sdk/v2/x/token/internal/types" -// "github.com/line/lbm-sdk/v2/x/wasm" -// ) - -// func NewMsgEncodeHandler(tokenKeeper Keeper) wasm.EncodeHandler { -// return func(jsonMsg json.RawMessage) ([]sdk.Msg, error) { -// var wasmCustomMsg types.WasmCustomMsg -// err := json.Unmarshal(jsonMsg, &wasmCustomMsg) -// if err != nil { -// return nil, err -// } -// switch types.MsgRoute(wasmCustomMsg.Route) { -// case types.RIssue: -// return handleMsgIssue(wasmCustomMsg.Data) -// case types.RTransfer: -// return handleMsgTransfer(wasmCustomMsg.Data) -// case types.RTransferFrom: -// return handleMsgTransferFrom(wasmCustomMsg.Data) -// case types.RMint: -// return handleMsgMint(wasmCustomMsg.Data) -// case types.RBurn: -// return handleMsgBurn(wasmCustomMsg.Data) -// case types.RBurnFrom: -// return handleMsgBurnFrom(wasmCustomMsg.Data) -// case types.RGrantPerm: -// return handleMsgGrantPerm(wasmCustomMsg.Data) -// case types.RRevokePerm: -// return handleMsgRevokePerm(wasmCustomMsg.Data) -// case types.RModify: -// return handleMsgModify(wasmCustomMsg.Data) -// case types.RApprove: -// return handleMsgApprove(wasmCustomMsg.Data) -// default: -// return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized Msg route: %T", wasmCustomMsg.Route) -// } -// } -// } - -// func handleMsgIssue(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgIssue -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgTransfer(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgTransfer -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgTransferFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgTransferFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgMint(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgMint -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgBurn(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgBurn -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgBurnFrom(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgBurnFrom -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgGrantPerm(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgGrantPermission -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgRevokePerm(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgRevokePermission -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgModify(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgModify -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } - -// func handleMsgApprove(msgData json.RawMessage) ([]sdk.Msg, error) { -// var msg types.MsgApprove -// err := json.Unmarshal(msgData, &msg) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// return []sdk.Msg{msg}, nil -// } diff --git a/x/token/internal/keeper/msg_encoder_test.go b/x/token/internal/keeper/msg_encoder_test.go deleted file mode 100644 index 6571c1e661..0000000000 --- a/x/token/internal/keeper/msg_encoder_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package keeper - -// import ( -// "encoding/json" -// "fmt" -// "testing" - -// sdk "github.com/cosmos/cosmos-sdk/types" -// "github.com/line/lbm-sdk/v2/x/token/internal/types" -// "github.com/stretchr/testify/assert" -// "github.com/stretchr/testify/require" -// ) - -// func Test_Encode(t *testing.T) { -// encodeHandler := NewMsgEncodeHandler(keeper) -// jsonMsg := json.RawMessage(`{"foo": 123}`) - -// testContractID := "test_contract_id" -// issue := fmt.Sprintf(`{"route":"issue", "data":{"owner":"%s","to":"%s","name":"TestToken1","symbol":"TT1","img_uri":"","meta":"","amount":"1000","mintable":true,"decimals":"18"}}`, addr1.String(), addr2.String()) -// issueMsg := json.RawMessage(issue) -// transfer := fmt.Sprintf(`{"route":"transfer", "data":{"from":"%s", "contract_id":"%s", "to":"%s", "amount":"100"}}`, addr1.String(), testContractID, addr2.String()) -// transferMsg := json.RawMessage(transfer) -// transferFrom := fmt.Sprintf(`{"route":"transfer_from", "data":{"proxy":"%s", "from":"%s", "contract_id":"%s", "to":"%s", "amount":"100"}}`, addr3.String(), addr1.String(), testContractID, addr2.String()) -// transferFromMsg := json.RawMessage(transferFrom) -// mint := fmt.Sprintf(`{"route":"mint", "data":{"from":"%s", "contract_id":"%s", "to":"%s", "amount":"100"}}`, addr1.String(), testContractID, addr2.String()) -// mintMsg := json.RawMessage(mint) -// burn := fmt.Sprintf(`{"route":"burn", "data":{"from":"%s", "contract_id":"%s", "amount":"5"}}`, addr1.String(), testContractID) -// burnMsg := json.RawMessage(burn) -// burnFrom := fmt.Sprintf(`{"route":"burn_from", "data":{"proxy":"%s", "from":"%s", "contract_id":"%s", "amount":"5"}}`, addr2.String(), addr1.String(), testContractID) -// burnFromMsg := json.RawMessage(burnFrom) - -// grantPermission := fmt.Sprintf(`{"route":"grant_perm", "data":{"from":"%s", "contract_id":"%s", "to":"%s", "permission":"mint"}}`, addr1.String(), testContractID, addr2.String()) -// grantPermissionMsg := json.RawMessage(grantPermission) -// revokePermission := fmt.Sprintf(`{"route":"revoke_perm", "data":{"from":"%s", "contract_id":"%s", "permission":"mint"}}`, addr1.String(), testContractID) -// revokePermissionMsg := json.RawMessage(revokePermission) -// modify := fmt.Sprintf(`{"route":"modify","data":{"owner":"%s","contract_id":"%s","changes":[{"field":"meta","value":"update_meta"}]}}`, addr1.String(), testContractID) -// modifyMsg := json.RawMessage(modify) -// approver := fmt.Sprintf(`{"route":"approve", "data":{"approver":"%s", "contract_id":"%s", "proxy":"%s"}}`, addr1.String(), testContractID, addr2.String()) -// approverMsg := json.RawMessage(approver) - -// changes := types.NewChanges(types.NewChange("meta", "update_meta")) - -// cases := map[string]struct { -// input json.RawMessage -// // set if valid -// output []sdk.Msg -// // set if invalid -// isError bool -// }{ -// "issue token": { -// input: issueMsg, -// output: []sdk.Msg{ -// types.MsgIssue{ -// Owner: addr1, -// To: addr2, -// Name: "TestToken1", -// Symbol: "TT1", -// ImageURI: "", -// Meta: "", -// Amount: sdk.NewInt(1000), -// Mintable: true, -// Decimals: sdk.NewInt(18), -// }, -// }, -// }, -// "transfer token": { -// input: transferMsg, -// output: []sdk.Msg{ -// types.MsgTransfer{ -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// Amount: sdk.NewInt(100), -// }, -// }, -// }, -// "transfer from token": { -// input: transferFromMsg, -// output: []sdk.Msg{ -// types.MsgTransferFrom{ -// Proxy: addr3, -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// Amount: sdk.NewInt(100), -// }, -// }, -// }, -// "mint token": { -// input: mintMsg, -// output: []sdk.Msg{ -// types.MsgMint{ -// From: addr1, -// ContractID: testContractID, -// To: addr2, -// Amount: sdk.NewInt(100), -// }, -// }, -// }, -// "burn token": { -// input: burnMsg, -// output: []sdk.Msg{ -// types.NewMsgBurn(addr1, testContractID, sdk.NewInt(5)), -// }, -// }, -// "burn from token": { -// input: burnFromMsg, -// output: []sdk.Msg{ -// types.NewMsgBurnFrom(addr2, testContractID, addr1, sdk.NewInt(5)), -// }, -// }, -// "grant permission": { -// input: grantPermissionMsg, -// output: []sdk.Msg{ -// types.NewMsgGrantPermission(addr1, testContractID, addr2, types.Permission("mint")), -// }, -// }, -// "revoke permission": { -// input: revokePermissionMsg, -// output: []sdk.Msg{ -// types.NewMsgRevokePermission(addr1, testContractID, types.Permission("mint")), -// }, -// }, -// "modify token": { -// input: modifyMsg, -// output: []sdk.Msg{ -// types.NewMsgModify(addr1, testContractID, changes), -// }, -// }, -// "approve": { -// input: approverMsg, -// output: []sdk.Msg{ -// types.NewMsgApprove(addr1, testContractID, addr2), -// }, -// }, -// "unknown custom msg": { -// input: jsonMsg, -// isError: true, -// }, -// } - -// for name, tc := range cases { -// tc := tc -// t.Run(name, func(t *testing.T) { -// res, err := encodeHandler(tc.input) -// if tc.isError { -// require.Error(t, err) -// } else { -// require.NoError(t, err) -// assert.Equal(t, tc.output, res) -// } -// }) -// } -// } diff --git a/x/token/internal/keeper/perm.go b/x/token/internal/keeper/perm.go deleted file mode 100644 index 802dde55d9..0000000000 --- a/x/token/internal/keeper/perm.go +++ /dev/null @@ -1,91 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) AddPermission(ctx sdk.Context, addr sdk.AccAddress, perm types.Permission) { - accPerm := k.getAccountPermission(ctx, addr) - accPerm.AddPermission(perm) - k.setAccountPermission(ctx, accPerm) -} - -func (k Keeper) HasPermission(ctx sdk.Context, addr sdk.AccAddress, p types.Permission) bool { - accPerm := k.getAccountPermission(ctx, addr) - return accPerm.HasPermission(p) -} - -func (k Keeper) GetPermissions(ctx sdk.Context, addr sdk.AccAddress) types.Permissions { - accPerm := k.getAccountPermission(ctx, addr) - return accPerm.GetPermissions() -} - -func (k Keeper) RevokePermission(ctx sdk.Context, addr sdk.AccAddress, perm types.Permission) error { - if !k.HasPermission(ctx, addr, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", addr.String(), perm.String()) - } - accPerm := k.getAccountPermission(ctx, addr) - accPerm.RemovePermission(perm) - k.setAccountPermission(ctx, accPerm) - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeRevokePermToken, - sdk.NewAttribute(types.AttributeKeyFrom, addr.String()), - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyPerm, perm.String()), - ), - }) - return nil -} - -func (k Keeper) GrantPermission(ctx sdk.Context, from, to sdk.AccAddress, perm types.Permission) error { - if !k.HasPermission(ctx, from, perm) { - return sdkerrors.Wrapf(types.ErrTokenNoPermission, "Account: %s, Permission: %s", from.String(), perm.String()) - } - k.AddPermission(ctx, to, perm) - - // Set Account if not exists yet - account := k.accountKeeper.GetAccount(ctx, to) - if account == nil { - account = k.accountKeeper.NewAccountWithAddress(ctx, to) - k.accountKeeper.SetAccount(ctx, account) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeGrantPermToken, - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyPerm, perm.String()), - ), - }) - - return nil -} - -func (k Keeper) getAccountPermission(ctx sdk.Context, addr sdk.AccAddress) (accPerm types.AccountPermissionI) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.PermKey(k.getContractID(ctx), addr)) - if bz != nil { - accPerm = k.mustDecodeAccountPermission(bz) - return accPerm - } - return types.NewAccountPermission(addr) -} - -func (k Keeper) setAccountPermission(ctx sdk.Context, accPerm types.AccountPermissionI) { - store := ctx.KVStore(k.storeKey) - store.Set(types.PermKey(k.getContractID(ctx), accPerm.GetAddress()), k.cdc.MustMarshalBinaryBare(accPerm)) -} - -func (k Keeper) mustDecodeAccountPermission(bz []byte) (accPerm types.AccountPermissionI) { - err := k.cdc.UnmarshalBinaryBare(bz, &accPerm) - if err != nil { - panic(err) - } - return -} diff --git a/x/token/internal/keeper/perm_test.go b/x/token/internal/keeper/perm_test.go deleted file mode 100644 index df0b5b71c1..0000000000 --- a/x/token/internal/keeper/perm_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func preparePermissions(ctx sdk.Context, t *testing.T) types.Permissions { - expected := types.Permissions{ - types.NewMintPermission(), - types.NewBurnPermission(), - } - t.Log("Prepare Permissions") - { - for _, perm := range expected { - keeper.AddPermission(ctx, addr1, perm) - } - } - return expected -} - -func TestKeeper_GetPermissions(t *testing.T) { - ctx = cacheKeeper() - expected := preparePermissions(ctx, t) - - t.Log("Compare Permissions") - { - actual := keeper.GetPermissions(ctx, addr1) - for index := range actual { - require.Equal(t, expected[index].String(), actual[index].String()) - } - } -} - -func TestKeeper_AddPermission(t *testing.T) { - ctx = cacheKeeper() - keeper.AddPermission(ctx, addr1, types.NewMintPermission()) - keeper.AddPermission(ctx, addr1, types.NewBurnPermission()) - keeper.AddPermission(ctx, addr1, types.NewModifyPermission()) - require.Equal(t, 3, len(keeper.GetPermissions(ctx, addr1))) -} - -func TestKeeper_GrantPermission(t *testing.T) { - ctx = cacheKeeper() - expected := preparePermissions(ctx, t) - t.Log("Grant Permissions addr1 -> addr2") - { - for _, perm := range expected { - err := keeper.GrantPermission(ctx, addr1, addr2, perm) - require.NoError(t, err) - } - } - t.Log("Grant Permission. addr1 has not the permission") - { - err := keeper.GrantPermission(ctx, addr1, addr2, types.NewModifyPermission()) - require.Error(t, err) - } -} - -func TestKeeper_RevokePermission(t *testing.T) { - ctx = cacheKeeper() - expected := preparePermissions(ctx, t) - t.Log("Revoke Permissions addr1") - { - for _, perm := range expected { - err := keeper.RevokePermission(ctx, addr1, perm) - require.NoError(t, err) - } - } - t.Log("Revoke Permission. addr1 has not the permission") - { - err := keeper.RevokePermission(ctx, addr1, types.NewModifyPermission()) - require.Error(t, err) - } -} - -func TestKeeper_HasPermission(t *testing.T) { - ctx = cacheKeeper() - expected := preparePermissions(ctx, t) - t.Log("Has Permissions addr1") - { - for _, perm := range expected { - require.True(t, keeper.HasPermission(ctx, addr1, perm)) - } - } - t.Log("Revoke Permission. addr1 has not the permission") - { - require.False(t, keeper.HasPermission(ctx, addr1, types.NewModifyPermission())) - } -} diff --git a/x/token/internal/keeper/proxy.go b/x/token/internal/keeper/proxy.go deleted file mode 100644 index 89f71fa734..0000000000 --- a/x/token/internal/keeper/proxy.go +++ /dev/null @@ -1,89 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -var ( - ApprovedValue = []byte{0x01} -) - -type ProxyKeeper interface { - IsApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) bool - SetApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) error - DeleteApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) error -} - -func (k Keeper) IsApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) bool { - store := ctx.KVStore(k.storeKey) - approvedKey := types.TokenApprovedKey(k.getContractID(ctx), proxy, approver) - return store.Has(approvedKey) -} - -func (k Keeper) SetApproved(ctx sdk.Context, proxy sdk.AccAddress, approver sdk.AccAddress) error { - store := ctx.KVStore(k.storeKey) - if !store.Has(types.TokenKey(k.getContractID(ctx))) { - return sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s", k.getContractID(ctx)) - } - - approvedKey := types.TokenApprovedKey(k.getContractID(ctx), proxy, approver) - if store.Has(approvedKey) { - return sdkerrors.Wrapf(types.ErrTokenAlreadyApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), approver.String(), k.getContractID(ctx)) - } - store.Set(approvedKey, ApprovedValue) - - // Set Account if not exists yet - account := k.accountKeeper.GetAccount(ctx, proxy) - if account == nil { - account = k.accountKeeper.NewAccountWithAddress(ctx, proxy) - k.accountKeeper.SetAccount(ctx, account) - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeApproveToken, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyApprover, approver.String()), - ), - }) - - return nil -} - -func (k Keeper) GetApprovers(ctx sdk.Context, proxy sdk.AccAddress) (accAds []sdk.AccAddress, err error) { - _, err = k.GetToken(ctx) - if err != nil { - return nil, err - } - k.iterateApprovers(ctx, proxy, false, func(address sdk.AccAddress) bool { - accAds = append(accAds, address) - return false - }) - return accAds, nil -} - -func (k Keeper) iterateApprovers(ctx sdk.Context, prefix sdk.AccAddress, reverse bool, process func(accAd sdk.AccAddress) bool) { - store := ctx.KVStore(k.storeKey) - prefixKey := types.TokenApproversKey(k.getContractID(ctx), prefix) - var iter sdk.Iterator - if reverse { - iter = sdk.KVStoreReversePrefixIterator(store, prefixKey) - } else { - iter = sdk.KVStorePrefixIterator(store, prefixKey) - } - defer iter.Close() - for { - if !iter.Valid() { - return - } - bz := iter.Key() - approver := bz[len(prefixKey):] - if process(approver) { - return - } - iter.Next() - } -} diff --git a/x/token/internal/keeper/proxy_test.go b/x/token/internal/keeper/proxy_test.go deleted file mode 100644 index cee62e4a3e..0000000000 --- a/x/token/internal/keeper/proxy_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestApproveScenario(t *testing.T) { - ctx := cacheKeeper() - - // prepare token - someToken := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.IssueToken(ctx, someToken, sdk.NewInt(defaultAmount), addr1, addr1)) - - // approve test - anotherCtx := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, anotherContractID)) - require.EqualError(t, keeper.SetApproved(anotherCtx, addr3, addr1), sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s", anotherContractID).Error()) - require.NoError(t, keeper.SetApproved(ctx, addr3, addr1)) - require.EqualError(t, keeper.SetApproved(ctx, addr3, addr1), sdkerrors.Wrapf(types.ErrTokenAlreadyApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr3.String(), addr1.String(), defaultContractID).Error()) - - // transfer_from test - require.EqualError(t, keeper.TransferFrom(ctx, addr2, addr1, addr2, sdk.NewInt(10)), sdkerrors.Wrapf(types.ErrTokenNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", addr2.String(), addr1.String(), defaultContractID).Error()) - require.NoError(t, keeper.TransferFrom(ctx, addr3, addr1, addr2, sdk.NewInt(10))) - - t.Log("add one more approver fo test") - { - require.NoError(t, keeper.SetApproved(ctx, addr3, addr2)) - } - - t.Log("succeed to GetApprovers") - { - approvers, err := keeper.GetApprovers(ctx, addr3) - require.NoError(t, err) - require.True(t, len(approvers) == 2) - require.True(t, types.IsAddressContains(approvers, addr1)) - require.True(t, types.IsAddressContains(approvers, addr2)) - } - - t.Log("fail to GetApprovres") - { - _, err := keeper.GetApprovers(anotherCtx, addr3) - require.Error(t, err, "") - } -} diff --git a/x/token/internal/keeper/supply.go b/x/token/internal/keeper/supply.go deleted file mode 100644 index 82cae5b786..0000000000 --- a/x/token/internal/keeper/supply.go +++ /dev/null @@ -1,112 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -type SupplyKeeper interface { - GetTotalInt(ctx sdk.Context, target string) (sdk.Int, error) - MintSupply(ctx sdk.Context, to sdk.AccAddress, amount sdk.Int) error - BurnSupply(ctx sdk.Context, from sdk.AccAddress, amount sdk.Int) error -} - -var _ SupplyKeeper = (*Keeper)(nil) - -func (k Keeper) GetTotalInt(ctx sdk.Context, target string) (sdk.Int, error) { - supply, err := k.getSupply(ctx) - if err != nil { - return sdk.ZeroInt(), err - } - - switch target { - case types.QuerySupply: - return supply.GetTotalSupply(), nil - case types.QueryBurn: - return supply.GetTotalBurn(), nil - case types.QueryMint: - return supply.GetTotalMint(), nil - default: - return sdk.ZeroInt(), sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid request target to query total %s", target) - } -} - -func (k Keeper) getSupply(ctx sdk.Context) (supply types.Supply, err error) { - if _, err := k.GetToken(ctx); err != nil { - return nil, err - } - store := ctx.KVStore(k.storeKey) - b := store.Get(types.SupplyKey(k.getContractID(ctx))) - if b == nil { - panic("stored supply should not have been nil") - } - k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &supply) - return -} - -func (k Keeper) setSupply(ctx sdk.Context, supply types.Supply) { - if k.getContractID(ctx) != supply.GetContractID() { - panic("cannot set supply with different contract id") - } - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryLengthPrefixed(supply) - store.Set(types.SupplyKey(k.getContractID(ctx)), b) -} - -func (k Keeper) MintSupply(ctx sdk.Context, to sdk.AccAddress, amount sdk.Int) (err error) { - defer func() { - // to recover from overflows - if r := recover(); r != nil { - err = types.WrapIfOverflowPanic(r) - } - }() - - _, err = k.addBalance(ctx, to, amount) - if err != nil { - return err - } - - supply, err := k.getSupply(ctx) - if err != nil { - return err - } - oldSupplyAmount := supply.GetTotalSupply() - newSupplyAmount := oldSupplyAmount.Add(amount) - if newSupplyAmount.IsNegative() { - return sdkerrors.Wrapf(types.ErrInsufficientSupply, "insufficient supply for token [%s]; %s < %s", k.getContractID(ctx), oldSupplyAmount, amount) - } - supply = supply.Inflate(amount) - k.setSupply(ctx, supply) - - return nil -} - -func (k Keeper) BurnSupply(ctx sdk.Context, from sdk.AccAddress, amount sdk.Int) (err error) { - defer func() { - // to recover from overflows - // however, it will return insufficient fund error instead of panicking in the case - if r := recover(); r != nil { - err = types.WrapIfOverflowPanic(r) - } - }() - - _, err = k.subtractBalance(ctx, from, amount) - if err != nil { - return err - } - - supply, err := k.getSupply(ctx) - if err != nil { - return err - } - oldSupplyAmount := supply.GetTotalSupply() - newSupplyAmount := oldSupplyAmount.Sub(amount) - if newSupplyAmount.IsNegative() { - return sdkerrors.Wrapf(types.ErrInsufficientSupply, "insufficient supply for token [%s]; %s < %s", k.getContractID(ctx), oldSupplyAmount, amount) - } - supply = supply.Deflate(amount) - k.setSupply(ctx, supply) - - return nil -} diff --git a/x/token/internal/keeper/supply_test.go b/x/token/internal/keeper/supply_test.go deleted file mode 100644 index f48269c04c..0000000000 --- a/x/token/internal/keeper/supply_test.go +++ /dev/null @@ -1,219 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func verifySupplyFunc(t *testing.T, expected types.Supply, actual types.Supply) { - require.Equal(t, expected.GetContractID(), actual.GetContractID()) - require.Equal(t, expected.GetTotalSupply().Int64(), actual.GetTotalSupply().Int64()) -} - -func TestKeeper_GetTotalInt(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Supply and Token") - expected := types.DefaultSupply(defaultContractID) - { - store := ctx.KVStore(keeper.storeKey) - b := keeper.cdc.MustMarshalBinaryLengthPrefixed(expected) - store.Set(types.SupplyKey(expected.GetContractID()), b) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - store.Set(types.TokenKey(expected.GetContractID()), keeper.cdc.MustMarshalBinaryBare(token)) - } - t.Log("Get Supply") - { - actual, err := keeper.getSupply(ctx) - require.NoError(t, err) - verifySupplyFunc(t, expected, actual) - } - t.Log("Get Total Supply Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, expected.GetTotalSupply().Int64(), actual.Int64()) - } - t.Log("Get Total Mint Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QueryMint) - require.NoError(t, err) - require.Equal(t, expected.GetTotalMint().Int64(), actual.Int64()) - } - t.Log("Get Total Burn Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, expected.GetTotalBurn().Int64(), actual.Int64()) - } -} - -func TestKeeper_MintSupply(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.SetToken(ctx, token)) - } - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Mint Supply") - { - require.NoError(t, keeper.MintSupply(ctx, addr1, sdk.NewInt(defaultAmount))) - } - t.Log("Get Balance") - { - balance := keeper.GetBalance(ctx, addr1) - require.Equal(t, sdk.NewInt(defaultAmount).Int64(), balance.Int64()) - } - t.Log("Get Total Supply Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount), actual) - } - t.Log("Get Total Mint Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QueryMint) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount), actual) - } - t.Log("Get Total Burn Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, sdk.ZeroInt(), actual) - } -} - -func TestKeeper_BurnSupply(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.SetToken(ctx, token)) - } - t.Log("Set Account") - acc := types.NewBaseAccountWithAddress(defaultContractID, addr1) - { - require.NoError(t, keeper.SetAccount(ctx, acc)) - } - t.Log("Set Balance And Supply") - { - require.NoError(t, keeper.SetBalance(ctx, addr1, sdk.NewInt(defaultAmount))) - keeper.setSupply(ctx, types.DefaultSupply(defaultContractID).SetTotalSupply(sdk.NewInt(defaultAmount))) - } - t.Log("Burn Supply") - { - require.NoError(t, keeper.BurnSupply(ctx, addr1, sdk.NewInt(defaultAmount))) - } - t.Log("Get Balance") - { - balance := keeper.GetBalance(ctx, addr1) - require.Equal(t, sdk.ZeroInt().Int64(), balance.Int64()) - } - t.Log("Get Total Supply Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, sdk.ZeroInt(), actual) - } - t.Log("Get Total Mint Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QueryMint) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount), actual) - } - t.Log("Get Total Burn Int") - { - actual, err := keeper.GetTotalInt(ctx, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, sdk.NewInt(defaultAmount), actual) - } -} - -func TestKeeper_Handle_Overflows(t *testing.T) { - ctx := cacheKeeper() - - t.Log("Prepare Supply and Token") - expected := types.DefaultSupply(defaultContractID) - { - store := ctx.KVStore(keeper.storeKey) - b := keeper.cdc.MustMarshalBinaryLengthPrefixed(expected) - store.Set(types.SupplyKey(expected.GetContractID()), b) - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultImageURI, defaultMeta, sdk.NewInt(defaultDecimals), true) - store.Set(types.TokenKey(expected.GetContractID()), keeper.cdc.MustMarshalBinaryBare(token)) - } - - // int64 is the set of all signed 64-bit integers. - // Range: -9223372036854775808 through 9223372036854775807. - - // Int wraps integer with 256 bit range bound - // Checks overflow, underflow and division by zero - // Exists in range from -(2^maxBitLen-1) to 2^maxBitLen-1 - - t.Log("Set supply less than the overflow limit") - maxInt64Supply := sdk.NewInt(9223372036854775807) - - initialSupply := maxInt64Supply.Mul(maxInt64Supply).Mul(maxInt64Supply).Mul(maxInt64Supply) - newSupply := types.NewSupply(defaultContractID, initialSupply) - keeper.setSupply(ctx, newSupply) - - ts, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalSupply(), ts) - - tm, err := keeper.GetTotalInt(ctx, types.QueryMint) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalMint(), tm) - - tb, err := keeper.GetTotalInt(ctx, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalBurn(), tb) - - // inflate over the overflow limit - t.Log("Inflate the supply over the overflow limit") - addToOverflow := initialSupply.Mul(sdk.NewInt(8)) - err = keeper.MintSupply(ctx, addr1, addToOverflow) - require.Equal(t, types.ErrSupplyOverflow, err) - - // should have not changed - t.Log("Totals have not changed") - ts, err = keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalSupply(), ts) - - tm, err = keeper.GetTotalInt(ctx, types.QueryMint) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalMint(), tm) - - tb, err = keeper.GetTotalInt(ctx, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalBurn(), tb) - - // deflate below the overflow limit - it will return insufficient fund instead of panicking - t.Log("Deflate the supply below the overflow limit - will return insufficient fund instead of panicking") - subToOverflow := initialSupply.Mul(sdk.NewInt(8)) - err = keeper.BurnSupply(ctx, addr1, subToOverflow) - require.True(t, types.ErrInsufficientSupply.Is(err)) - - // should have not changed - t.Log("Totals have not changed") - ts, err = keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalSupply(), ts) - - tm, err = keeper.GetTotalInt(ctx, types.QueryMint) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalMint(), tm) - - tb, err = keeper.GetTotalInt(ctx, types.QueryBurn) - require.NoError(t, err) - require.Equal(t, newSupply.GetTotalBurn(), tb) -} diff --git a/x/token/internal/keeper/test_common.go b/x/token/internal/keeper/test_common.go deleted file mode 100644 index 4463b8dbfb..0000000000 --- a/x/token/internal/keeper/test_common.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestKeeper() (sdk.Context, store.CommitMultiStore, Keeper) { - keyAuth := sdk.NewKVStoreKey(auth.StoreKey) - keyParams := sdk.NewKVStoreKey(params.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) - keyToken := sdk.NewKVStoreKey(types.StoreKey) - keyContract := sdk.NewKVStoreKey(contract.StoreKey) - - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyAuth, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyToken, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyContract, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) - if err := ms.LoadLatestVersion(); err != nil { - panic(err) - } - - cdc := codec.New() - types.RegisterCodec(cdc) - auth.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - cdc.Seal() - - paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams) - authSubspace := paramsKeeper.Subspace(auth.DefaultParamspace) - - // add keepers - accountKeeper := auth.NewAccountKeeper(cdc, keyAuth, authSubspace, auth.ProtoBaseAccount) - keeper := NewKeeper(cdc, accountKeeper, contract.NewContractKeeper(cdc, keyContract), keyToken) - ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) - - return ctx, ms, keeper -} diff --git a/x/token/internal/keeper/token.go b/x/token/internal/keeper/token.go deleted file mode 100644 index 91c03c3aaa..0000000000 --- a/x/token/internal/keeper/token.go +++ /dev/null @@ -1,79 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) GetToken(ctx sdk.Context) (types.Token, error) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.TokenKey(k.getContractID(ctx))) - if bz == nil { - return nil, sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s", k.getContractID(ctx)) - } - return k.mustDecodeToken(bz), nil -} - -func (k Keeper) SetToken(ctx sdk.Context, token types.Token) error { - if k.getContractID(ctx) != token.GetContractID() { - panic("cannot set token with different contract id") - } - store := ctx.KVStore(k.storeKey) - tokenKey := types.TokenKey(k.getContractID(ctx)) - if store.Has(tokenKey) { - return sdkerrors.Wrapf(types.ErrTokenExist, "ContractID: %s", k.getContractID(ctx)) - } - store.Set(tokenKey, k.cdc.MustMarshalBinaryBare(token)) - - k.setSupply(ctx, types.DefaultSupply(token.GetContractID())) - - return nil -} - -func (k Keeper) UpdateToken(ctx sdk.Context, token types.Token) error { - if k.getContractID(ctx) != token.GetContractID() { - panic("cannot update token with different contract id") - } - store := ctx.KVStore(k.storeKey) - tokenKey := types.TokenKey(k.getContractID(ctx)) - if !store.Has(tokenKey) { - return sdkerrors.Wrapf(types.ErrTokenNotExist, "ContractID: %s", k.getContractID(ctx)) - } - store.Set(tokenKey, k.cdc.MustMarshalBinaryBare(token)) - return nil -} - -func (k Keeper) GetAllTokens(ctx sdk.Context) (tokens types.Tokens) { - appendToken := func(token types.Token) (stop bool) { - tokens = append(tokens, token) - return false - } - k.iterateTokens(ctx, "", appendToken) - return tokens -} - -func (k Keeper) iterateTokens(ctx sdk.Context, prefix string, process func(types.Token) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.TokenKey(prefix)) - defer iter.Close() - for { - if !iter.Valid() { - return - } - val := iter.Value() - token := k.mustDecodeToken(val) - if process(token) { - return - } - iter.Next() - } -} - -func (k Keeper) mustDecodeToken(tokenByte []byte) (token types.Token) { - err := k.cdc.UnmarshalBinaryBare(tokenByte, &token) - if err != nil { - panic(err) - } - return token -} diff --git a/x/token/internal/keeper/token_test.go b/x/token/internal/keeper/token_test.go deleted file mode 100644 index 81b079933f..0000000000 --- a/x/token/internal/keeper/token_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_GetToken(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Token") - expected := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - { - store := ctx.KVStore(keeper.storeKey) - store.Set(types.TokenKey(expected.GetContractID()), keeper.cdc.MustMarshalBinaryBare(expected)) - } - t.Log("Get Token") - { - actual, err := keeper.GetToken(ctx) - require.NoError(t, err) - verifyTokenFunc(t, expected, actual) - } -} - -func TestKeeper_SetToken(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Token") - expected := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.SetToken(ctx, expected)) - } - t.Log("Compare Token") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenKey(expected.GetContractID())) - actual := keeper.mustDecodeToken(bz) - verifyTokenFunc(t, expected, actual) - } -} - -func TestKeeper_UpdateToken(t *testing.T) { - ctx := cacheKeeper() - t.Log("Set Token") - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.SetToken(ctx, token)) - } - t.Log("Update Token") - expected := types.NewToken(token.GetContractID(), "modifiedname", "BTC", "{}", "modifiedtokenuri", sdk.NewInt(defaultDecimals), true) - { - require.NoError(t, keeper.UpdateToken(ctx, expected)) - } - t.Log("Compare Token") - { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(types.TokenKey(token.GetContractID())) - actual := keeper.mustDecodeToken(bz) - verifyTokenFunc(t, expected, actual) - } -} - -func TestKeeper_GetAllTokens(t *testing.T) { - ctx := cacheKeeper() - t.Log("Prepare Tokens") - expected := types.Tokens{ - types.NewToken(defaultContractID+"1", defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true), - types.NewToken(defaultContractID+"2", defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true), - types.NewToken(defaultContractID+"3", defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true), - types.NewToken(defaultContractID+"4", defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true), - } - { - store := ctx.KVStore(keeper.storeKey) - for _, t := range expected { - store.Set(types.TokenKey(t.GetContractID()), keeper.cdc.MustMarshalBinaryBare(t)) - } - } - t.Log("Compare Tokens") - { - actual := keeper.GetAllTokens(ctx) - for index := range expected { - verifyTokenFunc(t, expected[index], actual[index]) - } - } -} diff --git a/x/token/internal/keeper/transfer.go b/x/token/internal/keeper/transfer.go deleted file mode 100644 index 0473e9c067..0000000000 --- a/x/token/internal/keeper/transfer.go +++ /dev/null @@ -1,54 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/coin" - "github.com/line/lbm-sdk/v2/x/token/internal/types" -) - -func (k Keeper) Transfer(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, amount sdk.Int) error { - // reject if to address is blacklisted (safety box addresses) - if k.IsBlacklisted(ctx, to, coin.ActionTransferTo) { - return sdkerrors.Wrapf(coin.ErrCanNotTransferToBlacklisted, "Addr: %s", to.String()) - } - - err := k.Send(ctx, from, to, amount) - if err != nil { - return err - } - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransfer, - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - ), - }) - - return nil -} - -func (k Keeper) TransferFrom(ctx sdk.Context, proxy sdk.AccAddress, from sdk.AccAddress, to sdk.AccAddress, amount sdk.Int) error { - if !k.IsApproved(ctx, proxy, from) { - return sdkerrors.Wrapf(types.ErrTokenNotApproved, "Proxy: %s, Approver: %s, ContractID: %s", proxy.String(), from.String(), k.getContractID(ctx)) - } - - if err := k.Send(ctx, from, to, amount); err != nil { - return err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransferFrom, - sdk.NewAttribute(types.AttributeKeyContractID, k.getContractID(ctx)), - sdk.NewAttribute(types.AttributeKeyProxy, proxy.String()), - sdk.NewAttribute(types.AttributeKeyFrom, from.String()), - sdk.NewAttribute(types.AttributeKeyTo, to.String()), - sdk.NewAttribute(types.AttributeKeyAmount, amount.String()), - ), - }) - - return nil -} diff --git a/x/token/internal/keeper/transfer_test.go b/x/token/internal/keeper/transfer_test.go deleted file mode 100644 index 826758ebff..0000000000 --- a/x/token/internal/keeper/transfer_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_Transfer(t *testing.T) { - ctx := cacheKeeper() - t.Log("Issue Token") - { - token := types.NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - require.NoError(t, keeper.IssueToken(ctx, token, sdk.NewInt(defaultAmount), addr1, addr1)) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } - t.Log("Balance of Account 1") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } - t.Log("Balance of Account 2") - { - supply := keeper.GetBalance(ctx, addr2) - require.Equal(t, int64(0), supply.Int64()) - } - t.Log("Transfer Token") - { - err := keeper.Transfer(ctx, addr1, addr2, sdk.NewInt(defaultAmount)) - require.NoError(t, err) - } - t.Log("TotalSupply supply") - { - supply, err := keeper.GetTotalInt(ctx, types.QuerySupply) - require.NoError(t, err) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } - t.Log("Balance of Account 1") - { - supply := keeper.GetBalance(ctx, addr1) - require.Equal(t, int64(0), supply.Int64()) - } - t.Log("Balance of Account 2") - { - supply := keeper.GetBalance(ctx, addr2) - require.Equal(t, int64(defaultAmount), supply.Int64()) - } -} diff --git a/x/token/internal/legacy/upgrade.go b/x/token/internal/legacy/upgrade.go deleted file mode 100644 index 177ded52c9..0000000000 --- a/x/token/internal/legacy/upgrade.go +++ /dev/null @@ -1,13 +0,0 @@ -package legacy - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/upgrade" -) - -func UpgradeHandler(version string) upgrade.UpgradeHandler { - // XXX: return handler for the migration version - return func(ctx sdk.Context, plan upgrade.Plan) { - - } -} diff --git a/x/token/internal/querier/querier.go b/x/token/internal/querier/querier.go deleted file mode 100644 index eea6a7396d..0000000000 --- a/x/token/internal/querier/querier.go +++ /dev/null @@ -1,150 +0,0 @@ -package querier - -import ( - "context" - - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - abci "github.com/tendermint/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// creates a querier for token REST endpoints -func NewQuerier(keeper keeper.Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - if len(path) >= 2 { - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, path[1])) - } - switch path[0] { - case types.QueryPerms: - return queryAccountPermission(ctx, req, keeper) - case types.QueryTokens: - return queryTokens(ctx, req, keeper) - case types.QueryBalance: - return queryBalance(ctx, req, keeper) - case types.QueryMint: - return queryTotal(ctx, req, keeper, types.QueryMint) - case types.QueryBurn: - return queryTotal(ctx, req, keeper, types.QueryBurn) - case types.QuerySupply: - return queryTotal(ctx, req, keeper, types.QuerySupply) - case types.QueryIsApproved: - return queryIsApproved(ctx, req, keeper) - case types.QueryApprovers: - return queryApprovers(ctx, req, keeper) - default: - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown token query endpoint") - } - } -} - -func queryBalance(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - if len(req.Data) == 0 { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "data is nil") - } - var params types.QueryContractIDAccAddressParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - supply := keeper.GetBalance(ctx, params.Addr) - bz, err := keeper.MarshalJSONIndent(supply) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryAccountPermission(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - if len(req.Data) == 0 { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "data is nil") - } - var params types.QueryContractIDAccAddressParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - pms := keeper.GetPermissions(ctx, params.Addr) - - bz, err := keeper.MarshalJSONIndent(pms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryTokens(ctx sdk.Context, _ abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - if ctx.Context().Value(contract.CtxKey{}) == nil { - tokens := keeper.GetAllTokens(ctx) - - bz, err := keeper.MarshalJSONIndent(tokens) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - } - token, err := keeper.GetToken(ctx) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(token) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryTotal(ctx sdk.Context, _ abci.RequestQuery, keeper keeper.Keeper, target string) ([]byte, error) { - total, err := keeper.GetTotalInt(ctx, target) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(total) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} - -func queryIsApproved(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryIsApprovedParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - approved := keeper.IsApproved(ctx, params.Proxy, params.Approver) - - bz, err := keeper.MarshalJSONIndent(approved) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryApprovers(ctx sdk.Context, req abci.RequestQuery, keeper keeper.Keeper) ([]byte, error) { - var params types.QueryProxyParams - if err := keeper.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - approvers, err := keeper.GetApprovers(ctx, params.Proxy) - if err != nil { - return nil, err - } - - bz, err2 := keeper.MarshalJSONIndent(approvers) - if err2 != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err2.Error()) - } - - return bz, nil -} diff --git a/x/token/internal/querier/querier_encoder.go b/x/token/internal/querier/querier_encoder.go deleted file mode 100644 index 542ede1678..0000000000 --- a/x/token/internal/querier/querier_encoder.go +++ /dev/null @@ -1,154 +0,0 @@ -package querier - -// import ( -// "encoding/json" - -// "github.com/cosmos/cosmos-sdk/codec" -// sdk "github.com/cosmos/cosmos-sdk/types" -// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -// "github.com/line/lbm-sdk/v2/x/token/internal/types" -// abci "github.com/tendermint/tendermint/abci/types" - -// "github.com/line/lbm-sdk/v2/x/wasm" -// ) - -// func NewQueryEncoder(tokenQuerier sdk.Querier) wasm.EncodeQuerier { -// return func(ctx sdk.Context, jsonQuerier json.RawMessage) ([]byte, error) { -// var customQuerier types.WasmCustomQuerier -// err := json.Unmarshal(jsonQuerier, &customQuerier) -// if err != nil { -// return nil, err -// } -// switch customQuerier.Route { -// case types.QueryTokens: -// return handleQueryToken(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryBalance: -// return handleQueryBalance(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QuerySupply: -// return handleQueryTotal(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryMint: -// return handleQueryTotal(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryBurn: -// return handleQueryTotal(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryPerms: -// return handleQueryPerms(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryIsApproved: -// return handleQueryIsApproved(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// case types.QueryApprovers: -// return handleQueryApprovers(ctx, tokenQuerier, []string{customQuerier.Route}, customQuerier.Data) -// default: -// return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized Msg route: %T", customQuerier.Route) -// } -// } -// } - -// func handleQueryToken(ctx sdk.Context, tokenQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryTokenWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// req := makeRequestQuery(nil) - -// contractID := wrapper.TokenParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return tokenQuerier(ctx, path, req) -// } - -// func handleQueryBalance(ctx sdk.Context, tokenQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryBalanceWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } - -// req := makeRequestQuery(types.QueryContractIDAccAddressParams{ -// Addr: wrapper.BalanceParam.Address, -// }) - -// contractID := wrapper.BalanceParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return tokenQuerier(ctx, path, req) -// } - -// func handleQueryTotal(ctx sdk.Context, tokenQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryTotalWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } -// req := makeRequestQuery(nil) - -// contractID := wrapper.TotalParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return tokenQuerier(ctx, path, req) -// } - -// func handleQueryPerms(ctx sdk.Context, tokenQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryPermWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } - -// req := makeRequestQuery(types.QueryContractIDAccAddressParams{ -// Addr: wrapper.PermParam.Address, -// }) - -// contractID := wrapper.PermParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return tokenQuerier(ctx, path, req) -// } - -// func handleQueryIsApproved(ctx sdk.Context, tokenQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryIsApprovedWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } - -// req := makeRequestQuery(types.QueryIsApprovedParams{ -// Proxy: wrapper.IsApprovedParam.Proxy, -// Approver: wrapper.IsApprovedParam.Approver, -// }) - -// contractID := wrapper.IsApprovedParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return tokenQuerier(ctx, path, req) -// } - -// func handleQueryApprovers(ctx sdk.Context, tokenQuerier sdk.Querier, path []string, msgData json.RawMessage) ([]byte, error) { -// var wrapper types.QueryApproversWrapper -// err := json.Unmarshal(msgData, &wrapper) -// if err != nil { -// return nil, err -// } - -// req := makeRequestQuery(types.QueryProxyParams{ -// Proxy: wrapper.ApproversParam.Proxy, -// }) - -// contractID := wrapper.ApproversParam.ContractID -// if contractID != "" { -// path = append(path, contractID) -// } -// return tokenQuerier(ctx, path, req) -// } - -// func makeRequestQuery(params interface{}) abci.RequestQuery { -// req := abci.RequestQuery{ -// Path: "", -// Data: []byte(string(codec.MustMarshalJSONIndent(types.ModuleCdc, params))), -// } -// return req -// } diff --git a/x/token/internal/querier/querier_encoder_test.go b/x/token/internal/querier/querier_encoder_test.go deleted file mode 100644 index 38612fcdc5..0000000000 --- a/x/token/internal/querier/querier_encoder_test.go +++ /dev/null @@ -1,143 +0,0 @@ -package querier - -// import ( -// "encoding/json" -// "fmt" -// "testing" - -// sdk "github.com/cosmos/cosmos-sdk/types" -// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -// "github.com/line/lbm-sdk/v2/x/token/internal/types" -// "github.com/line/lbm-sdk/v2/x/wasm" -// "github.com/stretchr/testify/require" -// ) - -// var ( -// tokenQueryEncoder wasm.EncodeQuerier -// ) - -// func setupQueryEncoder() { -// tokenQuerier := NewQuerier(tkeeper) - -// tokenQueryEncoder = NewQueryEncoder(tokenQuerier) -// } - -// func encodeQuery(t *testing.T, jsonQuerier json.RawMessage, result interface{}) error { -// res, err := tokenQueryEncoder(ctx, jsonQuerier) -// if len(res) > 0 { -// require.NoError(t, tkeeper.UnmarshalJSON(res, result)) -// } -// return err -// } - -// func TestNewQuerier_encodeQueryTokens(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"tokens","data":{"token_param":{"contract_id":"%s"}}}`, contractID) - -// var token types.Token -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &token) -// require.NoError(t, err) -// require.Equal(t, token.GetContractID(), contractID) -// require.Equal(t, token.GetName(), tokenName) -// require.Equal(t, token.GetSymbol(), tokenSymbol) -// require.Equal(t, token.GetImageURI(), tokenImageURL) -// } - -// func TestNewQuerier_encodeQueryAccountPermission(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"perms","data":{"perm_param":{"contract_id":"%s","address":"%s"}}}`, contractID, addr1) - -// var perms types.Permissions -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &perms) -// require.NoError(t, err) -// require.Equal(t, len(perms), 3) -// require.Equal(t, perms[0].String(), "modify") -// require.Equal(t, perms[1].String(), "mint") -// require.Equal(t, perms[2].String(), "burn") -// } - -// func TestNewQuerier_encodeQueryBalance(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"balance","data":{"balance_param":{"contract_id":"%s","address":"%s"}}}`, contractID, addr1) - -// var balance sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &balance) -// require.NoError(t, err) -// require.Equal(t, balance.Int64(), int64(tokenAmount-tokenBurned)) -// } - -// func TestNewQuerier_encodeQueryTotalSupply(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"%s","data":{"total_param":{"contract_id":"%s"}}}`, types.QuerySupply, contractID) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, supply.Int64(), int64(tokenAmount-tokenBurned)) -// } - -// func TestNewQuerier_encodeQueryTotalMint(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"%s","data":{"total_param":{"contract_id":"%s"}}}`, types.QueryMint, contractID) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, supply.Int64(), int64(tokenAmount)) -// } - -// func TestNewQuerier_encodeQueryTotalBurn(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"%s","data":{"total_param":{"contract_id":"%s"}}}`, types.QueryBurn, contractID) - -// var supply sdk.Int -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &supply) -// require.NoError(t, err) -// require.Equal(t, supply.Int64(), int64(tokenBurned)) -// } - -// func TestNewQuerier_encodeQueryIsApproved_true(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"approved","data":{"is_approved_param":{"proxy":"%s", "contract_id":"%s","approver":"%s"}}}`, addr1, contractID, addr2) - -// var approved bool -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &approved) -// require.NoError(t, err) -// require.True(t, approved) -// } - -// func TestNewQuerier_encodeQueryApprovers(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintf(`{"route":"approvers","data":{"approvers_param":{"proxy":"%s", "contract_id":"%s"}}}`, addr1, contractID) - -// var approvers []sdk.AccAddress -// err := encodeQuery(t, json.RawMessage(jsonQuerier), &approvers) -// require.NoError(t, err) -// require.Equal(t, 2, len(approvers)) -// require.True(t, types.IsAddressContains(approvers, addr3)) -// require.True(t, types.IsAddressContains(approvers, addr2)) - -// var acAdEmpty []sdk.AccAddress -// jsonQuerier = fmt.Sprintf(`{"route":"approvers","data":{"approvers_param":{"proxy":"%s", "contract_id":"%s"}}}`, addr2, contractID) - -// err = encodeQuery(t, json.RawMessage(jsonQuerier), &acAdEmpty) -// require.NoError(t, err) -// require.Empty(t, acAdEmpty) -// } - -// func TestNewQuerier_invalidEncode(t *testing.T) { -// prepare(t) -// setupQueryEncoder() -// jsonQuerier := fmt.Sprintln(`{"route":"noquery","data":{"query_invalid_param":""}}`) - -// err := encodeQuery(t, json.RawMessage(jsonQuerier), nil) -// require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized Msg route: %T", "noquery").Error()) -// } diff --git a/x/token/internal/querier/querier_test.go b/x/token/internal/querier/querier_test.go deleted file mode 100644 index 7d04f91ea2..0000000000 --- a/x/token/internal/querier/querier_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package querier - -import ( - "context" - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/types" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - contractID = "9be17165" - tokenName = "linko token" - tokenSymbol = "LINKO" - tokenImageURL = "url" - tokenAmount = 1000 - tokenBurned = 10 - tokenMeta = "{}" -) - -var ( - ms store.CommitMultiStore - ctx sdk.Context - tkeeper keeper.Keeper - addr1 sdk.AccAddress - addr2 sdk.AccAddress - addr3 sdk.AccAddress -) - -func prepare(t *testing.T) { - ctx, ms, tkeeper = keeper.TestKeeper() - msCache := ms.CacheMultiStore() - ctx = ctx.WithMultiStore(msCache) - - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr3 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - // prepare token - ctx2 := ctx.WithContext(context.WithValue(ctx.Context(), contract.CtxKey{}, contractID)) - require.NoError(t, tkeeper.IssueToken(ctx2, types.NewToken(contractID, tokenName, tokenSymbol, tokenMeta, tokenImageURL, sdk.NewInt(1), true), sdk.NewInt(tokenAmount), addr1, addr1)) - require.NoError(t, tkeeper.BurnToken(ctx2, sdk.NewInt(tokenBurned), addr1)) - - require.NoError(t, tkeeper.GrantPermission(ctx2, addr1, addr2, types.NewBurnPermission())) - require.NoError(t, tkeeper.SetApproved(ctx2, addr1, addr2)) - - // prepare one more approver for test proxy - require.NoError(t, tkeeper.SetApproved(ctx2, addr1, addr3)) -} - -func query(t *testing.T, params interface{}, query string, result interface{}) { - req := abci.RequestQuery{ - Path: "", - Data: []byte(string(codec.MustMarshalJSONIndent(types.ModuleCdc, params))), - } - if params == nil { - req.Data = nil - } - path := []string{query} - if contractID != "" { - path = append(path, contractID) - } - querier := NewQuerier(tkeeper) - res, err := querier(ctx, path, req) - require.NoError(t, err) - if len(res) > 0 { - require.NoError(t, tkeeper.UnmarshalJSON(res, result)) - } -} - -func TestNewQuerier_queryAccountPermission(t *testing.T) { - prepare(t) - - params := types.NewQueryContractIDAccAddressParams(addr1) - var perms types.Permissions - query(t, params, types.QueryPerms, &perms) - require.Equal(t, len(perms), 3) - require.Equal(t, perms[0].String(), "modify") - require.Equal(t, perms[1].String(), "mint") - require.Equal(t, perms[2].String(), "burn") -} - -func TestNewQuerier_queryTokens_one(t *testing.T) { - prepare(t) - - var token types.Token - query(t, nil, types.QueryTokens, &token) - require.Equal(t, token.GetContractID(), contractID) - require.Equal(t, token.GetName(), tokenName) - require.Equal(t, token.GetSymbol(), tokenSymbol) - require.Equal(t, token.GetImageURI(), tokenImageURL) -} - -func TestNewQuerier_queryBalance(t *testing.T) { - prepare(t) - - params := types.QueryContractIDAccAddressParams{ - Addr: addr1, - } - var balance sdk.Int - query(t, params, types.QueryBalance, &balance) - require.Equal(t, balance.Int64(), int64(tokenAmount-tokenBurned)) -} - -func TestNewQuerier_queryTotalSupply(t *testing.T) { - prepare(t) - - var supply sdk.Int - query(t, nil, types.QuerySupply, &supply) - require.Equal(t, supply.Int64(), int64(tokenAmount-tokenBurned)) -} - -func TestNewQuerier_queryTotalMint(t *testing.T) { - prepare(t) - - var supply sdk.Int - query(t, nil, types.QueryMint, &supply) - require.Equal(t, supply.Int64(), int64(tokenAmount)) -} - -func TestNewQuerier_queryTotalBurn(t *testing.T) { - prepare(t) - - var supply sdk.Int - query(t, nil, types.QueryBurn, &supply) - require.Equal(t, supply.Int64(), int64(tokenBurned)) -} - -func TestNewQuerier_invalid(t *testing.T) { - prepare(t) - params := types.QueryContractIDAccAddressParams{ - Addr: addr1, - } - querier := NewQuerier(tkeeper) - path := []string{"noquery", contractID} - req := abci.RequestQuery{ - Path: "", - Data: []byte(string(codec.MustMarshalJSONIndent(types.ModuleCdc, params))), - } - _, err := querier(ctx, path, req) - require.EqualError(t, err, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown token query endpoint").Error()) -} - -func TestNewQuerier_queryIsApproved_true(t *testing.T) { - prepare(t) - - params := types.QueryIsApprovedParams{ - Proxy: addr1, - Approver: addr2, - } - var approved bool - query(t, params, types.QueryIsApproved, &approved) - require.True(t, approved) -} - -func TestNewQuerier_queryIsApproved_false(t *testing.T) { - prepare(t) - - params := types.QueryIsApprovedParams{ - Proxy: addr2, - Approver: addr1, - } - var approved bool - query(t, params, types.QueryIsApproved, &approved) - require.False(t, approved) -} - -func TestNewQuerier_queryApprovers(t *testing.T) { - prepare(t) - params := types.QueryProxyParams{ - Proxy: addr1, - } - var approvers []sdk.AccAddress - query(t, params, types.QueryApprovers, &approvers) - require.Equal(t, 2, len(approvers)) - require.True(t, types.IsAddressContains(approvers, addr3)) - require.True(t, types.IsAddressContains(approvers, addr2)) - - var acAdEmpty []sdk.AccAddress - paramsEmpty := types.QueryProxyParams{ - Proxy: addr2, - } - query(t, paramsEmpty, types.QueryApprovers, &acAdEmpty) - require.Empty(t, acAdEmpty) -} diff --git a/x/token/internal/types/account.go b/x/token/internal/types/account.go deleted file mode 100644 index 3c3ddc8776..0000000000 --- a/x/token/internal/types/account.go +++ /dev/null @@ -1,56 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type TokenID string - -type Account interface { - GetAddress() sdk.AccAddress - GetContractID() string - GetBalance() sdk.Int - SetBalance(amount sdk.Int) Account - String() string -} - -type BaseAccount struct { - ContractID string `json:"contract_id"` - Address sdk.AccAddress `json:"address"` - Amount sdk.Int `json:"amount"` -} - -func NewBaseAccountWithAddress(contractID string, addr sdk.AccAddress) *BaseAccount { - return &BaseAccount{ - ContractID: contractID, - Address: addr, - Amount: sdk.ZeroInt(), - } -} - -func (acc BaseAccount) GetContractID() string { - return acc.ContractID -} - -func (acc BaseAccount) String() string { - b, err := json.Marshal(acc) - if err != nil { - panic(err) - } - return string(b) -} - -func (acc BaseAccount) GetAddress() sdk.AccAddress { - return acc.Address -} - -func (acc BaseAccount) GetBalance() sdk.Int { - return acc.Amount -} - -func (acc BaseAccount) SetBalance(amount sdk.Int) Account { - acc.Amount = amount - return acc -} diff --git a/x/token/internal/types/account_test.go b/x/token/internal/types/account_test.go deleted file mode 100644 index dfecb83ab7..0000000000 --- a/x/token/internal/types/account_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestAccount(t *testing.T) { - var acc Account - acc = NewBaseAccountWithAddress(defaultContractID, addr1) - - require.Equal(t, defaultContractID, acc.GetContractID()) - require.Equal(t, addr1, acc.GetAddress()) - require.Equal(t, sdk.ZeroInt(), acc.GetBalance()) - - acc = acc.SetBalance(sdk.OneInt()) - - require.Equal(t, sdk.OneInt(), acc.GetBalance()) - - require.True(t, len(acc.String()) > 0) -} diff --git a/x/token/internal/types/codec.go b/x/token/internal/types/codec.go deleted file mode 100644 index 20f5c39a99..0000000000 --- a/x/token/internal/types/codec.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -var ModuleCdc *codec.Codec - -func init() { - ModuleCdc = codec.New() - RegisterCodec(ModuleCdc) - ModuleCdc.Seal() -} - -// RegisterCodec registers concrete types on the Amino codec -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgIssue{}, "token/MsgIssue", nil) - cdc.RegisterConcrete(MsgModify{}, "token/MsgModify", nil) - cdc.RegisterConcrete(MsgMint{}, "token/MsgMint", nil) - cdc.RegisterConcrete(MsgBurn{}, "token/MsgBurn", nil) - cdc.RegisterConcrete(MsgGrantPermission{}, "token/MsgGrantPermission", nil) - cdc.RegisterConcrete(MsgRevokePermission{}, "token/MsgRevokePermission", nil) - cdc.RegisterConcrete(MsgTransfer{}, "token/MsgTransfer", nil) - cdc.RegisterInterface((*Token)(nil), nil) - cdc.RegisterConcrete(&BaseToken{}, "token/Token", nil) - cdc.RegisterInterface((*Supply)(nil), nil) - cdc.RegisterConcrete(&BaseSupply{}, "token/Supply", nil) - cdc.RegisterInterface((*Account)(nil), nil) - cdc.RegisterConcrete(&BaseAccount{}, "token/Account", nil) - cdc.RegisterInterface((*AccountPermissionI)(nil), nil) - cdc.RegisterConcrete(&AccountPermission{}, "token/AccountPermission", nil) - cdc.RegisterConcrete(MsgApprove{}, "token/MsgApprove", nil) - cdc.RegisterConcrete(MsgTransferFrom{}, "token/MsgTransferFrom", nil) - cdc.RegisterConcrete(MsgBurnFrom{}, "token/MsgBurnFrom", nil) -} diff --git a/x/token/internal/types/common_test.go b/x/token/internal/types/common_test.go deleted file mode 100644 index 16d9aff437..0000000000 --- a/x/token/internal/types/common_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - defaultName = "name" - defaultContractID = "linktkn" - defaultSymbol = "BTC" - defaultMeta = "{}" - defaultImageURI = "image-uri" - defaultDecimals = 6 - defaultAmount = 1000 -) - -var ( - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) -) diff --git a/x/token/internal/types/encoder.go b/x/token/internal/types/encoder.go deleted file mode 100644 index f152e4e232..0000000000 --- a/x/token/internal/types/encoder.go +++ /dev/null @@ -1,93 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type EncodeHandler func(jsonMsg json.RawMessage) ([]sdk.Msg, error) -type EncodeQuerier func(ctx sdk.Context, jsonQuerier json.RawMessage) ([]byte, error) - -const ( - EncodeRouterKey = "tokenencode" -) - -type MsgRoute string - -const ( - RIssue = MsgRoute("issue") - RTransfer = MsgRoute("transfer") - RTransferFrom = MsgRoute("transfer_from") - RMint = MsgRoute("mint") - RBurn = MsgRoute("burn") - RBurnFrom = MsgRoute("burn_from") - RGrantPerm = MsgRoute("grant_perm") - RRevokePerm = MsgRoute("revoke_perm") - RModify = MsgRoute("modify") - RApprove = MsgRoute("approve") -) - -// WasmCustomMsg - wasm custom msg parser -type WasmCustomMsg struct { - Route string `json:"route"` - Data json.RawMessage `json:"data"` -} - -type WasmCustomQuerier struct { - Route string `json:"route"` - Data json.RawMessage `json:"data"` -} - -type QueryTokenWrapper struct { - TokenParam TokenParam `json:"token_param"` -} - -type TokenParam struct { - ContractID string `json:"contract_id"` -} - -type QueryBalanceWrapper struct { - BalanceParam BalanceParam `json:"balance_param"` -} - -type BalanceParam struct { - ContractID string `json:"contract_id"` - Address sdk.AccAddress `json:"address"` -} - -type QueryTotalWrapper struct { - TotalParam TotalParam `json:"total_param"` -} - -type TotalParam struct { - ContractID string `json:"contract_id"` -} - -type QueryPermWrapper struct { - PermParam PermParam `json:"perm_param"` -} - -type PermParam struct { - ContractID string `json:"contract_id"` - Address sdk.AccAddress `json:"address"` -} - -type QueryIsApprovedWrapper struct { - IsApprovedParam IsApprovedParam `json:"is_approved_param"` -} - -type IsApprovedParam struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - Approver sdk.AccAddress `json:"approver"` -} - -type QueryApproversWrapper struct { - ApproversParam ApproversParam `json:"approvers_param"` -} - -type ApproversParam struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` -} diff --git a/x/token/internal/types/errors.go b/x/token/internal/types/errors.go deleted file mode 100644 index dab4ad7b4a..0000000000 --- a/x/token/internal/types/errors.go +++ /dev/null @@ -1,45 +0,0 @@ -package types - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -var ( - ErrTokenExist = sdkerrors.Register(ModuleName, 1, "token already exists") - ErrTokenNotExist = sdkerrors.Register(ModuleName, 2, "token does not exist") - ErrTokenNotMintable = sdkerrors.Register(ModuleName, 3, "token is not mintable") - ErrInvalidTokenName = sdkerrors.Register(ModuleName, 4, "token name should not be empty") - ErrInvalidTokenDecimals = sdkerrors.Register(ModuleName, 5, "token decimals should be within the range in 0 ~ 18") - ErrInvalidAmount = sdkerrors.Register(ModuleName, 6, "invalid token amount") - ErrInvalidImageURILength = sdkerrors.Register(ModuleName, 7, "invalid token uri length") - ErrInvalidNameLength = sdkerrors.Register(ModuleName, 8, "invalid name length") - ErrInvalidTokenSymbol = sdkerrors.Register(ModuleName, 9, "invalid token symbol") - ErrTokenNoPermission = sdkerrors.Register(ModuleName, 10, "account does not have the permission") - ErrAccountExist = sdkerrors.Register(ModuleName, 11, "account already exists") - ErrAccountNotExist = sdkerrors.Register(ModuleName, 12, "account does not exists") - ErrInsufficientBalance = sdkerrors.Register(ModuleName, 13, "insufficient balance") - ErrSupplyExist = sdkerrors.Register(ModuleName, 14, "supply for token already exists") - ErrInsufficientSupply = sdkerrors.Register(ModuleName, 15, "insufficient supply") - ErrInvalidChangesFieldCount = sdkerrors.Register(ModuleName, 16, "invalid count of field changes") - ErrEmptyChanges = sdkerrors.Register(ModuleName, 17, "changes is empty") - ErrInvalidChangesField = sdkerrors.Register(ModuleName, 18, "invalid field of changes") - ErrDuplicateChangesField = sdkerrors.Register(ModuleName, 19, "invalid field of changes") - ErrInvalidMetaLength = sdkerrors.Register(ModuleName, 20, "invalid meta length") - ErrSupplyOverflow = sdkerrors.Register(ModuleName, 21, "supply for token reached maximum") - ErrApproverProxySame = sdkerrors.Register(ModuleName, 22, "approver is same with proxy") - ErrTokenNotApproved = sdkerrors.Register(ModuleName, 23, "proxy is not approved on the token") - ErrTokenAlreadyApproved = sdkerrors.Register(ModuleName, 24, "proxy is already approved on the token") - ErrInvalidPermissionAction = sdkerrors.Register(ModuleName, 25, "invalid permission action") -) - -func WrapIfOverflowPanic(r interface{}) error { - if isOverflowPanic(r) { - return ErrSupplyOverflow - } - // unknown panic, bubble up :( - panic(r) -} - -func isOverflowPanic(r interface{}) bool { - return r == "Int overflow" || r == "negative coin amount" -} diff --git a/x/token/internal/types/events.go b/x/token/internal/types/events.go deleted file mode 100644 index 44d5e4460b..0000000000 --- a/x/token/internal/types/events.go +++ /dev/null @@ -1,30 +0,0 @@ -package types - -var ( - EventTypeIssueToken = "issue" - EventTypeMintToken = "mint" - EventTypeBurnToken = "burn" - EventTypeBurnTokenFrom = "burn_from" - EventTypeModifyToken = "modify_token" - EventTypeGrantPermToken = "grant_perm" - EventTypeRevokePermToken = "revoke_perm" - EventTypeTransfer = "transfer" - EventTypeTransferFrom = "transfer_from" - EventTypeApproveToken = "approve_token" - - AttributeKeyName = "name" - AttributeKeySymbol = "symbol" - AttributeKeyContractID = "contract_id" - AttributeKeyOwner = "owner" - AttributeKeyAmount = "amount" - AttributeKeyDecimals = "decimals" - AttributeKeyMeta = "meta" - AttributeKeyImageURI = "img_uri" - AttributeKeyMintable = "mintable" - AttributeKeyFrom = "from" - AttributeKeyTo = "to" - AttributeKeyPerm = "perm" - AttributeKeyApprover = "approver" - AttributeKeyProxy = "proxy" - AttributeValueCategory = ModuleName -) diff --git a/x/token/internal/types/expected_keeper.go b/x/token/internal/types/expected_keeper.go deleted file mode 100644 index 865b6266c3..0000000000 --- a/x/token/internal/types/expected_keeper.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - auth "github.com/cosmos/cosmos-sdk/x/auth/exported" -) - -type AccountKeeper interface { - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) auth.Account - GetAccount(ctx sdk.Context, addr sdk.AccAddress) auth.Account - SetAccount(ctx sdk.Context, acc auth.Account) -} diff --git a/x/token/internal/types/key.go b/x/token/internal/types/key.go deleted file mode 100644 index 752e689b35..0000000000 --- a/x/token/internal/types/key.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -const ( - ModuleName = "token" - - StoreKey = ModuleName - RouterKey = ModuleName -) - -var ( - TokenKeyPrefix = []byte{0x00} - BlacklistKeyPrefix = []byte{0x01} - AccountKeyPrefix = []byte{0x02} - SupplyKeyPrefix = []byte{0x03} - PermKeyPrefix = []byte{0x04} - TokenApprovedKeyPrefix = []byte{0x05} -) - -func BlacklistKey(addr sdk.AccAddress, action string) []byte { - key := append(BlacklistKeyPrefix, addr...) - key = append(key, []byte(":"+action)...) - return key -} - -func TokenKey(contractID string) []byte { - return append(TokenKeyPrefix, []byte(contractID)...) -} - -func SupplyKey(contractID string) []byte { - return append(SupplyKeyPrefix, []byte(contractID)...) -} - -func AccountKey(contractID string, addr sdk.AccAddress) []byte { - return append(append(AccountKeyPrefix, []byte(contractID)...), addr...) -} - -func PermKey(contractID string, addr sdk.AccAddress) []byte { - return append(append(PermKeyPrefix, []byte(contractID)...), addr...) -} - -func TokenApprovedKey(contractID string, proxy sdk.AccAddress, approver sdk.AccAddress) []byte { - return append(append(append(TokenApprovedKeyPrefix, []byte(contractID)...), proxy.Bytes()...), approver.Bytes()...) -} - -func TokenApproversKey(contractID string, proxy sdk.AccAddress) []byte { - return append(append(TokenApprovedKeyPrefix, []byte(contractID)...), proxy.Bytes()...) -} diff --git a/x/token/internal/types/key_test.go b/x/token/internal/types/key_test.go deleted file mode 100644 index a76ad22e00..0000000000 --- a/x/token/internal/types/key_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -func TestTokenApproveKey(t *testing.T) { - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - contractID1 := "abcdef012" - contractID2 := "abcdef013" - - require.NotEqual(t, TokenApprovedKey(contractID1, addr1, addr2), TokenApprovedKey(contractID1, addr2, addr1)) - require.NotEqual(t, TokenApprovedKey(contractID1, addr1, addr2), TokenApprovedKey(contractID2, addr1, addr2)) -} - -func TestTokenApproversKey(t *testing.T) { - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - addr2 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - contractID := "abcdef012" - - tokenApproversKey := TokenApproversKey(contractID, addr1) - - require.NotEqual(t, tokenApproversKey, TokenApproversKey(contractID, addr2)) - require.Contains(t, string(tokenApproversKey), contractID) - require.Contains(t, string(tokenApproversKey), string(addr1.Bytes())) -} diff --git a/x/token/internal/types/modify.go b/x/token/internal/types/modify.go deleted file mode 100644 index a0e22b2c6f..0000000000 --- a/x/token/internal/types/modify.go +++ /dev/null @@ -1,29 +0,0 @@ -package types - -type Change struct { - Field string `json:"field"` - Value string `json:"value"` -} - -func NewChange(field string, value string) Change { - return Change{ - Field: field, - Value: value, - } -} - -type Changes []Change - -func NewChanges(changes ...Change) Changes { - return changes -} - -func NewChangesWithMap(changesMap map[string]string) Changes { - changes := make([]Change, len(changesMap)) - idx := 0 - for k, v := range changesMap { - changes[idx] = Change{Field: k, Value: v} - idx++ - } - return NewChanges(changes...) -} diff --git a/x/token/internal/types/msgs_modify.go b/x/token/internal/types/msgs_modify.go deleted file mode 100644 index b1c3725ab4..0000000000 --- a/x/token/internal/types/msgs_modify.go +++ /dev/null @@ -1,48 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgModify)(nil) - -type MsgModify struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - Changes Changes `json:"changes"` -} - -func NewMsgModify(owner sdk.AccAddress, contractID string, changes Changes) MsgModify { - return MsgModify{ - Owner: owner, - ContractID: contractID, - Changes: changes, - } -} - -func (msg MsgModify) Route() string { return RouterKey } -func (msg MsgModify) Type() string { return "modify_token" } -func (msg MsgModify) GetContractID() string { return msg.ContractID } -func (msg MsgModify) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} -func (msg MsgModify) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Owner} } - -func (msg MsgModify) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - validator := NewChangesValidator() - if err := validator.Validate(msg.Changes); err != nil { - return err - } - - if msg.Owner.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty") - } - - return nil -} diff --git a/x/token/internal/types/msgs_modify_test.go b/x/token/internal/types/msgs_modify_test.go deleted file mode 100644 index 3d3917ac1a..0000000000 --- a/x/token/internal/types/msgs_modify_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package types - -import ( - "testing" - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -const ( - ModifyMsgType = "modify_token" - DefaultContractID = "abcd1234" -) - -func TestNewMsgModify(t *testing.T) { - msg := AMsgModify().Build() - - require.Equal(t, ModifyMsgType, msg.Type()) - require.Equal(t, ModuleName, msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, msg.Owner, msg.GetSigners()[0]) -} - -func TestMarshalMsgModify(t *testing.T) { - // Given - msg := AMsgModify().Build() - - // When marshal and unmarshal it - msg2 := MsgModify{} - err := ModuleCdc.UnmarshalJSON(msg.GetSignBytes(), &msg2) - require.NoError(t, err) - - // Then they are equal - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.Changes, msg2.Changes) - require.Equal(t, msg.Owner, msg2.Owner) -} - -func TestMsgModify_ValidateBasic(t *testing.T) { - t.Log("normal case") - { - msg := AMsgModify().Build() - require.NoError(t, msg.ValidateBasic()) - } - t.Log("empty contractID found") - { - msg := AMsgModify().ContractID("").Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: ").Error()) - } - t.Log("empty owner") - { - msg := AMsgModify().Owner(nil).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner address cannot be empty").Error()) - } - t.Log("invalid contractID found") - { - invalidContractID := "invalid2198721987" - msg := AMsgModify().ContractID(invalidContractID).Build() - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(contract.ErrInvalidContractID, "ContractID: %s", invalidContractID).Error()) - } - t.Log("image uri too long") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"img_uri": length1001String})).Build() - - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidImageURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxImageURILength, utf8.RuneCountInString(length1001String)).Error()) - } - t.Log("name too long") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"name": length1001String})).Build() - - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxTokenNameLength, utf8.RuneCountInString(length1001String)).Error()) - } - t.Log("invalid changes field") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"invalid_field": "val"})).Build() - - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidChangesField, "Field: invalid_field").Error()) - } - t.Log("no token uri field") - { - msg := AMsgModify().Changes(NewChangesWithMap(map[string]string{"name": "new_name"})).Build() - require.NoError(t, msg.ValidateBasic()) - } - t.Log("Test with changes more than max") - { - // Given changes more than max - changeList := make([]Change, MaxChangeFieldsCount+1) - msg := AMsgModify().Changes(changeList).Build() - - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidChangesFieldCount, "You can not change fields more than [%d] at once, current count: [%d]", MaxChangeFieldsCount, len(changeList)).Error()) - } -} - -func AMsgModify() *MsgModifyBuilder { - return &MsgModifyBuilder{ - msgModify: NewMsgModify( - sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()), - DefaultContractID, - NewChangesWithMap(map[string]string{ - "name": "new_name", - "img_uri": "new_img_uri", - }), - ), - } -} - -type MsgModifyBuilder struct { - msgModify MsgModify -} - -func (b *MsgModifyBuilder) Build() MsgModify { - return b.msgModify -} - -func (b *MsgModifyBuilder) Owner(owner sdk.AccAddress) *MsgModifyBuilder { - b.msgModify.Owner = owner - return b -} - -func (b *MsgModifyBuilder) ContractID(contractID string) *MsgModifyBuilder { - b.msgModify.ContractID = contractID - return b -} - -func (b *MsgModifyBuilder) Changes(changes Changes) *MsgModifyBuilder { - b.msgModify.Changes = changes - return b -} diff --git a/x/token/internal/types/msgs_perm.go b/x/token/internal/types/msgs_perm.go deleted file mode 100644 index 9c027fe893..0000000000 --- a/x/token/internal/types/msgs_perm.go +++ /dev/null @@ -1,95 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ sdk.Msg = (*MsgGrantPermission)(nil) - -func NewMsgGrantPermission(from sdk.AccAddress, contractID string, to sdk.AccAddress, perm Permission) MsgGrantPermission { - return MsgGrantPermission{ - From: from, - ContractID: contractID, - To: to, - Permission: perm, - } -} - -type MsgGrantPermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Permission Permission `json:"permission"` -} - -func (MsgGrantPermission) Route() string { return RouterKey } -func (MsgGrantPermission) Type() string { return "grant_perm" } -func (msg MsgGrantPermission) GetContractID() string { return msg.ContractID } -func (msg MsgGrantPermission) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgGrantPermission) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgGrantPermission) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.From.Empty() || msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "addresses cannot be empty") - } - - if msg.From.Equals(msg.To) { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from, to address can not be the same") - } - - return validateAction(msg.Permission.String(), MintAction, BurnAction, ModifyAction) -} - -var _ sdk.Msg = (*MsgRevokePermission)(nil) - -func NewMsgRevokePermission(from sdk.AccAddress, contractID string, perm Permission) MsgRevokePermission { - return MsgRevokePermission{ - From: from, - ContractID: contractID, - Permission: perm, - } -} - -type MsgRevokePermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Permission Permission `json:"permission"` -} - -func (MsgRevokePermission) Route() string { return RouterKey } -func (MsgRevokePermission) Type() string { return "revoke_perm" } -func (msg MsgRevokePermission) GetContractID() string { return msg.ContractID } -func (msg MsgRevokePermission) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgRevokePermission) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgRevokePermission) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "addresses cannot be empty") - } - - return validateAction(msg.Permission.String(), MintAction, BurnAction, ModifyAction) -} -func validateAction(action string, actions ...string) error { - for _, a := range actions { - if action == a { - return nil - } - } - return sdkerrors.Wrap(ErrInvalidPermissionAction, - fmt.Sprintf("permission action should be one of [%s]", strings.Join(actions, ","))) -} diff --git a/x/token/internal/types/msgs_proxy.go b/x/token/internal/types/msgs_proxy.go deleted file mode 100644 index 85b410ef0a..0000000000 --- a/x/token/internal/types/msgs_proxy.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgApprove)(nil) - -type MsgApprove struct { - Approver sdk.AccAddress `json:"approver"` - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` -} - -func NewMsgApprove(approver sdk.AccAddress, contractID string, proxy sdk.AccAddress) MsgApprove { - return MsgApprove{ - Approver: approver, - ContractID: contractID, - Proxy: proxy, - } -} - -func (msg MsgApprove) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return nil - } - if msg.Approver.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Approver cannot be empty") - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.Approver.Equals(msg.Proxy) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.Approver.String()) - } - return nil -} - -func (MsgApprove) Route() string { return RouterKey } -func (MsgApprove) Type() string { return "approve_token" } -func (msg MsgApprove) GetContractID() string { return msg.ContractID } -func (msg MsgApprove) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Approver} -} -func (msg MsgApprove) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} diff --git a/x/token/internal/types/msgs_test.go b/x/token/internal/types/msgs_test.go deleted file mode 100644 index 1f8b47bb75..0000000000 --- a/x/token/internal/types/msgs_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package types - -import ( - "strings" - "testing" - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/secp256k1" -) - -// nolint:dupl -func TestMsgBasics(t *testing.T) { - cdc := ModuleCdc - addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - length1001String := strings.Repeat("Eng글자日本語はスゲ", 91) // 11 * 91 = 1001 - - { - msg := NewMsgIssue(addr, addr, "name", "BTC", "{}", "imageuri", sdk.NewInt(1), sdk.NewInt(8), true) - require.Equal(t, "issue_token", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgIssue{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Name, msg2.Name) - require.Equal(t, msg.Symbol, msg2.Symbol) - require.Equal(t, msg.ImageURI, msg2.ImageURI) - require.Equal(t, msg.Owner, msg2.Owner) - require.Equal(t, msg.Amount, msg.Amount) - require.Equal(t, msg.Decimals, msg2.Decimals) - require.Equal(t, msg.Mintable, msg2.Mintable) - } - { - msg := NewMsgIssue(addr, addr, "name", "BTC", "", length1001String, sdk.NewInt(1), sdk.NewInt(8), true) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidImageURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxImageURILength, utf8.RuneCountInString(length1001String)).Error()) - } - { - msg := NewMsgIssue(addr, addr, "name", "", "", length1001String, sdk.NewInt(1), sdk.NewInt(8), true) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenSymbol, "Symbol: ").Error()) - } - { - msg := NewMsgIssue(addr, addr, "name", "123456789012345678901", "", length1001String, sdk.NewInt(1), sdk.NewInt(8), true) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenSymbol, "Symbol: 123456789012345678901").Error()) - } - { - msg := NewMsgIssue(addr, addr, "name", "BCD_A", "", length1001String, sdk.NewInt(1), sdk.NewInt(8), true) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenSymbol, "Symbol: BCD_A").Error()) - } - { - msg := NewMsgIssue(addr, addr, "name", "12", "", length1001String, sdk.NewInt(1), sdk.NewInt(8), true) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidTokenSymbol, "Symbol: 12").Error()) - } - { - msg := NewMsgIssue(addr, addr, length1001String, "BTC", "", "tokenuri", sdk.NewInt(1), sdk.NewInt(8), true) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxTokenNameLength, utf8.RuneCountInString(length1001String)).Error()) - } - { - msg := NewMsgIssue(addr, addr, "", "BTC", "", "tokenuri", sdk.NewInt(1), sdk.NewInt(8), true) - require.EqualError(t, msg.ValidateBasic(), ErrInvalidTokenName.Error()) - } - { - msg := NewMsgIssue(addr, addr, "name", "BTC", "", "tokenuri", sdk.NewInt(1), sdk.NewInt(19), true) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrInvalidTokenDecimals, "Decimals: %s", sdk.NewInt(19).String()).Error()) - } - { - msg := NewMsgMint(addr, contract.SampleContractID, addr, sdk.NewInt(1)) - require.Equal(t, "mint", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgMint{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.Amount, msg2.Amount) - } - { - msg := NewMsgBurn(addr, contract.SampleContractID, sdk.NewInt(1)) - require.Equal(t, "burn", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgBurn{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.Amount, msg2.Amount) - } - { - msg := NewMsgBurnFrom(addr1, contract.SampleContractID, addr2, sdk.NewInt(1)) - require.Equal(t, "burn_from", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgBurnFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.Amount, msg2.Amount) - } - - { - msg := NewMsgBurnFrom(addr1, contract.SampleContractID, addr1, sdk.NewInt(1)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", addr1.String()).Error()) - - msg = NewMsgBurnFrom(nil, contract.SampleContractID, addr1, sdk.NewInt(1)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgBurnFrom(addr1, contract.SampleContractID, nil, sdk.NewInt(1)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgBurnFrom(addr1, contract.SampleContractID, addr2, sdk.NewInt(-1)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(ErrInvalidAmount, "-1").Error()) - } - { - addr2 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - msg := NewMsgGrantPermission(addr, contract.SampleContractID, addr2, NewMintPermission()) - require.Equal(t, "grant_perm", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgGrantPermission{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.Permission, msg2.Permission) - } - - { - msg := NewMsgRevokePermission(addr, contract.SampleContractID, NewMintPermission()) - require.Equal(t, "revoke_perm", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgRevokePermission{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.Permission, msg2.Permission) - } - - { - msg := NewMsgTransfer(addr, addr, contract.SampleContractID, sdk.NewInt(4)) - require.Equal(t, "transfer_ft", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgTransfer{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.Amount, msg2.Amount) - } - - { - msg := NewMsgTransfer(nil, addr, contract.SampleContractID, sdk.NewInt(4)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from cannot be empty").Error()) - - msg = NewMsgTransfer(addr, nil, contract.SampleContractID, sdk.NewInt(4)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "to cannot be empty").Error()) - - msg = NewMsgTransfer(addr, addr, "m", sdk.NewInt(4)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(contract.ErrInvalidContractID, "ContractID: m").Error()) - - msg = NewMsgTransfer(addr, addr, contract.SampleContractID, sdk.NewInt(-1)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "send amount must be positive").Error()) - } - - { - msg := NewMsgTransferFrom(addr1, contract.SampleContractID, addr2, addr2, sdk.NewInt(defaultAmount)) - require.Equal(t, "transfer_from", msg.Type()) - require.Equal(t, "token", msg.Route()) - require.Equal(t, sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)), msg.GetSignBytes()) - require.Equal(t, addr1, msg.GetSigners()[0]) - require.NoError(t, msg.ValidateBasic()) - - b := msg.GetSignBytes() - - msg2 := MsgTransferFrom{} - - err := cdc.UnmarshalJSON(b, &msg2) - require.NoError(t, err) - - require.Equal(t, msg.Proxy, msg2.Proxy) - require.Equal(t, msg.From, msg2.From) - require.Equal(t, msg.To, msg2.To) - require.Equal(t, msg.ContractID, msg2.ContractID) - require.Equal(t, msg.Amount, msg2.Amount) - } - - { - msg := NewMsgTransferFrom(nil, contract.SampleContractID, addr2, addr2, sdk.NewInt(defaultAmount)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty").Error()) - - msg = NewMsgTransferFrom(addr1, contract.SampleContractID, nil, addr2, sdk.NewInt(defaultAmount)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty").Error()) - - msg = NewMsgTransferFrom(addr1, contract.SampleContractID, addr2, nil, sdk.NewInt(defaultAmount)) - require.EqualError(t, msg.ValidateBasic(), sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty").Error()) - } -} diff --git a/x/token/internal/types/msgs_token.go b/x/token/internal/types/msgs_token.go deleted file mode 100644 index 86fb4e3281..0000000000 --- a/x/token/internal/types/msgs_token.go +++ /dev/null @@ -1,213 +0,0 @@ -package types - -import ( - "unicode/utf8" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ sdk.Msg = (*MsgIssue)(nil) - -type MsgIssue struct { - Owner sdk.AccAddress `json:"owner"` - To sdk.AccAddress `json:"to"` - Name string `json:"name"` - Symbol string `json:"symbol"` - ImageURI string `json:"img_uri"` - Meta string `json:"meta"` - Amount sdk.Int `json:"amount"` - Mintable bool `json:"mintable"` - Decimals sdk.Int `json:"decimals"` -} - -func NewMsgIssue(owner, to sdk.AccAddress, name, symbol, meta string, imageURI string, amount sdk.Int, decimal sdk.Int, mintable bool) MsgIssue { - return MsgIssue{ - Owner: owner, - To: to, - Name: name, - Symbol: symbol, - Meta: meta, - ImageURI: imageURI, - Amount: amount, - Mintable: mintable, - Decimals: decimal, - } -} - -func (msg MsgIssue) Route() string { return RouterKey } -func (msg MsgIssue) Type() string { return "issue_token" } -func (msg MsgIssue) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) } -func (msg MsgIssue) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Owner} } - -func (msg MsgIssue) ValidateBasic() error { - if len(msg.Name) == 0 { - return ErrInvalidTokenName - } - if msg.Owner.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner cannot be empty") - } - - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "to cannot be empty") - } - - if !ValidateName(msg.Name) { - return sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Name, MaxTokenNameLength, utf8.RuneCountInString(msg.Name)) - } - if !ValidateMeta(msg.Meta) { - return sdkerrors.Wrapf(ErrInvalidMetaLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.Meta, MaxTokenMetaLength, utf8.RuneCountInString(msg.Meta)) - } - - if err := ValidateTokenSymbol(msg.Symbol); err != nil { - return sdkerrors.Wrapf(ErrInvalidTokenSymbol, "Symbol: %s", msg.Symbol) - } - - if !ValidateImageURI(msg.ImageURI) { - return sdkerrors.Wrapf(ErrInvalidImageURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", msg.ImageURI, MaxImageURILength, utf8.RuneCountInString(msg.ImageURI)) - } - - if msg.Decimals.GT(sdk.NewInt(18)) || msg.Decimals.IsNegative() { - return sdkerrors.Wrapf(ErrInvalidTokenDecimals, "Decimals: %s", msg.Decimals) - } - - if !msg.Amount.IsPositive() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - - return nil -} - -var _ contract.Msg = (*MsgMint)(nil) - -type MsgMint struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount sdk.Int `json:"amount"` -} - -func NewMsgMint(from sdk.AccAddress, contractID string, to sdk.AccAddress, amount sdk.Int) MsgMint { - return MsgMint{ - From: from, - ContractID: contractID, - To: to, - Amount: amount, - } -} -func (MsgMint) Route() string { return RouterKey } -func (MsgMint) Type() string { return "mint" } -func (msg MsgMint) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgMint) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgMint) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Amount.IsNegative() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from cannot be empty") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "to cannot be empty") - } - return nil -} -func (msg MsgMint) GetContractID() string { - return msg.ContractID -} - -var _ contract.Msg = (*MsgBurn)(nil) - -type MsgBurn struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Amount sdk.Int `json:"amount"` -} - -func NewMsgBurn(from sdk.AccAddress, contractID string, amount sdk.Int) MsgBurn { - return MsgBurn{ - From: from, - ContractID: contractID, - Amount: amount, - } -} -func (MsgBurn) Route() string { return RouterKey } -func (MsgBurn) Type() string { return "burn" } -func (msg MsgBurn) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg MsgBurn) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgBurn) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if !msg.Amount.IsPositive() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "owner cannot be empty") - } - if msg.Amount.IsNegative() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - return nil -} - -func (msg MsgBurn) GetContractID() string { - return msg.ContractID -} - -var _ contract.Msg = (*MsgBurnFrom)(nil) - -type MsgBurnFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - Amount sdk.Int `json:"amount"` -} - -func NewMsgBurnFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, amount sdk.Int) MsgBurnFrom { - return MsgBurnFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - Amount: amount, - } -} -func (MsgBurnFrom) Route() string { return RouterKey } -func (MsgBurnFrom) Type() string { return "burn_from" } -func (msg MsgBurnFrom) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Proxy} } -func (msg MsgBurnFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgBurnFrom) ValidateBasic() error { - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if !msg.Amount.IsPositive() { - return sdkerrors.Wrap(ErrInvalidAmount, msg.Amount.String()) - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if msg.Proxy.Equals(msg.From) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.Proxy.String()) - } - - return nil -} - -func (msg MsgBurnFrom) GetContractID() string { - return msg.ContractID -} diff --git a/x/token/internal/types/msgs_transfer.go b/x/token/internal/types/msgs_transfer.go deleted file mode 100644 index bb1d6843f8..0000000000 --- a/x/token/internal/types/msgs_transfer.go +++ /dev/null @@ -1,122 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/line/lbm-sdk/v2/x/contract" -) - -var _ contract.Msg = (*MsgTransfer)(nil) - -type MsgTransfer struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount sdk.Int `json:"amount"` -} - -func NewMsgTransfer(from sdk.AccAddress, to sdk.AccAddress, contractID string, amount sdk.Int) MsgTransfer { - return MsgTransfer{From: from, To: to, ContractID: contractID, Amount: amount} -} - -func (msg MsgTransfer) Route() string { return RouterKey } - -func (msg MsgTransfer) Type() string { return "transfer_ft" } - -func (msg MsgTransfer) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "from cannot be empty") - } - - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "to cannot be empty") - } - - if !msg.Amount.IsPositive() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "send amount must be positive") - } - return nil -} - -func (msg MsgTransfer) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgTransfer) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -func (msg MsgTransfer) GetContractID() string { - return msg.ContractID -} - -var _ contract.Msg = (*MsgTransferFrom)(nil) - -type MsgTransferFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - To sdk.AccAddress `json:"to"` - Amount sdk.Int `json:"amount"` -} - -func NewMsgTransferFrom(proxy sdk.AccAddress, contractID string, from sdk.AccAddress, to sdk.AccAddress, amount sdk.Int) MsgTransferFrom { - return MsgTransferFrom{ - Proxy: proxy, - ContractID: contractID, - From: from, - To: to, - Amount: amount, - } -} -func (msg MsgTransferFrom) MarshalJSON() ([]byte, error) { - type msgAlias MsgTransferFrom - return json.Marshal(msgAlias(msg)) -} - -func (msg *MsgTransferFrom) UnmarshalJSON(data []byte) error { - type msgAlias *MsgTransferFrom - return json.Unmarshal(data, msgAlias(msg)) -} - -func (MsgTransferFrom) Route() string { return RouterKey } - -func (MsgTransferFrom) Type() string { return "transfer_from" } - -func (msg MsgTransferFrom) GetContractID() string { return msg.ContractID } - -func (msg MsgTransferFrom) ValidateBasic() error { - if err := contract.ValidateContractIDBasic(msg); err != nil { - return err - } - if msg.Proxy.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Proxy cannot be empty") - } - if msg.From.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "From cannot be empty") - } - if msg.To.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "To cannot be empty") - } - if msg.From.Equals(msg.Proxy) { - return sdkerrors.Wrapf(ErrApproverProxySame, "Approver: %s", msg.From.String()) - } - if !msg.Amount.IsPositive() { - return sdkerrors.Wrap(ErrInvalidAmount, "invalid amount") - } - return nil -} - -func (msg MsgTransferFrom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -func (msg MsgTransferFrom) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Proxy} -} diff --git a/x/token/internal/types/perm.go b/x/token/internal/types/perm.go deleted file mode 100644 index 77391c9045..0000000000 --- a/x/token/internal/types/perm.go +++ /dev/null @@ -1,137 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - MintAction = "mint" - BurnAction = "burn" - ModifyAction = "modify" -) - -type Permission string - -func NewMintPermission() Permission { - return MintAction -} - -func NewBurnPermission() Permission { - return BurnAction -} - -func NewModifyPermission() Permission { - return ModifyAction -} - -func (p Permission) Equal(p2 Permission) bool { - return p == p2 -} -func (p Permission) String() string { - return string(p) -} - -func (p Permission) Validate() bool { - if p == MintAction { - return true - } - if p == BurnAction { - return true - } - if p == ModifyAction { - return true - } - return false -} - -type Permissions []Permission - -func NewPermissions(perms ...Permission) Permissions { - pms := Permissions{} - for _, perm := range perms { - pms.AddPermission(perm) - } - return pms -} - -func (pms *Permissions) GetPermissions() []Permission { - return []Permission(*pms) -} - -func (pms *Permissions) RemoveElement(idx int) { - *pms = append((*pms)[:idx], (*pms)[idx+1:]...) -} - -func (pms *Permissions) AddPermission(p Permission) { - for _, pin := range *pms { - if pin.Equal(p) { - return - } - } - *pms = append(*pms, p) -} - -func (pms *Permissions) RemovePermission(p Permission) { - for idx, pin := range *pms { - if pin.Equal(p) { - pms.RemoveElement(idx) - return - } - } -} - -func (pms Permissions) HasPermission(p Permission) bool { - for _, pin := range pms { - if pin.Equal(p) { - return true - } - } - return false -} -func (pms Permissions) String() string { - return fmt.Sprintf("%#v", pms) -} - -type AccountPermissionI interface { - GetAddress() sdk.AccAddress - HasPermission(Permission) bool - AddPermission(Permission) - RemovePermission(Permission) - String() string - GetPermissions() Permissions -} - -type AccountPermission struct { - Address sdk.AccAddress - Permissions Permissions -} - -func NewAccountPermission(addr sdk.AccAddress) AccountPermissionI { - return &AccountPermission{ - Address: addr, - } -} - -func (ap *AccountPermission) String() string { - return fmt.Sprintf("%#v", ap) -} - -func (ap *AccountPermission) GetPermissions() Permissions { - return ap.Permissions.GetPermissions() -} - -func (ap *AccountPermission) GetAddress() sdk.AccAddress { - return ap.Address -} - -func (ap *AccountPermission) HasPermission(p Permission) bool { - return ap.Permissions.HasPermission(p) -} -func (ap *AccountPermission) AddPermission(p Permission) { - ap.Permissions.AddPermission(p) -} -func (ap *AccountPermission) RemovePermission(p Permission) { - ap.Permissions.RemovePermission(p) -} diff --git a/x/token/internal/types/perm_test.go b/x/token/internal/types/perm_test.go deleted file mode 100644 index 99208113d7..0000000000 --- a/x/token/internal/types/perm_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestPermission(t *testing.T) { - // Given permissions - mintPerm := NewMintPermission() - burnPerm := NewBurnPermission() - modifyPerm := NewModifyPermission() - - require.True(t, mintPerm.Validate()) - require.True(t, burnPerm.Validate()) - require.True(t, modifyPerm.Validate()) - - require.True(t, mintPerm.Equal(mintPerm)) - require.False(t, mintPerm.Equal(burnPerm)) - require.False(t, mintPerm.Equal(modifyPerm)) - - // When make resource or action empty - mintPerm = "" - burnPerm = "" - - // Then they are invalid - require.False(t, mintPerm.Validate()) - require.False(t, burnPerm.Validate()) -} - -func TestPermissionString(t *testing.T) { - mintPerm := NewMintPermission() - burnPerm := NewBurnPermission() - modifyPerm := NewModifyPermission() - - require.Equal(t, mintPerm.String(), "mint") - require.Equal(t, burnPerm.String(), "burn") - require.Equal(t, modifyPerm.String(), "modify") -} - -func TestPermissionsString(t *testing.T) { - perms := Permissions{ - NewMintPermission(), - NewBurnPermission(), - NewModifyPermission(), - } - - require.Equal(t, `types.Permissions{"mint", "burn", "modify"}`, perms.String()) -} diff --git a/x/token/internal/types/querier.go b/x/token/internal/types/querier.go deleted file mode 100644 index 889b15a0b1..0000000000 --- a/x/token/internal/types/querier.go +++ /dev/null @@ -1,60 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - QuerierRoute = "token" - QueryTokens = "tokens" - QueryPerms = "perms" - QueryBalance = "balance" - QuerySupply = "supply" - QueryMint = "mint" - QueryBurn = "burn" - QueryIsApproved = "approved" - QueryApprovers = "approvers" -) - -type NodeQuerier interface { - QueryWithData(path string, data []byte) ([]byte, int64, error) - WithHeight(height int64) context.CLIContext -} - -type QueryContractIDAccAddressParams struct { - Addr sdk.AccAddress `json:"addr"` -} - -func NewQueryContractIDAccAddressParams(addr sdk.AccAddress) QueryContractIDAccAddressParams { - return QueryContractIDAccAddressParams{Addr: addr} -} - -type QueryIsApprovedParams struct { - Proxy sdk.AccAddress `json:"proxy"` - Approver sdk.AccAddress `json:"approver"` -} - -func NewQueryIsApprovedParams(proxy sdk.AccAddress, approver sdk.AccAddress) QueryIsApprovedParams { - return QueryIsApprovedParams{ - Proxy: proxy, - Approver: approver, - } -} - -type QueryProxyParams struct { - Proxy sdk.AccAddress `json:"proxy"` -} - -func NewQueryApproverParams(proxy sdk.AccAddress) QueryProxyParams { - return QueryProxyParams{Proxy: proxy} -} - -func IsAddressContains(addresses []sdk.AccAddress, address sdk.AccAddress) bool { - for _, it := range addresses { - if address.Equals(it) { - return true - } - } - return false -} diff --git a/x/token/internal/types/supply.go b/x/token/internal/types/supply.go deleted file mode 100644 index df5df1b1c2..0000000000 --- a/x/token/internal/types/supply.go +++ /dev/null @@ -1,94 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Supply interface { - GetTotalSupply() sdk.Int - SetTotalSupply(total sdk.Int) Supply - GetTotalBurn() sdk.Int - GetTotalMint() sdk.Int - GetContractID() string - - Inflate(amount sdk.Int) Supply - Deflate(amount sdk.Int) Supply - - String() string -} - -type BaseSupply struct { - ContractID string `json:"contract_id"` - TotalSupply sdk.Int `json:"total_supply"` - TotalMint sdk.Int `json:"total_mint"` - TotalBurn sdk.Int `json:"total_burn"` -} - -func NewSupply(contractID string, total sdk.Int) Supply { - return BaseSupply{contractID, total, total, sdk.ZeroInt()} -} - -func DefaultSupply(contractID string) Supply { - return NewSupply(contractID, sdk.ZeroInt()) -} - -func (supply BaseSupply) SetTotalSupply(total sdk.Int) Supply { - supply.TotalSupply = total - supply.TotalMint = total - supply.TotalBurn = sdk.ZeroInt() - return supply -} - -func (supply BaseSupply) GetContractID() string { - return supply.ContractID -} - -func (supply BaseSupply) GetTotalSupply() sdk.Int { - return supply.TotalSupply -} - -func (supply BaseSupply) GetTotalMint() sdk.Int { - return supply.TotalMint -} - -func (supply BaseSupply) GetTotalBurn() sdk.Int { - return supply.TotalBurn -} - -func (supply BaseSupply) Inflate(amount sdk.Int) Supply { - supply.TotalSupply = supply.TotalSupply.Add(amount) - supply.TotalMint = supply.TotalMint.Add(amount) - supply.checkInvariant() - return supply -} - -func (supply BaseSupply) Deflate(amount sdk.Int) Supply { - supply.TotalSupply = supply.TotalSupply.Sub(amount) - supply.TotalBurn = supply.TotalBurn.Add(amount) - supply.checkInvariant() - return supply -} - -func (supply BaseSupply) String() string { - b, err := json.Marshal(supply) - if err != nil { - panic(err) - } - return string(b) -} - -// panic if totalSupply != totalMint - totalBurn -func (supply BaseSupply) checkInvariant() { - if !supply.TotalSupply.Equal(supply.TotalMint.Sub(supply.TotalBurn)) { - panic(fmt.Sprintf( - "Token [%v]'s total supply [%v] does not match with total mint [%v] - total burn [%v]", - supply.GetContractID(), - supply.TotalSupply, - supply.TotalMint, - supply.TotalBurn, - )) - } -} diff --git a/x/token/internal/types/supply_test.go b/x/token/internal/types/supply_test.go deleted file mode 100644 index ee6eb6ee80..0000000000 --- a/x/token/internal/types/supply_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package types - -import ( - "fmt" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestSupply(t *testing.T) { - var supply Supply - supply = DefaultSupply(defaultContractID) - - // create default - require.Equal(t, defaultContractID, supply.GetContractID()) - require.Equal(t, sdk.ZeroInt(), supply.GetTotalSupply()) - require.Equal(t, sdk.ZeroInt(), supply.GetTotalMint()) - require.Equal(t, sdk.ZeroInt(), supply.GetTotalBurn()) - - // set total supply - initialSupply := sdk.NewInt(3) - supply = supply.SetTotalSupply(initialSupply) - require.Equal(t, initialSupply, supply.GetTotalSupply()) - require.Equal(t, initialSupply, supply.GetTotalMint()) - require.Equal(t, sdk.ZeroInt(), supply.GetTotalBurn()) - - // inflate - toInflate := sdk.NewInt(2) - supply = supply.Inflate(toInflate) - require.Equal(t, initialSupply.Add(toInflate), supply.GetTotalSupply()) - require.Equal(t, initialSupply.Add(toInflate), supply.GetTotalMint()) - require.Equal(t, sdk.ZeroInt(), supply.GetTotalBurn()) - - // deflate - toDeflate := sdk.NewInt(4) - supply = supply.Deflate(toDeflate) - require.Equal(t, initialSupply.Add(toInflate).Sub(toDeflate), supply.GetTotalSupply()) - require.Equal(t, initialSupply.Add(toInflate), supply.GetTotalMint()) - require.Equal(t, toDeflate, supply.GetTotalBurn()) - - // total - expected := fmt.Sprintf( - `{"contract_id":"%s","total_supply":"%s","total_mint":"%s","total_burn":"%s"}`, - defaultContractID, - initialSupply.Add(toInflate).Sub(toDeflate), - initialSupply.Add(toInflate), - toDeflate, - ) - require.Equal(t, expected, supply.String()) -} diff --git a/x/token/internal/types/symbol.go b/x/token/internal/types/symbol.go deleted file mode 100644 index c5a6c5eba6..0000000000 --- a/x/token/internal/types/symbol.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - "fmt" - "regexp" -) - -const ( - /* #nosec */ - reUserTokenSymbolString = `[A-Z][A-Z0-9]{1,4}` -) - -var ( - reUserTokenSymbol = regexp.MustCompile(fmt.Sprintf(`^%s$`, reUserTokenSymbolString)) -) - -func ValidateReg(symbol string, reg *regexp.Regexp) error { - if !reg.MatchString(symbol) { - return fmt.Errorf("symbol [%s] mismatched to [%s]", symbol, reg.String()) - } - return nil -} - -func ValidateTokenSymbol(symbol string) error { return ValidateReg(symbol, reUserTokenSymbol) } diff --git a/x/token/internal/types/token.go b/x/token/internal/types/token.go deleted file mode 100644 index ac05248e70..0000000000 --- a/x/token/internal/types/token.go +++ /dev/null @@ -1,80 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Tokens []Token - -func (ts Tokens) String() string { - b, err := json.Marshal(ts) - if err != nil { - panic(err) - } - return string(b) -} - -type Token interface { - GetContractID() string - GetName() string - SetName(name string) - GetSymbol() string - GetMeta() string - SetMeta(meta string) - GetImageURI() string - SetImageURI(tokenURI string) - GetMintable() bool - GetDecimals() sdk.Int - String() string -} - -var _ Token = (*BaseToken)(nil) - -type BaseToken struct { - ContractID string `json:"contract_id"` - Name string `json:"name"` - Symbol string `json:"symbol"` - Meta string `json:"meta"` - ImageURI string `json:"img_uri"` - Decimals sdk.Int `json:"decimals"` - Mintable bool `json:"mintable"` -} - -func NewToken(contractID, name, symbol, meta string, imageURI string, decimals sdk.Int, mintable bool) Token { - return &BaseToken{ - ContractID: contractID, - Name: name, - Symbol: symbol, - Meta: meta, - ImageURI: imageURI, - Decimals: decimals, - Mintable: mintable, - } -} - -func (t BaseToken) GetContractID() string { return t.ContractID } -func (t BaseToken) GetName() string { return t.Name } -func (t BaseToken) GetSymbol() string { return t.Symbol } -func (t BaseToken) GetImageURI() string { return t.ImageURI } -func (t BaseToken) GetMintable() bool { return t.Mintable } -func (t BaseToken) GetDecimals() sdk.Int { return t.Decimals } -func (t *BaseToken) SetName(name string) { - t.Name = name -} -func (t BaseToken) GetMeta() string { return t.Meta } -func (t *BaseToken) SetMeta(meta string) { - t.Meta = meta -} -func (t *BaseToken) SetImageURI(tokenURI string) { - t.ImageURI = tokenURI -} - -func (t BaseToken) String() string { - b, err := json.Marshal(t) - if err != nil { - panic(err) - } - return string(b) -} diff --git a/x/token/internal/types/token_test.go b/x/token/internal/types/token_test.go deleted file mode 100644 index 39fce64581..0000000000 --- a/x/token/internal/types/token_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestUnmarshalToken(t *testing.T) { - // Given a token - token := NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - var token2 Token - - // When marshal and unmarshal the token - bz, err := ModuleCdc.MarshalJSON(token) - require.NoError(t, err) - err = ModuleCdc.UnmarshalJSON(bz, &token2) - require.NoError(t, err) - - // Then the properties are same - r := require.New(t) - r.EqualValues(defaultName, token.GetName(), token2.GetName()) - r.Equal(defaultContractID, token.GetContractID(), token2.GetContractID()) - r.Equal(defaultImageURI, token.GetImageURI(), token2.GetImageURI()) - r.Equal(int64(defaultDecimals), token.GetDecimals().Int64(), token2.GetDecimals().Int64()) - r.Equal(true, token.GetMintable(), token2.GetMintable()) -} - -func TestSetToken(t *testing.T) { - // Given a token - token := NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - - // When change name and test uri, Then they are changed - token.SetName("new_name") - token.SetImageURI("new_token_uri") - token.SetMeta("new_meta") - require.Equal(t, "new_name", token.GetName()) - require.Equal(t, "new_token_uri", token.GetImageURI()) - require.Equal(t, "new_meta", token.GetMeta()) -} - -func TestBaseToken_String(t *testing.T) { - token := NewToken(defaultContractID, defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true) - - require.Equal(t, `{"contract_id":"linktkn","name":"name","symbol":"BTC","meta":"{}","img_uri":"image-uri","decimals":"6","mintable":true}`, token.String()) -} - -func TestTokensString(t *testing.T) { - tokens := Tokens{ - NewToken(defaultContractID+"1", defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true), - NewToken(defaultContractID+"2", defaultName, defaultSymbol, defaultMeta, defaultImageURI, sdk.NewInt(defaultDecimals), true), - } - - require.Equal(t, `[{"contract_id":"linktkn1","name":"name","symbol":"BTC","meta":"{}","img_uri":"image-uri","decimals":"6","mintable":true},{"contract_id":"linktkn2","name":"name","symbol":"BTC","meta":"{}","img_uri":"image-uri","decimals":"6","mintable":true}]`, tokens.String()) -} diff --git a/x/token/internal/types/validators.go b/x/token/internal/types/validators.go deleted file mode 100644 index e3d9194453..0000000000 --- a/x/token/internal/types/validators.go +++ /dev/null @@ -1,98 +0,0 @@ -package types - -import ( - "unicode/utf8" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - MaxImageURILength = 1000 - MaxTokenNameLength = 20 - MaxTokenMetaLength = 1000 - MaxChangeFieldsCount = 100 -) - -var ( - TokenModifiableFields = ModifiableFields{ - AttributeKeyName: true, - AttributeKeyMeta: true, - AttributeKeyImageURI: true, - } -) - -type ModifiableFields map[string]bool - -func ValidateName(name string) bool { - return utf8.RuneCountInString(name) <= MaxTokenNameLength -} - -func ValidateMeta(meta string) bool { - return utf8.RuneCountInString(meta) <= MaxTokenMetaLength -} - -func ValidateImageURI(imageURI string) bool { - return utf8.RuneCountInString(imageURI) <= MaxImageURILength -} - -type ChangesValidator struct { - modifiableFields ModifiableFields - handlers map[string]func(value string) error -} - -func NewChangesValidator() *ChangesValidator { - hs := make(map[string]func(value string) error) - hs[AttributeKeyName] = func(value string) error { - if !ValidateName(value) { - return sdkerrors.Wrapf(ErrInvalidNameLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", value, MaxTokenNameLength, utf8.RuneCountInString(value)) - } - return nil - } - hs[AttributeKeyImageURI] = func(value string) error { - if !ValidateImageURI(value) { - return sdkerrors.Wrapf(ErrInvalidImageURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", value, MaxImageURILength, utf8.RuneCountInString(value)) - } - return nil - } - hs[AttributeKeyMeta] = func(value string) error { - if !ValidateMeta(value) { - return sdkerrors.Wrapf(ErrInvalidMetaLength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", value, MaxTokenMetaLength, utf8.RuneCountInString(value)) - } - return nil - } - return &ChangesValidator{ - modifiableFields: TokenModifiableFields, - handlers: hs, - } -} - -func (c *ChangesValidator) Validate(changes Changes) error { - if len(changes) == 0 { - return ErrEmptyChanges - } - - if len(changes) > MaxChangeFieldsCount { - return sdkerrors.Wrapf(ErrInvalidChangesFieldCount, "You can not change fields more than [%d] at once, current count: [%d]", MaxChangeFieldsCount, len(changes)) - } - - checkedFields := map[string]bool{} - for _, change := range changes { - if !c.modifiableFields[change.Field] { - return sdkerrors.Wrapf(ErrInvalidChangesField, "Field: %s", change.Field) - } - if checkedFields[change.Field] { - return sdkerrors.Wrapf(ErrDuplicateChangesField, "Field: %s", change.Field) - } - - validateHandler, ok := c.handlers[change.Field] - if !ok { - return sdkerrors.Wrapf(ErrInvalidChangesField, "Field: %s", change.Field) - } - - if err := validateHandler(change.Value); err != nil { - return err - } - checkedFields[change.Field] = true - } - return nil -} diff --git a/x/token/internal/types/validators_test.go b/x/token/internal/types/validators_test.go deleted file mode 100644 index c7c672ce38..0000000000 --- a/x/token/internal/types/validators_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package types - -import ( - "strings" - "testing" - "unicode/utf8" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" -) - -var length1001String = strings.Repeat("Eng글자日本語はスゲ", 91) // 11 * 91 = 1001 - -func TestValidateName(t *testing.T) { - t.Log("Given valid name") - { - var length20String = strings.Repeat("Eng글자日本語はス", 2) // 10 * 2 = 20 - require.True(t, ValidateName(length20String)) - } - t.Log("Given invalid name") - { - var length21String = strings.Repeat("Eng글자日本", 3) // 7 * 3 = 21 - require.False(t, ValidateName(length21String)) - } -} - -func TestValidateTokenURI(t *testing.T) { - t.Log("Given valid base_img_uri") - { - var length990String = strings.Repeat("Eng글자日本語はスゲ", 90) // 11 * 90 = 990 - require.True(t, ValidateImageURI(length990String)) - } - t.Log("Given invalid token_uri") - { - require.False(t, ValidateImageURI(length1001String)) - } -} - -func TestValidateChanges(t *testing.T) { - validator := NewChangesValidator() - t.Log("Test with valid changes") - { - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - "img_uri": "new_img_uri", - }) - - require.Nil(t, validator.Validate(changes)) - } - t.Log("Test with empty changes") - { - changes := Changes{} - require.EqualError(t, validator.Validate(changes), ErrEmptyChanges.Error()) - } - t.Log("Test with img_uri too long") - { - length1001String := strings.Repeat("Eng글자日本語はスゲ", 91) // 11 * 91 = 1001 - changes := NewChangesWithMap(map[string]string{ - "name": "new_name", - "img_uri": length1001String, - }) - - require.EqualError( - t, - validator.Validate(changes), - sdkerrors.Wrapf(ErrInvalidImageURILength, "[%s] should be shorter than [%d] UTF-8 characters, current length: [%d]", length1001String, MaxImageURILength, utf8.RuneCountInString(length1001String)).Error(), - ) - } - t.Log("Test with invalid changes field") - { - // Given changes with invalid fields - changes := NewChanges( - NewChange("invalid_field", "value"), - ) - // Then error is occurred - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrap(ErrInvalidChangesField, "Field: invalid_field").Error()) - } - t.Log("Test with changes more than max") - { - // Given changes more than max - changeList := make([]Change, MaxChangeFieldsCount+1) - changes := Changes(changeList) - - // Then error is occurred - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrapf(ErrInvalidChangesFieldCount, "You can not change fields more than [%d] at once, current count: [%d]", MaxChangeFieldsCount, len(changeList)).Error()) - } - t.Log("Test with duplicate fields") - { - // Given changes with duplicate fields - changes := NewChanges( - NewChange("name", "value"), - NewChange("name", "value2"), - ) - - // Then error is occurred - require.EqualError(t, validator.Validate(changes), sdkerrors.Wrapf(ErrDuplicateChangesField, "Field: name").Error()) - } -} diff --git a/x/token/module.go b/x/token/module.go deleted file mode 100644 index 696263f3ac..0000000000 --- a/x/token/module.go +++ /dev/null @@ -1,129 +0,0 @@ -package token - -import ( - "encoding/json" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/x/upgrade" - "github.com/line/lbm-sdk/v2/x/token/client/cli" - "github.com/line/lbm-sdk/v2/x/token/client/rest" - "github.com/line/lbm-sdk/v2/x/token/internal/handler" - "github.com/line/lbm-sdk/v2/x/token/internal/keeper" - "github.com/line/lbm-sdk/v2/x/token/internal/legacy" - "github.com/line/lbm-sdk/v2/x/token/internal/querier" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// app module basics object -type AppModuleBasic struct{} - -// module name -func (AppModuleBasic) Name() string { return ModuleName } - -// register module codec -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } - -// default genesis state -func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) -} - -// module validate genesis -func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := ModuleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - -// register rest routes -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr) -} - -// get the root tx command of this module -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetTxCmd(cdc) -} - -// get the root query command of this module -func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetQueryCmd(cdc) -} - -func (AppModuleBasic) GetUpgradeHandler(version string) upgrade.UpgradeHandler { - return legacy.UpgradeHandler(version) -} - -// ___________________________ -// app module -type AppModule struct { - AppModuleBasic - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// module name -func (AppModule) Name() string { return ModuleName } - -// register invariants -// TODO: should this module need invariants? -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// module message route name -func (AppModule) Route() string { return RouterKey } - -// module handler -func (am AppModule) NewHandler() sdk.Handler { return handler.NewHandler(am.keeper) } - -// module querier route name -func (AppModule) QuerierRoute() string { return RouterKey } - -// module querier -func (am AppModule) NewQuerierHandler() sdk.Querier { - return querier.NewQuerier(am.keeper) -} - -// module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - ModuleCdc.MustUnmarshalJSON(data, &genesisState) - InitGenesis(ctx, am.keeper, genesisState) - return []abci.ValidatorUpdate{} -} - -// module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return ModuleCdc.MustMarshalJSON(gs) -} - -// module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/token/spec/01_concept.md b/x/token/spec/01_concept.md deleted file mode 100644 index a525a86adb..0000000000 --- a/x/token/spec/01_concept.md +++ /dev/null @@ -1,2 +0,0 @@ -# Concept -TBD \ No newline at end of file diff --git a/x/token/spec/02_keepers.md b/x/token/spec/02_keepers.md deleted file mode 100644 index bddc31f1af..0000000000 --- a/x/token/spec/02_keepers.md +++ /dev/null @@ -1,2 +0,0 @@ -# Keepers -TBD diff --git a/x/token/spec/03_messages.md b/x/token/spec/03_messages.md deleted file mode 100644 index e6e1450ba6..0000000000 --- a/x/token/spec/03_messages.md +++ /dev/null @@ -1,180 +0,0 @@ -# Messages -## MsgIssue - -**Issue token messages are to create a new token on Link Chain** -- See [symbol rule](01_concept.md#rule-for-defining-symbols) for the details -- The first issuer for the token symbol occupies the symbol and the issue permission is granted to the issuer -- An issuer who granted issue permission can issue collective tokens -- Mint permission is granted to the token issuer when the token is mintable -- The identifier for the collective token is defined by the concatenation of the symbol and the token id - -### MsgIssue -```golang -type MsgIssue struct { - Owner sdk.AccAddress `json:"owner"` - To sdk.AccAddress `json:"to"` - Name string `json:"name"` - Meta string `json:"meta"` - Symbol string `json:"symbol"` - ImageURI string `json:"img_uri"` - Amount sdk.Int `json:"amount"` - Mintable bool `json:"mintable"` - Decimals sdk.Int `json:"decimals"` -} -``` -## Mint - -**Mint message is to increase the total supply of the token** -- Signer(From) of this message must have permission -- Minted token is added to the `To` account - -### MsgMint - -```golang -type MsgMint struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount sdk.Int `json:"amount"` -} -``` - -## Burn -**Burn message is to decrease the total supply of the token** -- Signer(From) of this message must have the amount of the tokens -- Token is subtracted from the `From` account - -### MsgBurn - -```golang -type MsgBurn struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Amount sdk.Int `json:"amount"` -} -``` - -### MsgBurnFrom - -```golang -type MsgBurnFrom struct { - Proxy sdk.AccAddress `json:"proxy"` - ContractID string `json:"contract_id"` - From sdk.AccAddress `json:"from"` - Amount sdk.Int `json:"amount"` -} -``` - - -## MsgGrantPermission - -```golang -type MsgGrantPermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Permission Permission `json:"permission"` -} -``` - -**Grant Permission is to give a permission to the `To` account** -- `From` account must has the permission - -## MsgRevokePermission - -```golang -type MsgRevokePermission struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - Permission Permission `json:"permission"` -} -``` - -**Revoke Permission is to dump a permission from the `From` account** -- `From` account must has the permission - - -## MsgTransfer - -```golang -type MsgTransfer struct { - From sdk.AccAddress `json:"from"` - ContractID string `json:"contract_id"` - To sdk.AccAddress `json:"to"` - Amount sdk.Int `json:"amount"` -} -``` - -**Transfer message is to transfer a non-reserved fungible token** -- Signer of this message must have the amount of the tokens -- Token is subtracted from the `From` account -- Token is added to the `To` account - -## MsgModify - -```golang -type MsgModify struct { - Owner sdk.AccAddress `json:"owner"` - ContractID string `json:"contract_id"` - Changes linktype.Changes `json:"changes"` -} -``` - -**Modify message is to modify fields of token** -- `Owner` is the signer - -## MsgApprove - -```golang -type MsgApprove struct { - Approver sdk.AccAddress `json:"approver"` - ContractID string `json:"contract_id"` - Proxy sdk.AccAddress `json:"proxy"` -} -``` - -**Approve message is to approve a proxy to transfer and burn token** -- `Approver` is the signer - - - -# Syntax -| Message/Attributes | Tag | Type | -| ---- | ---- | ---- | -| Message | token/MsgIssue | github.com/line/link/x/token/internal/types.MsgIssue | - | Attributes | owner | []uint8 | - | Attributes | to | []uint8 | - | Attributes | name | string | - | Attributes | symbol | string | - | Attributes | img_uri | string | - | Attributes | meta | string | - | Attributes | amount | github.com/cosmos/cosmos-sdk/types.Int | - | Attributes | mintable | bool | - | Attributes | decimals | github.com/cosmos/cosmos-sdk/types.Int | -| Message | token/MsgModify | github.com/line/link/x/token/internal/types.MsgModify | - | Attributes | owner | []uint8 | - | Attributes | contract_id | string | - | Attributes | changes | []github.com/line/link/types.Change | -| Message | token/MsgMint | github.com/line/link/x/token/internal/types.MsgMint | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | amount | github.com/cosmos/cosmos-sdk/types.Int | -| Message | token/MsgBurn | github.com/line/link/x/token/internal/types.MsgBurn | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | amount | github.com/cosmos/cosmos-sdk/types.Int | -| Message | token/MsgGrantPermission | github.com/line/link/x/token/internal/types.MsgGrantPermission | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | permission | github.com/line/link/x/token/internal/types.Permission | -| Message | token/MsgRevokePermission | github.com/line/link/x/token/internal/types.MsgRevokePermission | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | permission | github.com/line/link/x/token/internal/types.Permission | -| Message | token/MsgTransfer | github.com/line/link/x/token/internal/types.MsgTransfer | - | Attributes | from | []uint8 | - | Attributes | contract_id | string | - | Attributes | to | []uint8 | - | Attributes | amount | github.com/cosmos/cosmos-sdk/types.Int | diff --git a/x/token/spec/04_events.md b/x/token/spec/04_events.md deleted file mode 100644 index 216badf210..0000000000 --- a/x/token/spec/04_events.md +++ /dev/null @@ -1,121 +0,0 @@ -# Events -**Not fully documented yet** -The token module emits the following events: - - -### MsgIssue -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | token | -| message | sender | {ownerAddress} | -| message | action | issue_token | -| grant_perm | to | {ownerAddress} | -| grant_perm | contract_id | {contractID} | -| grant_perm | perm | mint | -| grant_perm | to | {ownerAddress} | -| grant_perm | contract_id | {contractID} | -| grant_perm | perm | modify | -| issue | contract_id | {contractID} | -| issue | name | {name} | -| issue | symbol | {symbol} | -| issue | owner | {ownerAddress} | -| issue | to | {toAddress} | -| issue | amount | {amount} | -| issue | mintable | {mintable} | -| issue | decimals | {decimals} | - -### MsgMint -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | token | -| message | sender | {ownerAddress} | -| message | action | mint | -| mint | contract_id | {contractID} | -| mint | amount | {amount} | -| mint | from | {ownerAddress} | -| mint | to | {toAddress} | - -### MsgBurn -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | token | -| message | sender | {ownerAddress} | -| message | action | burn | -| burn | contract_id | {contractID} | -| burn | amount | {amount} | -| burn | from | {ownerAddress} | - -### MsgBurnFrom -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | token | -| message | sender | {proxyAddress} | -| message | action | burn | -| burn_from | contract_id | {contractID} | -| burn_from | proxy | {proxyAddress} | -| burn_from | from | {fromAddress} | -| burn_from | amount | {amount} | - -### MsgBurnFrom -| Type | Attribute Key | Attribute Value | -|------------------|----------------|------------------------------| -| message | module | token | -| message | sender | {proxyAddress} | -| message | action | burn_ft | -| burn_ft_from | contract_id | {contractID} | -| burn_ft_from | proxy | {proxyAddress} | -| burn_ft_from | from | {fromAddress} | -| burn_ft_from | amount | {amount}{contractID}{tokenID}| - - -### MsgTransfer -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | token | -| message | sender | {fromAddress} | -| message | action | transfer_ft | -| transfer_ft | contract_id | {contractID} | -| transfer_ft | from | {fromAddress} | -| transfer_ft | to | {toAddress} | -| transfer_ft | amount | {amount} | - -### MsgModify -| Type | Attribute Key | Attribute Value | -|-----------------------|----------------|-----------------------| -| message | module | token | -| message | sender | {ownerAddress} | -| message | action | modify_token | -| modify_token | contract_id | {contract_id} | -| modify_token | {modifiedField}| {modifiedValue} | - -### MsgGrantPermission -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | token | -| message | sender | {fromAddress} | -| message | action | grant_permission | -| grant_perm | from | {fromAddress} | -| grant_perm | to | {toAddress} | -| grant_perm | contract_id | {resource} | -| grant_perm | perm | issue/mint/burn/modify | - -### MsgRevokePermission -| Type | Attribute Key | Attribute Value | -|------------------|----------------|--------------------------| -| message | module | token | -| message | sender | {fromAddress} | -| message | action | revoke_permission | -| revoke_perm | from | {fromAddress} | -| revoke_perm | contract_id | {resource} | -| revoke_perm | perm | issue/mint/burn/modify | - -### MsgApprove -| Type | Attribute Key | Attribute Value | -|---------------|----------------|-------------------| -| message | module | token | -| message | sender | {approverAddress} | -| message | action | approve_token | -| approve_token | contract_id | {contractID} | -| approve_token | approver | {approverAddress} | -| approve_token | proxy | {proxyAddress} | - diff --git a/x/token/spec/README.md b/x/token/spec/README.md deleted file mode 100644 index e0c31c380d..0000000000 --- a/x/token/spec/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Token module specification - - - -## Abstract - -This document specifies the token module of the Link Network. - -## Contents - -1. **[Concept](01_concept.md)** -2. **[Keepers](02_keepers.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)**