From 1a821f7f889096789727c1857015b5d3b4ce77f8 Mon Sep 17 00:00:00 2001 From: ben Date: Tue, 8 Feb 2022 16:29:15 -0800 Subject: [PATCH 1/8] add stake-cw20-external-rewards --- Cargo.lock | 178 ++- Cargo.toml | 4 + .../stake-cw20-external-rewards/.cargo/config | 4 + .../stake-cw20-external-rewards/Cargo.lock | 817 ++++++++++ .../stake-cw20-external-rewards/Cargo.toml | 57 + contracts/stake-cw20-external-rewards/LICENSE | 202 +++ contracts/stake-cw20-external-rewards/NOTICE | 13 + .../stake-cw20-external-rewards/README.md | 108 ++ .../examples/schema.rs | 24 + .../schema/claimable_rewards_response.json | 19 + .../schema/config.json | 85 ++ .../schema/execute_msg.json | 82 + .../schema/info_response.json | 81 + .../schema/instantiate_msg.json | 81 + .../schema/last_claim.json | 33 + .../schema/query_msg.json | 44 + .../src/contract.rs | 1329 +++++++++++++++++ .../stake-cw20-external-rewards/src/error.rs | 44 + .../stake-cw20-external-rewards/src/lib.rs | 6 + .../stake-cw20-external-rewards/src/msg.rs | 57 + .../stake-cw20-external-rewards/src/state.rs | 27 + 21 files changed, 3266 insertions(+), 29 deletions(-) create mode 100644 contracts/stake-cw20-external-rewards/.cargo/config create mode 100644 contracts/stake-cw20-external-rewards/Cargo.lock create mode 100644 contracts/stake-cw20-external-rewards/Cargo.toml create mode 100644 contracts/stake-cw20-external-rewards/LICENSE create mode 100644 contracts/stake-cw20-external-rewards/NOTICE create mode 100644 contracts/stake-cw20-external-rewards/README.md create mode 100644 contracts/stake-cw20-external-rewards/examples/schema.rs create mode 100644 contracts/stake-cw20-external-rewards/schema/claimable_rewards_response.json create mode 100644 contracts/stake-cw20-external-rewards/schema/config.json create mode 100644 contracts/stake-cw20-external-rewards/schema/execute_msg.json create mode 100644 contracts/stake-cw20-external-rewards/schema/info_response.json create mode 100644 contracts/stake-cw20-external-rewards/schema/instantiate_msg.json create mode 100644 contracts/stake-cw20-external-rewards/schema/last_claim.json create mode 100644 contracts/stake-cw20-external-rewards/schema/query_msg.json create mode 100644 contracts/stake-cw20-external-rewards/src/contract.rs create mode 100644 contracts/stake-cw20-external-rewards/src/error.rs create mode 100644 contracts/stake-cw20-external-rewards/src/lib.rs create mode 100644 contracts/stake-cw20-external-rewards/src/msg.rs create mode 100644 contracts/stake-cw20-external-rewards/src/state.rs diff --git a/Cargo.lock b/Cargo.lock index 2ed3a1a75..70d4df0c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -168,7 +168,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64bfeaf55f8dba5646cc3daddce17cd23a60f8e0c3fbacbe6735d287d7a6e33a" dependencies = [ "cosmwasm-std", - "cw-storage-plus", + "cw-storage-plus 0.11.1", "cw-utils", "schemars", "serde", @@ -181,7 +181,26 @@ version = "0.2.5" dependencies = [ "cosmwasm-schema", "cosmwasm-std", - "cw-multi-test", + "cw-multi-test 0.11.1", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw-multi-test" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89a6191b839adef794f9bb8610d6d99857188517cca378b694e670bd1be614f" +dependencies = [ + "anyhow", + "cosmwasm-std", + "cosmwasm-storage", + "cw-storage-plus 0.10.3", + "cw0", + "derivative", + "itertools", + "prost", "schemars", "serde", "thiserror", @@ -196,7 +215,7 @@ dependencies = [ "anyhow", "cosmwasm-std", "cosmwasm-storage", - "cw-storage-plus", + "cw-storage-plus 0.11.1", "cw-utils", "derivative", "itertools", @@ -206,6 +225,17 @@ dependencies = [ "thiserror", ] +[[package]] +name = "cw-storage-plus" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b8b840947313c1a1cccf056836cd79a60b4526bdcd6582995be37dc97be4ae" +dependencies = [ + "cosmwasm-std", + "schemars", + "serde", +] + [[package]] name = "cw-storage-plus" version = "0.11.1" @@ -229,6 +259,30 @@ dependencies = [ "thiserror", ] +[[package]] +name = "cw0" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae676b6cced78a3d38ad4b01ab4ed66fc78ac191c3c0d6bfd5372cb2efd473b" +dependencies = [ + "cosmwasm-std", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw2" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7002e6f9c1a1ef3915dca704a6306ba00c39495efd928551d6077c734f9a3d8" +dependencies = [ + "cosmwasm-std", + "cw-storage-plus 0.10.3", + "schemars", + "serde", +] + [[package]] name = "cw2" version = "0.11.1" @@ -236,7 +290,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1d81d7c359d6c1fba3aa83dad7ec6f999e512571380ae62f81257c3db569743" dependencies = [ "cosmwasm-std", - "cw-storage-plus", + "cw-storage-plus 0.11.1", + "schemars", + "serde", +] + +[[package]] +name = "cw20" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56fc9d54b9b365801beb101a5c0375dceaa5a285bfc14438a7b6007f9d362142" +dependencies = [ + "cosmwasm-std", + "cw0", "schemars", "serde", ] @@ -253,6 +319,22 @@ dependencies = [ "serde", ] +[[package]] +name = "cw20-base" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4f5df0a946a4a58dd4fdb158ff1595c55774beeef76d09f108b547bce572dcf" +dependencies = [ + "cosmwasm-std", + "cw-storage-plus 0.10.3", + "cw0", + "cw2 0.10.3", + "cw20 0.10.3", + "schemars", + "serde", + "thiserror", +] + [[package]] name = "cw20-base" version = "0.11.1" @@ -260,10 +342,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62f6fc8c4cd451b418fa4f1ac2ea70595811fa9d8b4033617fe47953d7a93ceb" dependencies = [ "cosmwasm-std", - "cw-storage-plus", + "cw-storage-plus 0.11.1", "cw-utils", - "cw2", - "cw20", + "cw2 0.11.1", + "cw20 0.11.1", "schemars", "serde", "thiserror", @@ -287,16 +369,16 @@ version = "0.2.6" dependencies = [ "cosmwasm-schema", "cosmwasm-std", - "cw-multi-test", - "cw-storage-plus", + "cw-multi-test 0.11.1", + "cw-storage-plus 0.11.1", "cw-utils", - "cw2", - "cw20", - "cw20-base", + "cw2 0.11.1", + "cw20 0.11.1", + "cw20-base 0.11.1", "cw3", "schemars", "serde", - "stake-cw20", + "stake-cw20 0.2.6", "thiserror", ] @@ -306,12 +388,12 @@ version = "0.2.5" dependencies = [ "cosmwasm-schema", "cosmwasm-std", - "cw-multi-test", - "cw-storage-plus", + "cw-multi-test 0.11.1", + "cw-storage-plus 0.11.1", "cw-utils", - "cw2", - "cw20", - "cw20-base", + "cw2 0.11.1", + "cw20 0.11.1", + "cw20-base 0.11.1", "cw3", "cw4", "cw4-group", @@ -327,7 +409,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41445666e3f6284c72f569b2240bb52d0add94bb448e169d30ae28fe000cfaeb" dependencies = [ "cosmwasm-std", - "cw-storage-plus", + "cw-storage-plus 0.11.1", "schemars", "serde", ] @@ -340,9 +422,9 @@ checksum = "db3389be9a6d350cc5ed9918af4070007c9acc360e515788a10885536b972764" dependencies = [ "cosmwasm-std", "cw-controllers", - "cw-storage-plus", + "cw-storage-plus 0.11.1", "cw-utils", - "cw2", + "cw2 0.11.1", "cw4", "schemars", "serde", @@ -358,10 +440,10 @@ dependencies = [ "cosmwasm-schema", "cosmwasm-std", "cosmwasm-storage", - "cw-multi-test", - "cw-storage-plus", + "cw-multi-test 0.11.1", + "cw-storage-plus 0.11.1", "cw-utils", - "cw2", + "cw2 0.11.1", "cw4", "cw4-group", "schemars", @@ -751,14 +833,52 @@ dependencies = [ "cosmwasm-std", "cosmwasm-storage", "cw-controllers", - "cw-multi-test", - "cw-storage-plus", + "cw-multi-test 0.11.1", + "cw-storage-plus 0.11.1", + "cw-utils", + "cw2 0.11.1", + "cw20 0.11.1", + "cw20-base 0.11.1", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "stake-cw20" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfbd45133276dbe4d6588899f4d4d06fdb9f16921fd1394affc0bccc9a5cb0b6" +dependencies = [ + "cosmwasm-std", + "cosmwasm-storage", + "cw-controllers", + "cw-storage-plus 0.11.1", "cw-utils", - "cw2", - "cw20", - "cw20-base", + "cw2 0.11.1", + "cw20 0.11.1", + "cw20-base 0.11.1", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "stake-cw20-external-rewards" +version = "0.1.0" +dependencies = [ + "anyhow", + "cosmwasm-schema", + "cosmwasm-std", + "cosmwasm-storage", + "cw-multi-test 0.10.3", + "cw-storage-plus 0.10.3", + "cw2 0.10.3", + "cw20 0.10.3", + "cw20-base 0.10.3", "schemars", "serde", + "stake-cw20 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "thiserror", ] diff --git a/Cargo.toml b/Cargo.toml index 41fb9414e..ff6c1a334 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,10 @@ incremental = false codegen-units = 1 incremental = false +[profile.release.package.stake-cw20-external-rewards] +codegen-units = 1 +incremental = false + [profile.release.package.cw-distribution] codegen-units = 1 incremental = false diff --git a/contracts/stake-cw20-external-rewards/.cargo/config b/contracts/stake-cw20-external-rewards/.cargo/config new file mode 100644 index 000000000..336b618a1 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/.cargo/config @@ -0,0 +1,4 @@ +[alias] +wasm = "build --release --target wasm32-unknown-unknown" +unit-test = "test --lib" +schema = "run --example schema" diff --git a/contracts/stake-cw20-external-rewards/Cargo.lock b/contracts/stake-cw20-external-rewards/Cargo.lock new file mode 100644 index 000000000..845e7283c --- /dev/null +++ b/contracts/stake-cw20-external-rewards/Cargo.lock @@ -0,0 +1,817 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anyhow" +version = "1.0.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0" + +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", +] + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "const-oid" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c32f031ea41b4291d695026c023b95d59db2d8a2c7640800ed56bc8f510f22" + +[[package]] +name = "cosmwasm-crypto" +version = "1.0.0-beta4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f903ebbabc0d4880dbc76148efb8be8fc29fa4bf294c440c3d70da1c8bcafff7" +dependencies = [ + "digest", + "ed25519-zebra", + "k256", + "rand_core 0.5.1", + "thiserror", +] + +[[package]] +name = "cosmwasm-derive" +version = "1.0.0-beta4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "832bebef577ecb394603de8e2bf0de429b74aa364e17dec18e15ce37e71b0cae" +dependencies = [ + "syn", +] + +[[package]] +name = "cosmwasm-schema" +version = "1.0.0-beta" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e4b3f6933f94acdd3ddb931af4870c2002e3331a4a8b247a4ef070dd31ccb0" +dependencies = [ + "schemars", + "serde_json", +] + +[[package]] +name = "cosmwasm-std" +version = "1.0.0-beta4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6238c45840cc9de5a39f0f619e3a4f7c38c5d2c6ac9e3e4d72751ee045e6d7da" +dependencies = [ + "base64", + "cosmwasm-crypto", + "cosmwasm-derive", + "schemars", + "serde", + "serde-json-wasm", + "thiserror", + "uint", +] + +[[package]] +name = "cosmwasm-storage" +version = "1.0.0-beta" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "665cf97ad42be46936f6e6739711824a9bf21c440a6c98e185a3404aef0c3b81" +dependencies = [ + "cosmwasm-std", + "serde", +] + +[[package]] +name = "cpufeatures" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66c99696f6c9dd7f35d486b9d04d7e6e202aa3e8c40d553f2fdf5e7e0c6a71ef" +dependencies = [ + "libc", +] + +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" + +[[package]] +name = "crypto-bigint" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b32a398eb1ccfbe7e4f452bc749c44d38dd732e9a253f19da224c416f00ee7f4" +dependencies = [ + "generic-array", + "rand_core 0.6.3", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-mac" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d1a86f49236c215f271d40892d5fc950490551400b02ef360692c29815c714" +dependencies = [ + "generic-array", + "subtle", +] + +[[package]] +name = "curve25519-dalek" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b9fdf9972b2bd6af2d913799d9ebc165ea4d2e65878e329d9c6b372c4491b61" +dependencies = [ + "byteorder", + "digest", + "rand_core 0.5.1", + "subtle", + "zeroize", +] + +[[package]] +name = "cw-controllers" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64bfeaf55f8dba5646cc3daddce17cd23a60f8e0c3fbacbe6735d287d7a6e33a" +dependencies = [ + "cosmwasm-std", + "cw-storage-plus 0.11.1", + "cw-utils", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw-multi-test" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "670f079c08ee111664b4d01f845ab11aa1f722a51013bd71bfe9d930f323406d" +dependencies = [ + "anyhow", + "cosmwasm-std", + "cosmwasm-storage", + "cw-storage-plus 0.10.0", + "cw0", + "derivative", + "itertools", + "prost", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw-storage-plus" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae8575a3517f88581f0a48f7021f01a0ebde1b65d47d33b54d1cba3bd9028f" +dependencies = [ + "cosmwasm-std", + "schemars", + "serde", +] + +[[package]] +name = "cw-storage-plus" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d7ee1963302b0ac2a9d42fe0faec826209c17452bfd36fbfd9d002a88929261" +dependencies = [ + "cosmwasm-std", + "schemars", + "serde", +] + +[[package]] +name = "cw-utils" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef842a1792e4285beff7b3b518705f760fa4111dc1e296e53f3e92d1ef7f6220" +dependencies = [ + "cosmwasm-std", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw0" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7328a0b49764fb13e4c67fbe1e5527db1f33ed8c398b55efa6c0597fee5a58" +dependencies = [ + "cosmwasm-std", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw2" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4dc7be3e594753983f9c0a3ef23a1a3fb3afc2155f65ea8522c66703c8bd90f" +dependencies = [ + "cosmwasm-std", + "cw-storage-plus 0.10.0", + "schemars", + "serde", +] + +[[package]] +name = "cw2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1d81d7c359d6c1fba3aa83dad7ec6f999e512571380ae62f81257c3db569743" +dependencies = [ + "cosmwasm-std", + "cw-storage-plus 0.11.1", + "schemars", + "serde", +] + +[[package]] +name = "cw20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1f78c56916b79959930645446abdf29cd55df464e6057ba92252410f00c8ddb" +dependencies = [ + "cosmwasm-std", + "cw0", + "schemars", + "serde", +] + +[[package]] +name = "cw20" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9671d7edef5608acaf5b2f1e473ee3f501eced2cd4f7392e2106c8cf02ba0720" +dependencies = [ + "cosmwasm-std", + "cw-utils", + "schemars", + "serde", +] + +[[package]] +name = "cw20-base" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30b9c237cb0713816588c0cc6fb49dbdaf2688b184d441518436b0c986fb45dd" +dependencies = [ + "cosmwasm-std", + "cw-storage-plus 0.10.0", + "cw0", + "cw2 0.10.0", + "cw20 0.10.2", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw20-base" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62f6fc8c4cd451b418fa4f1ac2ea70595811fa9d8b4033617fe47953d7a93ceb" +dependencies = [ + "cosmwasm-std", + "cw-storage-plus 0.11.1", + "cw-utils", + "cw2 0.11.1", + "cw20 0.11.1", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "der" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31e21d2d0f22cde6e88694108429775c0219760a07779bf96503b434a03d7412" +dependencies = [ + "const-oid", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + +[[package]] +name = "dyn-clone" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee2626afccd7561a06cf1367e2950c4718ea04565e20fb5029b6c7d8ad09abcf" + +[[package]] +name = "ecdsa" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "713c32426287891008edb98f8b5c6abb2130aa043c93a818728fcda78606f274" +dependencies = [ + "der", + "elliptic-curve", + "hmac", + "signature", +] + +[[package]] +name = "ed25519-zebra" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a128b76af6dd4b427e34a6fd43dc78dbfe73672ec41ff615a2414c1a0ad0409" +dependencies = [ + "curve25519-dalek", + "hex", + "rand_core 0.5.1", + "serde", + "sha2", + "thiserror", +] + +[[package]] +name = "either" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" + +[[package]] +name = "elliptic-curve" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "069397e10739989e400628cbc0556a817a8a64119d7a2315767f4456e1332c23" +dependencies = [ + "crypto-bigint", + "ff", + "generic-array", + "group", + "pkcs8", + "rand_core 0.6.3", + "subtle", + "zeroize", +] + +[[package]] +name = "ff" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63eec06c61e487eecf0f7e6e6372e596a81922c28d33e645d6983ca6493a1af0" +dependencies = [ + "rand_core 0.6.3", + "subtle", +] + +[[package]] +name = "generic-array" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.10.2+wasi-snapshot-preview1", +] + +[[package]] +name = "group" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c363a5301b8f153d80747126a04b3c82073b9fe3130571a9d170cacdeaf7912" +dependencies = [ + "ff", + "rand_core 0.6.3", + "subtle", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a2a2320eb7ec0ebe8da8f744d7812d9fc4cb4d09344ac01898dbcb6a20ae69b" +dependencies = [ + "crypto-mac", + "digest", +] + +[[package]] +name = "itertools" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ddb889f9d0d08a67338271fa9b62996bc788c7796a5c18cf057420aaed5eaf" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" + +[[package]] +name = "k256" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "903ae2481bcdfdb7b68e0a9baa4b7c9aff600b9ae2e8e5bb5833b8c91ab851ea" +dependencies = [ + "cfg-if", + "ecdsa", + "elliptic-curve", + "sha2", +] + +[[package]] +name = "libc" +version = "0.2.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7f823d141fe0a24df1e23b4af4e3c7ba9e5966ec514ea068c93024aa7deb765" + +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + +[[package]] +name = "pkcs8" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbee84ed13e44dd82689fa18348a49934fa79cc774a344c42fc9b301c71b140a" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "proc-macro2" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "prost" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de5e2533f59d08fcf364fd374ebda0692a70bd6d7e66ef97f306f45c6c5d8020" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "600d2f334aa05acb02a755e217ef1ab6dea4d51b58b7846588b747edec04efba" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_core" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +dependencies = [ + "getrandom 0.2.3", +] + +[[package]] +name = "ryu" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" + +[[package]] +name = "schemars" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6b5a3c80cea1ab61f4260238409510e814e38b4b563c06044edf91e7dc070e3" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41ae4dce13e8614c46ac3c38ef1c0d668b101df6ac39817aebdaa26642ddae9b" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn", +] + +[[package]] +name = "serde" +version = "1.0.136" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde-json-wasm" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "042ac496d97e5885149d34139bad1d617192770d7eb8f1866da2317ff4501853" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.136" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive_internals" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dbab34ca63057a1f15280bdf3c39f2b1eb1b54c17e98360e511637aef7418c6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "336b10da19a12ad094b59d870ebde26a45402e5b470add4b5fd03c5048a32127" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b362ae5752fd2137731f9fa25fd4d9058af34666ca1966fb969119cc35719f12" +dependencies = [ + "block-buffer", + "cfg-if", + "cpufeatures", + "digest", + "opaque-debug", +] + +[[package]] +name = "signature" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c19772be3c4dd2ceaacf03cb41d5885f2a02c4d8804884918e3a258480803335" +dependencies = [ + "digest", + "rand_core 0.6.3", +] + +[[package]] +name = "spki" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "987637c5ae6b3121aba9d513f869bd2bff11c4cc086c22473befd6649c0bd521" +dependencies = [ + "der", +] + +[[package]] +name = "stake-cw20" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfbd45133276dbe4d6588899f4d4d06fdb9f16921fd1394affc0bccc9a5cb0b6" +dependencies = [ + "cosmwasm-std", + "cosmwasm-storage", + "cw-controllers", + "cw-storage-plus 0.11.1", + "cw-utils", + "cw2 0.11.1", + "cw20 0.11.1", + "cw20-base 0.11.1", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "stake-cw20-external-rewards" +version = "0.1.0" +dependencies = [ + "anyhow", + "cosmwasm-schema", + "cosmwasm-std", + "cosmwasm-storage", + "cw-multi-test", + "cw-storage-plus 0.10.0", + "cw2 0.10.0", + "cw20 0.10.2", + "cw20-base 0.10.0", + "schemars", + "serde", + "stake-cw20", + "thiserror", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + +[[package]] +name = "syn" +version = "1.0.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1873d832550d4588c3dbc20f01361ab00bfe741048f71e3fecf145a7cc18b29c" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "thiserror" +version = "1.0.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "typenum" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" + +[[package]] +name = "uint" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6470ab50f482bde894a037a57064480a246dbfdd5960bd65a44824693f08da5f" +dependencies = [ + "byteorder", + "crunchy", + "hex", + "static_assertions", +] + +[[package]] +name = "unicode-xid" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" + +[[package]] +name = "version_check" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.10.2+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" + +[[package]] +name = "zeroize" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "377db0846015f7ae377174787dd452e1c5f5a9050bc6f954911d01f116daa0cd" diff --git a/contracts/stake-cw20-external-rewards/Cargo.toml b/contracts/stake-cw20-external-rewards/Cargo.toml new file mode 100644 index 000000000..b4f6e1ed2 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "stake-cw20-external-rewards" +version = "0.1.0" +authors = ["ben2x4 "] +edition = "2018" + +exclude = [ + # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. + "contract.wasm", + "hash.txt", +] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["cdylib", "rlib"] + +[profile.release] +opt-level = 3 +debug = false +rpath = false +lto = true +debug-assertions = false +codegen-units = 1 +panic = 'abort' +incremental = false +overflow-checks = true + +[features] +# for more explicit tests, cargo test --features=backtraces +backtraces = ["cosmwasm-std/backtraces"] +# use library feature to disable all instantiate/execute/query exports +library = [] + +[package.metadata.scripts] +optimize = """docker run --rm -v "$(pwd)":/code \ + --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ + --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ + cosmwasm/rust-optimizer:0.12.3 +""" + +[dependencies] +cosmwasm-std = { version = "1.0.0-beta" } +cosmwasm-storage = { version = "1.0.0-beta" } +cw-storage-plus = "0.10" +cw2 = "0.10" +cw20 = "0.10" +cw20-base = { version = "0.10.0", features = ["library"] } +stake-cw20 = { version = "0.2.6", features = ["library"] } +schemars = "0.8.3" +serde = { version = "1.0.127", default-features = false, features = ["derive"] } +thiserror = { version = "1.0.26" } + +[dev-dependencies] +cosmwasm-schema = { version = "1.0.0-beta" } +cw-multi-test = { version = "0.10.0" } +anyhow = { version = "1.0.51"} diff --git a/contracts/stake-cw20-external-rewards/LICENSE b/contracts/stake-cw20-external-rewards/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/contracts/stake-cw20-external-rewards/NOTICE b/contracts/stake-cw20-external-rewards/NOTICE new file mode 100644 index 000000000..e607994b7 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/NOTICE @@ -0,0 +1,13 @@ +Copyright 2021 ben2x4 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/contracts/stake-cw20-external-rewards/README.md b/contracts/stake-cw20-external-rewards/README.md new file mode 100644 index 000000000..0a87caefd --- /dev/null +++ b/contracts/stake-cw20-external-rewards/README.md @@ -0,0 +1,108 @@ +# CosmWasm Starter Pack + +This is a template to build smart contracts in Rust to run inside a +[Cosmos SDK](https://github.com/cosmos/cosmos-sdk) module on all chains that enable it. +To understand the framework better, please read the overview in the +[cosmwasm repo](https://github.com/CosmWasm/cosmwasm/blob/master/README.md), +and dig into the [cosmwasm docs](https://www.cosmwasm.com). +This assumes you understand the theory and just want to get coding. + +## Creating a new repo from template + +Assuming you have a recent version of rust and cargo (v1.55.0+) installed +(via [rustup](https://rustup.rs/)), +then the following should get you a new repo to start a contract: + +(Note that recent cargo-generate requires Rust 1.55 features or produces a compile error) + +Install [cargo-generate](https://github.com/ashleygwilliams/cargo-generate) and cargo-run-script. +Unless you did that before, run this line now: + +```sh +cargo install cargo-generate --features vendored-openssl +cargo install cargo-run-script +``` + +Now, use it to create your new contract. +Go to the folder in which you want to place it and run: + + +**Latest: 1.0.0-beta** + +```sh +cargo generate --git https://github.com/CosmWasm/cw-template.git --name PROJECT_NAME +```` + +**Older Version** + +Pass version as branch flag: + +```sh +cargo generate --git https://github.com/CosmWasm/cw-template.git --branch --name PROJECT_NAME +```` + +Example: + +```sh +cargo generate --git https://github.com/CosmWasm/cw-template.git --branch 0.16 --name PROJECT_NAME +``` + +You will now have a new folder called `PROJECT_NAME` (I hope you changed that to something else) +containing a simple working contract and build system that you can customize. + +## Create a Repo + +After generating, you have a initialized local git repo, but no commits, and no remote. +Go to a server (eg. github) and create a new upstream repo (called `YOUR-GIT-URL` below). +Then run the following: + +```sh +# this is needed to create a valid Cargo.lock file (see below) +cargo check +git branch -M main +git add . +git commit -m 'Initial Commit' +git remote add origin YOUR-GIT-URL +git push -u origin main +``` + +## CI Support + +We have template configurations for both [GitHub Actions](.github/workflows/Basic.yml) +and [Circle CI](.circleci/config.yml) in the generated project, so you can +get up and running with CI right away. + +One note is that the CI runs all `cargo` commands +with `--locked` to ensure it uses the exact same versions as you have locally. This also means +you must have an up-to-date `Cargo.lock` file, which is not auto-generated. +The first time you set up the project (or after adding any dep), you should ensure the +`Cargo.lock` file is updated, so the CI will test properly. This can be done simply by +running `cargo check` or `cargo unit-test`. + +## Using your project + +Once you have your custom repo, you should check out [Developing](./Developing.md) to explain +more on how to run tests and develop code. Or go through the +[online tutorial](https://docs.cosmwasm.com/) to get a better feel +of how to develop. + +[Publishing](./Publishing.md) contains useful information on how to publish your contract +to the world, once you are ready to deploy it on a running blockchain. And +[Importing](./Importing.md) contains information about pulling in other contracts or crates +that have been published. + +Please replace this README file with information about your specific project. You can keep +the `Developing.md` and `Publishing.md` files as useful referenced, but please set some +proper description in the README. + +## Gitpod integration + +[Gitpod](https://www.gitpod.io/) container-based development platform will be enabled on your project by default. + +Workspace contains: + - **rust**: for builds + - [wasmd](https://github.com/CosmWasm/wasmd): for local node setup and client + - **jq**: shell JSON manipulation tool + +Follow [Gitpod Getting Started](https://www.gitpod.io/docs/getting-started) and launch your workspace. + diff --git a/contracts/stake-cw20-external-rewards/examples/schema.rs b/contracts/stake-cw20-external-rewards/examples/schema.rs new file mode 100644 index 000000000..471c9237f --- /dev/null +++ b/contracts/stake-cw20-external-rewards/examples/schema.rs @@ -0,0 +1,24 @@ +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use stake_cw20_external_rewards::msg::{ + ClaimableRewardsResponse, ExecuteMsg, InfoResponse, InstantiateMsg, QueryMsg, +}; +use stake_cw20_external_rewards::state::{Config, LastClaim}; + +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!(InstantiateMsg), &out_dir); + export_schema(&schema_for!(ExecuteMsg), &out_dir); + export_schema(&schema_for!(QueryMsg), &out_dir); + export_schema(&schema_for!(Config), &out_dir); + export_schema(&schema_for!(LastClaim), &out_dir); + export_schema(&schema_for!(InfoResponse), &out_dir); + export_schema(&schema_for!(ClaimableRewardsResponse), &out_dir); +} diff --git a/contracts/stake-cw20-external-rewards/schema/claimable_rewards_response.json b/contracts/stake-cw20-external-rewards/schema/claimable_rewards_response.json new file mode 100644 index 000000000..6866dd630 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/schema/claimable_rewards_response.json @@ -0,0 +1,19 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ClaimableRewardsResponse", + "type": "object", + "required": [ + "amount" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + } + }, + "definitions": { + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/stake-cw20-external-rewards/schema/config.json b/contracts/stake-cw20-external-rewards/schema/config.json new file mode 100644 index 000000000..3b10be52a --- /dev/null +++ b/contracts/stake-cw20-external-rewards/schema/config.json @@ -0,0 +1,85 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Config", + "type": "object", + "required": [ + "denom", + "end_block", + "funded", + "payment_block_delta", + "payment_per_block", + "staking_contract", + "start_block", + "total_amount" + ], + "properties": { + "denom": { + "$ref": "#/definitions/Denom" + }, + "end_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "funded": { + "type": "boolean" + }, + "payment_block_delta": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "payment_per_block": { + "$ref": "#/definitions/Uint128" + }, + "staking_contract": { + "$ref": "#/definitions/Addr" + }, + "start_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "total_amount": { + "$ref": "#/definitions/Uint128" + } + }, + "definitions": { + "Addr": { + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" + }, + "Denom": { + "oneOf": [ + { + "type": "object", + "required": [ + "native" + ], + "properties": { + "native": { + "type": "string" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "cw20" + ], + "properties": { + "cw20": { + "$ref": "#/definitions/Addr" + } + }, + "additionalProperties": false + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/stake-cw20-external-rewards/schema/execute_msg.json b/contracts/stake-cw20-external-rewards/schema/execute_msg.json new file mode 100644 index 000000000..be6af13c1 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/schema/execute_msg.json @@ -0,0 +1,82 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ExecuteMsg", + "oneOf": [ + { + "type": "object", + "required": [ + "claim" + ], + "properties": { + "claim": { + "type": "object" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "receive" + ], + "properties": { + "receive": { + "$ref": "#/definitions/Cw20ReceiveMsg" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "claim_up_to_block" + ], + "properties": { + "claim_up_to_block": { + "type": "object", + "required": [ + "block" + ], + "properties": { + "block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + } + } + } + }, + "additionalProperties": false + } + ], + "definitions": { + "Binary": { + "description": "Binary is a wrapper around Vec to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec", + "type": "string" + }, + "Cw20ReceiveMsg": { + "description": "Cw20ReceiveMsg should be de/serialized under `Receive()` variant in a ExecuteMsg", + "type": "object", + "required": [ + "amount", + "msg", + "sender" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "msg": { + "$ref": "#/definitions/Binary" + }, + "sender": { + "type": "string" + } + } + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/stake-cw20-external-rewards/schema/info_response.json b/contracts/stake-cw20-external-rewards/schema/info_response.json new file mode 100644 index 000000000..be5076aed --- /dev/null +++ b/contracts/stake-cw20-external-rewards/schema/info_response.json @@ -0,0 +1,81 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "InfoResponse", + "type": "object", + "required": [ + "denom", + "end_block", + "payment_block_delta", + "payment_per_block", + "staking_contract", + "start_block", + "total_amount" + ], + "properties": { + "denom": { + "$ref": "#/definitions/Denom" + }, + "end_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "payment_block_delta": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "payment_per_block": { + "$ref": "#/definitions/Uint128" + }, + "staking_contract": { + "type": "string" + }, + "start_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "total_amount": { + "$ref": "#/definitions/Uint128" + } + }, + "definitions": { + "Addr": { + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" + }, + "Denom": { + "oneOf": [ + { + "type": "object", + "required": [ + "native" + ], + "properties": { + "native": { + "type": "string" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "cw20" + ], + "properties": { + "cw20": { + "$ref": "#/definitions/Addr" + } + }, + "additionalProperties": false + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/stake-cw20-external-rewards/schema/instantiate_msg.json b/contracts/stake-cw20-external-rewards/schema/instantiate_msg.json new file mode 100644 index 000000000..a84e39346 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/schema/instantiate_msg.json @@ -0,0 +1,81 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "InstantiateMsg", + "type": "object", + "required": [ + "denom", + "distribution_token", + "end_block", + "payment_block_delta", + "payment_per_block", + "start_block", + "total_amount" + ], + "properties": { + "denom": { + "$ref": "#/definitions/Denom" + }, + "distribution_token": { + "type": "string" + }, + "end_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "payment_block_delta": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "payment_per_block": { + "$ref": "#/definitions/Uint128" + }, + "start_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "total_amount": { + "$ref": "#/definitions/Uint128" + } + }, + "definitions": { + "Addr": { + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" + }, + "Denom": { + "oneOf": [ + { + "type": "object", + "required": [ + "native" + ], + "properties": { + "native": { + "type": "string" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "cw20" + ], + "properties": { + "cw20": { + "$ref": "#/definitions/Addr" + } + }, + "additionalProperties": false + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/stake-cw20-external-rewards/schema/last_claim.json b/contracts/stake-cw20-external-rewards/schema/last_claim.json new file mode 100644 index 000000000..d8c799472 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/schema/last_claim.json @@ -0,0 +1,33 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "LastClaim", + "type": "object", + "required": [ + "block_height", + "time" + ], + "properties": { + "block_height": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "time": { + "$ref": "#/definitions/Timestamp" + } + }, + "definitions": { + "Timestamp": { + "description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```", + "allOf": [ + { + "$ref": "#/definitions/Uint64" + } + ] + }, + "Uint64": { + "description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/stake-cw20-external-rewards/schema/query_msg.json b/contracts/stake-cw20-external-rewards/schema/query_msg.json new file mode 100644 index 000000000..e1de5c2ee --- /dev/null +++ b/contracts/stake-cw20-external-rewards/schema/query_msg.json @@ -0,0 +1,44 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "QueryMsg", + "oneOf": [ + { + "type": "object", + "required": [ + "info" + ], + "properties": { + "info": { + "type": "object" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "claimable_rewards" + ], + "properties": { + "claimable_rewards": { + "type": "object", + "required": [ + "address" + ], + "properties": { + "address": { + "$ref": "#/definitions/Addr" + } + } + } + }, + "additionalProperties": false + } + ], + "definitions": { + "Addr": { + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" + } + } +} diff --git a/contracts/stake-cw20-external-rewards/src/contract.rs b/contracts/stake-cw20-external-rewards/src/contract.rs new file mode 100644 index 000000000..ce47d60d8 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/src/contract.rs @@ -0,0 +1,1329 @@ +#[cfg(not(feature = "library"))] +use cosmwasm_std::entry_point; +use cosmwasm_std::{ + from_binary, to_binary, Addr, BankMsg, Binary, Coin, CosmosMsg, Deps, DepsMut, Env, + MessageInfo, QuerierWrapper, Response, StdResult, Timestamp, Uint128, WasmMsg, +}; +use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg, Denom}; +use std::cmp::min; + +use crate::error::ContractError; +use crate::error::ContractError::RewardsNotStarted; +use crate::msg::{ + ClaimableRewardsResponse, ExecuteMsg, InfoResponse, InstantiateMsg, QueryMsg, ReceiveMsg, +}; +use crate::state::{Config, LastClaim, CONFIG, LAST_CLAIMED}; + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn instantiate( + deps: DepsMut, + env: Env, + _info: MessageInfo, + msg: InstantiateMsg, +) -> Result { + validate_instantiate_msg(&env, &msg)?; + let config = Config { + start_block: msg.start_block, + end_block: msg.end_block, + payment_per_block: msg.payment_per_block, + total_amount: msg.total_amount, + denom: msg.denom.clone(), + staking_contract: deps.api.addr_validate(&*msg.distribution_token)?, + funded: match msg.denom { + Denom::Native(_) => true, + Denom::Cw20(_) => false, + }, + payment_block_delta: msg.payment_block_delta, + }; + CONFIG.save(deps.storage, &config)?; + Ok(Response::default()) +} + +pub fn validate_instantiate_msg(env: &Env, msg: &InstantiateMsg) -> Result<(), ContractError> { + if env.block.height > msg.start_block { + return Err(ContractError::StartBlockAlreadyOccurred {}); + } + if msg.start_block > msg.end_block { + return Err(ContractError::StartBlockAfterEndBlock {}); + } + if msg.start_block % msg.payment_block_delta != 0 { + return Err(ContractError::StartBlockNotDivisibleByPaymentDelta {}); + } + if msg.end_block % msg.payment_block_delta != 0 { + return Err(ContractError::EndBlockNotDivisibleByPaymentDelta {}); + } + let duration = Uint128::from(((msg.end_block - msg.start_block) / msg.payment_block_delta) + 1); + let calculated_total = duration + .checked_mul(msg.payment_per_block) + .map_err(cosmwasm_std::StdError::overflow)? + .checked_mul(Uint128::from(msg.payment_block_delta)) + .map_err(cosmwasm_std::StdError::overflow)?; + if calculated_total != msg.total_amount { + return Err(ContractError::InvalidTotalAmount {}); + } + Ok(()) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn execute( + deps: DepsMut, + _env: Env, + info: MessageInfo, + msg: ExecuteMsg, +) -> Result { + match msg { + ExecuteMsg::Claim {} => try_claim(deps, _env.clone(), info, _env.block.height), + ExecuteMsg::Receive(msg) => try_receive(deps, _env, info, msg), + ExecuteMsg::ClaimUpToBlock { block } => try_claim(deps, _env, info, block), + } +} + +pub fn try_receive( + deps: DepsMut, + env: Env, + info: MessageInfo, + wrapper: Cw20ReceiveMsg, +) -> Result { + let msg: ReceiveMsg = from_binary(&wrapper.msg)?; + match msg { + ReceiveMsg::Fund {} => try_fund(deps, env, info, wrapper.amount), + } +} + +pub fn try_fund( + deps: DepsMut, + _env: Env, + info: MessageInfo, + amount: Uint128, +) -> Result { + let mut config = CONFIG.load(deps.storage)?; + if config.funded { + return Err(ContractError::AlreadyFunded {}); + } + if config.denom != Denom::Cw20(info.sender) { + return Err(ContractError::IncorrectDenom {}); + } + if amount != config.total_amount { + return Err(ContractError::IncorrectFundingAmount { + received: amount, + expected: config.total_amount, + }); + } + config.funded = true; + CONFIG.save(deps.storage, &config)?; + Ok(Response::new() + .add_attribute("action", "fund") + .add_attribute("amount", amount)) +} + +pub fn try_claim( + deps: DepsMut, + env: Env, + info: MessageInfo, + up_to_block: u64, +) -> Result { + if up_to_block > env.block.height { + return Err(ContractError::InvalidFutureBlock {}); + } + let config = CONFIG.load(deps.storage)?; + if !config.funded { + return Err(ContractError::NotFunded {}); + }; + if env.block.height < config.start_block { + return Err(RewardsNotStarted { + current_block: env.block.height, + start_block: config.start_block, + }); + } + let last_claimed = LAST_CLAIMED + .may_load(deps.storage, info.sender.clone())? + .unwrap_or(LastClaim { + block_height: config.start_block, + time: Timestamp::default(), + }); + let (amount_owed, new_claim_height) = get_amount_owed( + deps.as_ref(), + &info.sender, + &config, + last_claimed.block_height, + up_to_block, + )?; + + if amount_owed == Uint128::zero() { + return Err(ContractError::ZeroClaimable {}); + } + + let new_claim = LastClaim { + block_height: new_claim_height, + time: env.block.time, + }; + LAST_CLAIMED.save(deps.storage, info.sender.clone(), &new_claim)?; + + let payment_msg = get_payment_msg(&env, &config, &info, amount_owed)?; + + Ok(Response::new() + .add_message(payment_msg) + .add_attribute("action", "claim") + .add_attribute("amount", amount_owed)) +} + +fn get_amount_owed( + deps: Deps, + address: &Addr, + config: &Config, + last_claimed: u64, + up_to_block: u64, +) -> StdResult<(Uint128, u64)> { + let delta = config.payment_block_delta; + let mut current_block = last_claimed; + let mut amount = Uint128::zero(); + while current_block <= min(up_to_block, config.end_block) { + let stake_info = get_stake_info_at_height(deps.querier, config, address, current_block)?; + if stake_info.balance > Uint128::zero() { + amount += ((Uint128::from(delta) * config.payment_per_block) * stake_info.balance) + .checked_div(stake_info.total)? + } + current_block += delta; + } + Ok((amount, current_block)) +} + +fn get_payment_msg( + _env: &Env, + config: &Config, + info: &MessageInfo, + amount: Uint128, +) -> StdResult { + Ok(match config.clone().denom { + Denom::Native(denom) => BankMsg::Send { + to_address: info.sender.to_string(), + amount: vec![Coin { amount, denom }], + } + .into(), + Denom::Cw20(address) => { + let transfer = Cw20ExecuteMsg::Transfer { + recipient: info.sender.to_string(), + amount, + }; + WasmMsg::Execute { + contract_addr: address.to_string(), + msg: to_binary(&transfer)?, + funds: vec![], + } + .into() + } + }) +} + +struct StakeInfo { + pub balance: Uint128, + pub total: Uint128, +} +fn get_stake_info_at_height( + deps: QuerierWrapper, + config: &Config, + address: &Addr, + height: u64, +) -> StdResult { + let balance_query = stake_cw20::msg::QueryMsg::StakedBalanceAtHeight { + address: address.to_string(), + height: Some(height), + }; + let balance_response: stake_cw20::msg::StakedBalanceAtHeightResponse = + deps.query_wasm_smart(config.staking_contract.to_string(), &balance_query)?; + let total_query = stake_cw20::msg::QueryMsg::TotalStakedAtHeight { + height: Some(height), + }; + let total_response: stake_cw20::msg::TotalStakedAtHeightResponse = + deps.query_wasm_smart(config.staking_contract.to_string(), &total_query)?; + Ok(StakeInfo { + balance: balance_response.balance, + total: total_response.total, + }) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult { + match msg { + QueryMsg::Info {} => to_binary(&query_info(deps)?), + QueryMsg::ClaimableRewards { address } => { + to_binary(&query_claimable_rewards(deps, env, address)?) + } + } +} + +pub fn query_info(deps: Deps) -> StdResult { + let config = CONFIG.load(deps.storage)?; + Ok(InfoResponse { + start_block: config.start_block, + end_block: config.end_block, + payment_per_block: config.payment_per_block, + total_amount: config.total_amount, + denom: config.denom, + staking_contract: config.staking_contract.to_string(), + payment_block_delta: config.payment_block_delta, + }) +} + +pub fn query_claimable_rewards( + deps: Deps, + env: Env, + address: Addr, +) -> StdResult { + let config = CONFIG.load(deps.storage)?; + let last_claimed = LAST_CLAIMED + .may_load(deps.storage, address.clone())? + .unwrap_or(LastClaim { + block_height: config.start_block, + time: Timestamp::default(), + }); + let (amount, _) = get_amount_owed( + deps, + &address, + &config, + last_claimed.block_height, + env.block.height, + )?; + Ok(ClaimableRewardsResponse { amount }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::borrow::BorrowMut; + + use crate::msg::ExecuteMsg::{Claim, ClaimUpToBlock}; + use crate::msg::QueryMsg::{ClaimableRewards, Info}; + use cosmwasm_std::Empty; + use cw20::{Cw20Coin, Cw20Contract}; + use cw_multi_test::{next_block, App, Contract, ContractWrapper, Executor}; + + const OWNER: &str = "owner0001"; + const ADDR1: &str = "addr0001"; + const ADDR2: &str = "addr0002"; + const ADDR3: &str = "addr0003"; + const ADDR4: &str = "addr0004"; + const INITIAL_BALANCE: u32 = 1000; + + pub fn contract_rewards() -> Box> { + let contract = ContractWrapper::new( + crate::contract::execute, + crate::contract::instantiate, + crate::contract::query, + ); + Box::new(contract) + } + + pub fn contract_cw20() -> Box> { + let contract = ContractWrapper::new( + cw20_base::contract::execute, + cw20_base::contract::instantiate, + cw20_base::contract::query, + ); + Box::new(contract) + } + + pub fn contract_stake_cw20() -> Box> { + let contract = ContractWrapper::new( + stake_cw20::contract::execute, + stake_cw20::contract::instantiate, + stake_cw20::contract::query, + ); + Box::new(contract) + } + + fn mock_app() -> App { + App::default() + } + + // uploads code and returns address of cw20 contract + fn instantiate_cw20(app: &mut App) -> Addr { + let cw20_id = app.store_code(contract_cw20()); + let msg = cw20_base::msg::InstantiateMsg { + name: "test".to_string(), + symbol: "STAKE".to_string(), + decimals: 0, + initial_balances: vec![ + Cw20Coin { + address: Addr::unchecked(ADDR1).to_string(), + amount: Uint128::from(INITIAL_BALANCE), + }, + Cw20Coin { + address: Addr::unchecked(ADDR2).to_string(), + amount: Uint128::from(INITIAL_BALANCE), + }, + Cw20Coin { + address: Addr::unchecked(ADDR3).to_string(), + amount: Uint128::from(INITIAL_BALANCE), + }, + Cw20Coin { + address: Addr::unchecked(ADDR4).to_string(), + amount: Uint128::from(INITIAL_BALANCE), + }, + ], + mint: None, + marketing: None, + }; + let token_contract = app + .instantiate_contract(cw20_id, Addr::unchecked(OWNER), &msg, &[], "cw20", None) + .unwrap(); + + let stake_cw20_id = app.store_code(contract_stake_cw20()); + let msg = stake_cw20::msg::InstantiateMsg { + admin: None, + token_address: token_contract.clone(), + unstaking_duration: None, + }; + + let stake_contract = app + .instantiate_contract( + stake_cw20_id, + Addr::unchecked(OWNER), + &msg, + &[], + "cw20", + None, + ) + .unwrap(); + + app.execute_contract( + Addr::unchecked(ADDR1), + token_contract.clone(), + &cw20::Cw20ExecuteMsg::Send { + contract: stake_contract.to_string(), + amount: Uint128::from(INITIAL_BALANCE), + msg: to_binary(&stake_cw20::msg::ReceiveMsg::Stake {}).unwrap(), + }, + &[], + ) + .unwrap(); + app.execute_contract( + Addr::unchecked(ADDR2), + token_contract.clone(), + &cw20::Cw20ExecuteMsg::Send { + contract: stake_contract.to_string(), + amount: Uint128::from(INITIAL_BALANCE), + msg: to_binary(&stake_cw20::msg::ReceiveMsg::Stake {}).unwrap(), + }, + &[], + ) + .unwrap(); + app.execute_contract( + Addr::unchecked(ADDR3), + token_contract.clone(), + &cw20::Cw20ExecuteMsg::Send { + contract: stake_contract.to_string(), + amount: Uint128::from(INITIAL_BALANCE), + msg: to_binary(&stake_cw20::msg::ReceiveMsg::Stake {}).unwrap(), + }, + &[], + ) + .unwrap(); + app.execute_contract( + Addr::unchecked(ADDR4), + token_contract, + &cw20::Cw20ExecuteMsg::Send { + contract: stake_contract.to_string(), + amount: Uint128::from(INITIAL_BALANCE), + msg: to_binary(&stake_cw20::msg::ReceiveMsg::Stake {}).unwrap(), + }, + &[], + ) + .unwrap(); + + stake_contract + } + + fn instantiate_rewards( + app: &mut App, + msg: InstantiateMsg, + funds: &[Coin], + ) -> anyhow::Result { + let contract_id = app.store_code(contract_rewards()); + app.instantiate_contract( + contract_id, + Addr::unchecked(OWNER), + &msg, + funds, + "rewards", + None, + ) + } + + #[test] + fn proper_initialization() { + let mut app = mock_app(); + app.borrow_mut().update_block(|b| b.height = 0); + let stakeable_token = instantiate_cw20(&mut app); + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native("utest".to_string()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + let _reward = instantiate_rewards(&mut app, instantiate_msg, &[]).unwrap(); + } + + #[test] + fn basic_native_distribution() { + let mut app = mock_app(); + app.borrow_mut().update_block(|block| block.height = 0); + let denom = "utest".to_string(); + let owner = Addr::unchecked(OWNER); + + let init_funds = vec![Coin { + denom: denom.clone(), + amount: Uint128::new(16000), + }]; + app.borrow_mut().init_modules(|router, _, storage| { + router + .bank + .init_balance(storage, &owner, init_funds.clone()) + .unwrap() + }); + + println!( + "native balance: {}", + app.wrap() + .query_balance(owner, denom.clone()) + .unwrap() + .amount + ); + let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native(denom.clone()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + app.borrow_mut().update_block(next_block); + + let reward = + instantiate_rewards(&mut app.borrow_mut(), instantiate_msg, &init_funds).unwrap(); + + let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app + .wrap() + .query_wasm_smart( + stakeable_token, + &stake_cw20::msg::QueryMsg::StakedBalanceAtHeight { + address: ADDR1.to_string(), + height: None, + }, + ) + .unwrap(); + assert_eq!(res.balance, Uint128::new(1000)); + + // No claim before start block + app.borrow_mut().update_block(|block| block.height = 500); + let err: ContractError = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!( + err, + RewardsNotStarted { + current_block: 500, + start_block: 1000 + } + ); + + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR1), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::zero()); + + // Fist claim + app.borrow_mut().update_block(|block| block.height = 1001); + // Test query works + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR1), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(1000)); + + // Can't claim twice + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(0)); + app.borrow_mut().update_block(|block| block.height = 1020); + let err = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap_err(); + assert_eq!(ContractError::ZeroClaimable {}, err.downcast().unwrap()); + + // Second claim + app.borrow_mut().update_block(|block| block.height = 2011); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR1), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(2000)); + + // Addr2 claims two epochs at once + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR2), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::zero()); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR2), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(2000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR2), reward.clone(), &Claim {}, &[]) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR2), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(2000)); + + // Third claim + app.borrow_mut().update_block(|block| block.height = 3001); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR1), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(3000)); + + // 4th claim + app.borrow_mut().update_block(|block| block.height = 4001); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR1), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(4000)); + + // Rewards finished + app.borrow_mut().update_block(|block| block.height = 5001); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(0)); + let err = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap_err(); + assert_eq!(ContractError::ZeroClaimable {}, err.downcast().unwrap()); + + // Other addresses claim rewards + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR2), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(2000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR2), reward.clone(), &Claim {}, &[]) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR2), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(4000)); + + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR3), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(4000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR3), reward.clone(), &Claim {}, &[]) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR3), denom) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(4000)); + + let err = app + .execute_contract(Addr::unchecked(ADDR3), reward, &Claim {}, &[]) + .unwrap_err(); + assert_eq!(ContractError::ZeroClaimable {}, err.downcast().unwrap()); + } + + #[test] + fn basic_cw20_distribution() { + let mut app = mock_app(); + app.borrow_mut().update_block(|block| block.height = 0); + let denom = "utest".to_string(); + let owner = Addr::unchecked(OWNER); + + let init_funds = vec![Coin { + denom: denom.clone(), + amount: Uint128::new(16000), + }]; + app.borrow_mut().init_modules(|router, _, storage| { + router + .bank + .init_balance(storage, &owner, init_funds.clone()) + .unwrap() + }); + + println!( + "native balance: {}", + app.wrap().query_balance(owner, denom).unwrap().amount + ); + let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + + // Instantiate reward token + let cw20_id = app.store_code(contract_cw20()); + let msg = cw20_base::msg::InstantiateMsg { + name: "test".to_string(), + symbol: "STAKE".to_string(), + decimals: 0, + initial_balances: vec![Cw20Coin { + address: Addr::unchecked(OWNER).to_string(), + amount: Uint128::new(16000), + }], + mint: None, + marketing: None, + }; + let reward_contract_addr = app + .instantiate_contract( + cw20_id, + Addr::unchecked(OWNER), + &msg, + &[], + "cw20_reward", + None, + ) + .unwrap(); + let reward_contract = Cw20Contract(reward_contract_addr); + app.borrow_mut().update_block(next_block); + + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Cw20(reward_contract.addr()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + app.borrow_mut().update_block(next_block); + + let reward = + instantiate_rewards(&mut app.borrow_mut(), instantiate_msg, &init_funds).unwrap(); + + let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app + .wrap() + .query_wasm_smart( + stakeable_token, + &stake_cw20::msg::QueryMsg::StakedBalanceAtHeight { + address: ADDR1.to_string(), + height: None, + }, + ) + .unwrap(); + assert_eq!(res.balance, Uint128::new(1000)); + + // Fund Contract + let cw20_send = Cw20ExecuteMsg::Send { + contract: reward.to_string(), + amount: Uint128::new(16000), + msg: to_binary(&ReceiveMsg::Fund {}).unwrap(), + }; + let _res = app + .execute_contract( + Addr::unchecked(OWNER), + reward_contract.addr(), + &cw20_send, + &[], + ) + .unwrap(); + + // No claim before start block + app.borrow_mut().update_block(|block| block.height = 500); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(0)); + let err: ContractError = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!( + err, + RewardsNotStarted { + current_block: 500, + start_block: 1000 + } + ); + + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR1)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::zero()); + + // Fist claim + app.borrow_mut().update_block(|block| block.height = 1001); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR1)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::new(1000)); + + // Can't claim twice + app.borrow_mut().update_block(|block| block.height = 1020); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(0)); + let err = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap_err(); + assert_eq!(ContractError::ZeroClaimable {}, err.downcast().unwrap()); + + // Second claim + app.borrow_mut().update_block(|block| block.height = 2011); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR1)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::new(2000)); + + // Addr2 claims two epochs at once + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR2), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(2000)); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR2)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::zero()); + let _res = app + .execute_contract(Addr::unchecked(ADDR2), reward.clone(), &Claim {}, &[]) + .unwrap(); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR2)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::new(2000)); + + // Third claim + app.borrow_mut().update_block(|block| block.height = 3001); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR1)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::new(3000)); + + // 4th claim + app.borrow_mut().update_block(|block| block.height = 4001); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(1000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap(); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR1)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::new(4000)); + + // Rewards finished + app.borrow_mut().update_block(|block| block.height = 5001); + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(0)); + let err = app + .execute_contract(Addr::unchecked(ADDR1), reward.clone(), &Claim {}, &[]) + .unwrap_err(); + assert_eq!(ContractError::ZeroClaimable {}, err.downcast().unwrap()); + + // Other addresses claim rewards + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR2), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(2000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR2), reward.clone(), &Claim {}, &[]) + .unwrap(); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR2)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::new(4000)); + + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR3), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(4000)); + let _res = app + .execute_contract(Addr::unchecked(ADDR3), reward.clone(), &Claim {}, &[]) + .unwrap(); + let cw20_balance = reward_contract + .balance(&app, Addr::unchecked(ADDR3)) + .unwrap(); + assert_eq!(cw20_balance, Uint128::new(4000)); + + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR3), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(0)); + let err = app + .execute_contract(Addr::unchecked(ADDR3), reward, &Claim {}, &[]) + .unwrap_err(); + assert_eq!(ContractError::ZeroClaimable {}, err.downcast().unwrap()); + } + + #[test] + fn info_query() { + let mut app = mock_app(); + app.borrow_mut().update_block(|block| block.height = 0); + let denom = "utest".to_string(); + let owner = Addr::unchecked(OWNER); + + let init_funds = vec![Coin { + denom: denom.clone(), + amount: Uint128::new(16000), + }]; + app.borrow_mut().init_modules(|router, _, storage| { + router + .bank + .init_balance(storage, &owner, init_funds.clone()) + .unwrap() + }); + + println!( + "native balance: {}", + app.wrap() + .query_balance(owner, denom.clone()) + .unwrap() + .amount + ); + let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native(denom), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + app.borrow_mut().update_block(next_block); + + let reward = + instantiate_rewards(&mut app.borrow_mut(), instantiate_msg.clone(), &init_funds) + .unwrap(); + + let expected_response = InfoResponse { + start_block: instantiate_msg.start_block, + end_block: instantiate_msg.end_block, + payment_per_block: instantiate_msg.payment_per_block, + total_amount: instantiate_msg.total_amount, + denom: instantiate_msg.denom, + staking_contract: instantiate_msg.distribution_token, + payment_block_delta: 1000, + }; + + let res: InfoResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart(reward, &Info {}) + .unwrap(); + assert_eq!(res, expected_response) + } + + #[test] + fn claim_up_to() { + let mut app = mock_app(); + app.borrow_mut().update_block(|block| block.height = 0); + let denom = "utest".to_string(); + let owner = Addr::unchecked(OWNER); + + let init_funds = vec![Coin { + denom: denom.clone(), + amount: Uint128::new(16000), + }]; + app.borrow_mut().init_modules(|router, _, storage| { + router + .bank + .init_balance(storage, &owner, init_funds.clone()) + .unwrap() + }); + + println!( + "native balance: {}", + app.wrap() + .query_balance(owner, denom.clone()) + .unwrap() + .amount + ); + let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native(denom.clone()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + app.borrow_mut().update_block(next_block); + + let reward = + instantiate_rewards(&mut app.borrow_mut(), instantiate_msg, &init_funds).unwrap(); + + let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app + .wrap() + .query_wasm_smart( + stakeable_token, + &stake_cw20::msg::QueryMsg::StakedBalanceAtHeight { + address: ADDR1.to_string(), + height: None, + }, + ) + .unwrap(); + assert_eq!(res.balance, Uint128::new(1000)); + + // Cannont claim up to blocks in the future + let err: ContractError = app + .execute_contract( + Addr::unchecked(ADDR1), + reward.clone(), + &ClaimUpToBlock { block: 3001 }, + &[], + ) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!(err, ContractError::InvalidFutureBlock {}); + + // Claim Two blocks + app.borrow_mut().update_block(|block| block.height = 3001); + // Test query works + let res: ClaimableRewardsResponse = app + .borrow_mut() + .wrap() + .query_wasm_smart( + reward.clone(), + &ClaimableRewards { + address: Addr::unchecked(ADDR1), + }, + ) + .unwrap(); + assert_eq!(res.amount, Uint128::new(3000)); + let _res = app + .execute_contract( + Addr::unchecked(ADDR1), + reward.clone(), + &ClaimUpToBlock { block: 2001 }, + &[], + ) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR1), denom.clone()) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(2000)); + + let _res = app + .execute_contract( + Addr::unchecked(ADDR1), + reward, + &ClaimUpToBlock { block: 3001 }, + &[], + ) + .unwrap(); + let native_balance = app + .wrap() + .query_balance(Addr::unchecked(ADDR1), denom) + .unwrap() + .amount; + assert_eq!(native_balance, Uint128::new(3000)); + } + + #[test] + fn validate_instantiate_msg() { + let mut app = mock_app(); + app.borrow_mut().update_block(|b| b.height = 5000); + let stakeable_token = instantiate_cw20(&mut app); + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native("utest".to_string()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + let err: ContractError = instantiate_rewards(&mut app, instantiate_msg, &[]) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!(err, ContractError::StartBlockAlreadyOccurred {}); + + app.borrow_mut().update_block(|b| b.height = 0); + let stakeable_token = instantiate_cw20(&mut app); + let instantiate_msg = InstantiateMsg { + start_block: 5000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native("utest".to_string()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + let err: ContractError = instantiate_rewards(&mut app, instantiate_msg, &[]) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!(err, ContractError::StartBlockAfterEndBlock {}); + + app.borrow_mut().update_block(|b| b.height = 0); + let stakeable_token = instantiate_cw20(&mut app); + let instantiate_msg = InstantiateMsg { + start_block: 1050, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native("utest".to_string()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + let err: ContractError = instantiate_rewards(&mut app, instantiate_msg, &[]) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!(err, ContractError::StartBlockNotDivisibleByPaymentDelta {}); + + app.borrow_mut().update_block(|b| b.height = 0); + let stakeable_token = instantiate_cw20(&mut app); + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 3999, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16000), + denom: Denom::Native("utest".to_string()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + let err: ContractError = instantiate_rewards(&mut app, instantiate_msg, &[]) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!(err, ContractError::EndBlockNotDivisibleByPaymentDelta {}); + + app.borrow_mut().update_block(|b| b.height = 0); + let stakeable_token = instantiate_cw20(&mut app); + let instantiate_msg = InstantiateMsg { + start_block: 1000, + end_block: 4000, + payment_per_block: Uint128::new(4), + total_amount: Uint128::new(16001), + denom: Denom::Native("utest".to_string()), + distribution_token: stakeable_token.to_string(), + payment_block_delta: 1000, + }; + let err: ContractError = instantiate_rewards(&mut app, instantiate_msg, &[]) + .unwrap_err() + .downcast() + .unwrap(); + assert_eq!(err, ContractError::InvalidTotalAmount {}); + } +} diff --git a/contracts/stake-cw20-external-rewards/src/error.rs b/contracts/stake-cw20-external-rewards/src/error.rs new file mode 100644 index 000000000..3004aaf7a --- /dev/null +++ b/contracts/stake-cw20-external-rewards/src/error.rs @@ -0,0 +1,44 @@ +use cosmwasm_std::{StdError, Uint128}; +use thiserror::Error; + +#[derive(Error, Debug, PartialEq)] +pub enum ContractError { + #[error("{0}")] + Std(#[from] StdError), + #[error("DivideByZero")] + DivideByZero {}, + #[error("Unauthorized")] + Unauthorized {}, + #[error("NotFunded")] + NotFunded {}, + #[error("AlreadyFunded")] + AlreadyFunded {}, + #[error("IncorrectDenom")] + IncorrectDenom {}, + #[error("IncorrectFundingAmount")] + IncorrectFundingAmount { + received: Uint128, + expected: Uint128, + }, + #[error("RewardsNotStarted")] + RewardsNotStarted { + current_block: u64, + start_block: u64, + }, + #[error("ZeroClaimable")] + ZeroClaimable {}, + // Add any other custom errors you like here. + // Look at https://docs.rs/thiserror/1.0.21/thiserror/ for details. + #[error("BlockInFuture")] + InvalidFutureBlock {}, + #[error("Start block already occurred")] + StartBlockAlreadyOccurred {}, + #[error("Start block later then end block")] + StartBlockAfterEndBlock {}, + #[error("Start block is not divisible by payment delta")] + StartBlockNotDivisibleByPaymentDelta {}, + #[error("End block is not divisible by payment delta")] + EndBlockNotDivisibleByPaymentDelta {}, + #[error("Total amount is not equal to total payments")] + InvalidTotalAmount {}, +} diff --git a/contracts/stake-cw20-external-rewards/src/lib.rs b/contracts/stake-cw20-external-rewards/src/lib.rs new file mode 100644 index 000000000..dfedc9dc6 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/src/lib.rs @@ -0,0 +1,6 @@ +pub mod contract; +mod error; +pub mod msg; +pub mod state; + +pub use crate::error::ContractError; diff --git a/contracts/stake-cw20-external-rewards/src/msg.rs b/contracts/stake-cw20-external-rewards/src/msg.rs new file mode 100644 index 000000000..1540c3c49 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/src/msg.rs @@ -0,0 +1,57 @@ +use cosmwasm_std::{Addr, Uint128}; +use cw20::Cw20ReceiveMsg; +use cw20::Denom; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct InstantiateMsg { + pub start_block: u64, + pub end_block: u64, + pub payment_per_block: Uint128, + pub total_amount: Uint128, + pub denom: Denom, + pub distribution_token: String, + pub payment_block_delta: u64, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ExecuteMsg { + Claim {}, + Receive(Cw20ReceiveMsg), + ClaimUpToBlock { block: u64 }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ReceiveMsg { + /// Adds all sent native tokens to the contract + Fund {}, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum QueryMsg { + // GetCount returns the current count as a json-encoded number + Info {}, + ClaimableRewards { address: Addr }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct InfoResponse { + pub start_block: u64, + pub end_block: u64, + pub payment_per_block: Uint128, + pub total_amount: Uint128, + pub denom: Denom, + pub staking_contract: String, + pub payment_block_delta: u64, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct ClaimableRewardsResponse { + pub amount: Uint128, +} diff --git a/contracts/stake-cw20-external-rewards/src/state.rs b/contracts/stake-cw20-external-rewards/src/state.rs new file mode 100644 index 000000000..28b4dab59 --- /dev/null +++ b/contracts/stake-cw20-external-rewards/src/state.rs @@ -0,0 +1,27 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use cosmwasm_std::{Addr, Uint128}; +use cw20::Denom; +use cw_storage_plus::{Item, Map}; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct Config { + pub start_block: u64, + pub end_block: u64, + pub payment_per_block: Uint128, + pub total_amount: Uint128, + pub denom: Denom, + pub staking_contract: Addr, + pub funded: bool, + pub payment_block_delta: u64, +} + +pub const CONFIG: Item = Item::new("config"); + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct LastClaim { + pub block_height: u64, + pub time: cosmwasm_std::Timestamp, +} +pub const LAST_CLAIMED: Map = Map::new("last_claimed"); From f2785e6323dd0de54ffa3bbc8abb061fbd6c25bf Mon Sep 17 00:00:00 2001 From: ben Date: Tue, 8 Feb 2022 16:40:28 -0800 Subject: [PATCH 2/8] fix clippy issues --- .../stake-cw20-external-rewards/src/contract.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/contracts/stake-cw20-external-rewards/src/contract.rs b/contracts/stake-cw20-external-rewards/src/contract.rs index ce47d60d8..0b3ec34c4 100644 --- a/contracts/stake-cw20-external-rewards/src/contract.rs +++ b/contracts/stake-cw20-external-rewards/src/contract.rs @@ -492,7 +492,7 @@ mod tests { .unwrap() .amount ); - let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + let stakeable_token = instantiate_cw20(&mut app); let instantiate_msg = InstantiateMsg { start_block: 1000, end_block: 4000, @@ -505,7 +505,7 @@ mod tests { app.borrow_mut().update_block(next_block); let reward = - instantiate_rewards(&mut app.borrow_mut(), instantiate_msg, &init_funds).unwrap(); + instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app .wrap() @@ -769,7 +769,7 @@ mod tests { "native balance: {}", app.wrap().query_balance(owner, denom).unwrap().amount ); - let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + let stakeable_token = instantiate_cw20(&mut app); // Instantiate reward token let cw20_id = app.store_code(contract_cw20()); @@ -809,7 +809,7 @@ mod tests { app.borrow_mut().update_block(next_block); let reward = - instantiate_rewards(&mut app.borrow_mut(), instantiate_msg, &init_funds).unwrap(); + instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app .wrap() @@ -1094,7 +1094,7 @@ mod tests { .unwrap() .amount ); - let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + let stakeable_token = instantiate_cw20(&mut app); let instantiate_msg = InstantiateMsg { start_block: 1000, end_block: 4000, @@ -1107,7 +1107,7 @@ mod tests { app.borrow_mut().update_block(next_block); let reward = - instantiate_rewards(&mut app.borrow_mut(), instantiate_msg.clone(), &init_funds) + instantiate_rewards(&mut app, instantiate_msg.clone(), &init_funds) .unwrap(); let expected_response = InfoResponse { @@ -1153,7 +1153,7 @@ mod tests { .unwrap() .amount ); - let stakeable_token = instantiate_cw20(&mut app.borrow_mut()); + let stakeable_token = instantiate_cw20(&mut app); let instantiate_msg = InstantiateMsg { start_block: 1000, end_block: 4000, @@ -1166,7 +1166,7 @@ mod tests { app.borrow_mut().update_block(next_block); let reward = - instantiate_rewards(&mut app.borrow_mut(), instantiate_msg, &init_funds).unwrap(); + instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app .wrap() From 81545b3e256e2f9d6227a29a9ddb6b9b157b6cac Mon Sep 17 00:00:00 2001 From: ben Date: Tue, 8 Feb 2022 17:05:06 -0800 Subject: [PATCH 3/8] cargo fmt --- .../stake-cw20-external-rewards/src/contract.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/contracts/stake-cw20-external-rewards/src/contract.rs b/contracts/stake-cw20-external-rewards/src/contract.rs index 0b3ec34c4..7caa635d5 100644 --- a/contracts/stake-cw20-external-rewards/src/contract.rs +++ b/contracts/stake-cw20-external-rewards/src/contract.rs @@ -504,8 +504,7 @@ mod tests { }; app.borrow_mut().update_block(next_block); - let reward = - instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); + let reward = instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app .wrap() @@ -808,8 +807,7 @@ mod tests { }; app.borrow_mut().update_block(next_block); - let reward = - instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); + let reward = instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app .wrap() @@ -1106,9 +1104,7 @@ mod tests { }; app.borrow_mut().update_block(next_block); - let reward = - instantiate_rewards(&mut app, instantiate_msg.clone(), &init_funds) - .unwrap(); + let reward = instantiate_rewards(&mut app, instantiate_msg.clone(), &init_funds).unwrap(); let expected_response = InfoResponse { start_block: instantiate_msg.start_block, @@ -1165,8 +1161,7 @@ mod tests { }; app.borrow_mut().update_block(next_block); - let reward = - instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); + let reward = instantiate_rewards(&mut app, instantiate_msg, &init_funds).unwrap(); let res: stake_cw20::msg::StakedBalanceAtHeightResponse = app .wrap() From 7f3f5faf93d3db3cb3826c4897fd1046615d0041 Mon Sep 17 00:00:00 2001 From: ben2x4 <86395884+ben2x4@users.noreply.github.com> Date: Wed, 9 Feb 2022 18:42:32 -0800 Subject: [PATCH 4/8] remove unnecssary profile.release in cargo.toml Co-authored-by: zeke <30676292+ezekiiel@users.noreply.github.com> --- contracts/stake-cw20-external-rewards/Cargo.toml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/contracts/stake-cw20-external-rewards/Cargo.toml b/contracts/stake-cw20-external-rewards/Cargo.toml index b4f6e1ed2..98e06498b 100644 --- a/contracts/stake-cw20-external-rewards/Cargo.toml +++ b/contracts/stake-cw20-external-rewards/Cargo.toml @@ -15,16 +15,6 @@ exclude = [ [lib] crate-type = ["cdylib", "rlib"] -[profile.release] -opt-level = 3 -debug = false -rpath = false -lto = true -debug-assertions = false -codegen-units = 1 -panic = 'abort' -incremental = false -overflow-checks = true [features] # for more explicit tests, cargo test --features=backtraces From 4d69b91ee36a7ed562770cd6517f8e337b2a3a6d Mon Sep 17 00:00:00 2001 From: ben2x4 <86395884+ben2x4@users.noreply.github.com> Date: Wed, 9 Feb 2022 18:52:25 -0800 Subject: [PATCH 5/8] _env -> env Co-authored-by: zeke <30676292+ezekiiel@users.noreply.github.com> --- contracts/stake-cw20-external-rewards/src/contract.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contracts/stake-cw20-external-rewards/src/contract.rs b/contracts/stake-cw20-external-rewards/src/contract.rs index 7caa635d5..327ca1f7d 100644 --- a/contracts/stake-cw20-external-rewards/src/contract.rs +++ b/contracts/stake-cw20-external-rewards/src/contract.rs @@ -67,14 +67,14 @@ pub fn validate_instantiate_msg(env: &Env, msg: &InstantiateMsg) -> Result<(), C #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, - _env: Env, + env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result { match msg { - ExecuteMsg::Claim {} => try_claim(deps, _env.clone(), info, _env.block.height), - ExecuteMsg::Receive(msg) => try_receive(deps, _env, info, msg), - ExecuteMsg::ClaimUpToBlock { block } => try_claim(deps, _env, info, block), + ExecuteMsg::Claim {} => try_claim(deps, env.clone(), info, env.block.height), + ExecuteMsg::Receive(msg) => try_receive(deps, env, info, msg), + ExecuteMsg::ClaimUpToBlock { block } => try_claim(deps, env, info, block), } } From 9f044c133dd5c38736502ffbcf08c353a33641e2 Mon Sep 17 00:00:00 2001 From: ben Date: Wed, 9 Feb 2022 19:13:17 -0800 Subject: [PATCH 6/8] respond to comments --- .../src/contract.rs | 26 +++++++++---------- .../stake-cw20-external-rewards/src/error.rs | 6 ++--- .../stake-cw20-external-rewards/src/msg.rs | 3 ++- .../stake-cw20-external-rewards/src/state.rs | 2 +- 4 files changed, 17 insertions(+), 20 deletions(-) diff --git a/contracts/stake-cw20-external-rewards/src/contract.rs b/contracts/stake-cw20-external-rewards/src/contract.rs index 7caa635d5..ac7a64b55 100644 --- a/contracts/stake-cw20-external-rewards/src/contract.rs +++ b/contracts/stake-cw20-external-rewards/src/contract.rs @@ -33,7 +33,7 @@ pub fn instantiate( Denom::Native(_) => true, Denom::Cw20(_) => false, }, - payment_block_delta: msg.payment_block_delta, + blocks_between_payments: msg.payment_block_delta, }; CONFIG.save(deps.storage, &config)?; Ok(Response::default()) @@ -46,19 +46,15 @@ pub fn validate_instantiate_msg(env: &Env, msg: &InstantiateMsg) -> Result<(), C if msg.start_block > msg.end_block { return Err(ContractError::StartBlockAfterEndBlock {}); } - if msg.start_block % msg.payment_block_delta != 0 { - return Err(ContractError::StartBlockNotDivisibleByPaymentDelta {}); + if (msg.end_block - msg.start_block) % msg.payment_block_delta != 0 { + return Err(ContractError::StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {}); } - if msg.end_block % msg.payment_block_delta != 0 { - return Err(ContractError::EndBlockNotDivisibleByPaymentDelta {}); - } - let duration = Uint128::from(((msg.end_block - msg.start_block) / msg.payment_block_delta) + 1); + let duration = Uint128::from((msg.end_block - msg.start_block) + msg.payment_block_delta); let calculated_total = duration .checked_mul(msg.payment_per_block) - .map_err(cosmwasm_std::StdError::overflow)? - .checked_mul(Uint128::from(msg.payment_block_delta)) .map_err(cosmwasm_std::StdError::overflow)?; if calculated_total != msg.total_amount { + println!("{}, {}", calculated_total, msg.total_amount); return Err(ContractError::InvalidTotalAmount {}); } Ok(()) @@ -174,7 +170,7 @@ fn get_amount_owed( last_claimed: u64, up_to_block: u64, ) -> StdResult<(Uint128, u64)> { - let delta = config.payment_block_delta; + let delta = config.blocks_between_payments; let mut current_block = last_claimed; let mut amount = Uint128::zero(); while current_block <= min(up_to_block, config.end_block) { @@ -261,7 +257,8 @@ pub fn query_info(deps: Deps) -> StdResult { total_amount: config.total_amount, denom: config.denom, staking_contract: config.staking_contract.to_string(), - payment_block_delta: config.payment_block_delta, + blocks_between_payments: config.blocks_between_payments, + funded: config.funded }) } @@ -1113,7 +1110,8 @@ mod tests { total_amount: instantiate_msg.total_amount, denom: instantiate_msg.denom, staking_contract: instantiate_msg.distribution_token, - payment_block_delta: 1000, + blocks_between_payments: 1000, + funded: true, }; let res: InfoResponse = app @@ -1285,7 +1283,7 @@ mod tests { .unwrap_err() .downcast() .unwrap(); - assert_eq!(err, ContractError::StartBlockNotDivisibleByPaymentDelta {}); + assert_eq!(err, ContractError::StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {}); app.borrow_mut().update_block(|b| b.height = 0); let stakeable_token = instantiate_cw20(&mut app); @@ -1302,7 +1300,7 @@ mod tests { .unwrap_err() .downcast() .unwrap(); - assert_eq!(err, ContractError::EndBlockNotDivisibleByPaymentDelta {}); + assert_eq!(err, ContractError::StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {}); app.borrow_mut().update_block(|b| b.height = 0); let stakeable_token = instantiate_cw20(&mut app); diff --git a/contracts/stake-cw20-external-rewards/src/error.rs b/contracts/stake-cw20-external-rewards/src/error.rs index 3004aaf7a..eae341b60 100644 --- a/contracts/stake-cw20-external-rewards/src/error.rs +++ b/contracts/stake-cw20-external-rewards/src/error.rs @@ -35,10 +35,8 @@ pub enum ContractError { StartBlockAlreadyOccurred {}, #[error("Start block later then end block")] StartBlockAfterEndBlock {}, - #[error("Start block is not divisible by payment delta")] - StartBlockNotDivisibleByPaymentDelta {}, - #[error("End block is not divisible by payment delta")] - EndBlockNotDivisibleByPaymentDelta {}, + #[error("Start block is not divisible by blocks between payments")] + StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {}, #[error("Total amount is not equal to total payments")] InvalidTotalAmount {}, } diff --git a/contracts/stake-cw20-external-rewards/src/msg.rs b/contracts/stake-cw20-external-rewards/src/msg.rs index 1540c3c49..71e8b9adb 100644 --- a/contracts/stake-cw20-external-rewards/src/msg.rs +++ b/contracts/stake-cw20-external-rewards/src/msg.rs @@ -47,7 +47,8 @@ pub struct InfoResponse { pub total_amount: Uint128, pub denom: Denom, pub staking_contract: String, - pub payment_block_delta: u64, + pub blocks_between_payments: u64, + pub funded: bool, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] diff --git a/contracts/stake-cw20-external-rewards/src/state.rs b/contracts/stake-cw20-external-rewards/src/state.rs index 28b4dab59..9f475c7f3 100644 --- a/contracts/stake-cw20-external-rewards/src/state.rs +++ b/contracts/stake-cw20-external-rewards/src/state.rs @@ -14,7 +14,7 @@ pub struct Config { pub denom: Denom, pub staking_contract: Addr, pub funded: bool, - pub payment_block_delta: u64, + pub blocks_between_payments: u64, } pub const CONFIG: Item = Item::new("config"); From e2dfbdf9215d198469f9aad31fd4c6effe90fcac Mon Sep 17 00:00:00 2001 From: ben Date: Wed, 9 Feb 2022 19:13:40 -0800 Subject: [PATCH 7/8] cargo fmt --- .../stake-cw20-external-rewards/src/contract.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/contracts/stake-cw20-external-rewards/src/contract.rs b/contracts/stake-cw20-external-rewards/src/contract.rs index ac7a64b55..78557e21e 100644 --- a/contracts/stake-cw20-external-rewards/src/contract.rs +++ b/contracts/stake-cw20-external-rewards/src/contract.rs @@ -258,7 +258,7 @@ pub fn query_info(deps: Deps) -> StdResult { denom: config.denom, staking_contract: config.staking_contract.to_string(), blocks_between_payments: config.blocks_between_payments, - funded: config.funded + funded: config.funded, }) } @@ -1283,7 +1283,10 @@ mod tests { .unwrap_err() .downcast() .unwrap(); - assert_eq!(err, ContractError::StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {}); + assert_eq!( + err, + ContractError::StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {} + ); app.borrow_mut().update_block(|b| b.height = 0); let stakeable_token = instantiate_cw20(&mut app); @@ -1300,7 +1303,10 @@ mod tests { .unwrap_err() .downcast() .unwrap(); - assert_eq!(err, ContractError::StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {}); + assert_eq!( + err, + ContractError::StartAndEndBlocksNotDivisibleByBlocksBetweenPayments {} + ); app.borrow_mut().update_block(|b| b.height = 0); let stakeable_token = instantiate_cw20(&mut app); From 260d7d0e491493021f361027eb06361481efff86 Mon Sep 17 00:00:00 2001 From: ben Date: Wed, 9 Feb 2022 19:14:12 -0800 Subject: [PATCH 8/8] cargo schema --- .../stake-cw20-external-rewards/schema/config.json | 12 ++++++------ .../schema/info_response.json | 14 +++++++++----- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/contracts/stake-cw20-external-rewards/schema/config.json b/contracts/stake-cw20-external-rewards/schema/config.json index 3b10be52a..82542eb57 100644 --- a/contracts/stake-cw20-external-rewards/schema/config.json +++ b/contracts/stake-cw20-external-rewards/schema/config.json @@ -3,16 +3,21 @@ "title": "Config", "type": "object", "required": [ + "blocks_between_payments", "denom", "end_block", "funded", - "payment_block_delta", "payment_per_block", "staking_contract", "start_block", "total_amount" ], "properties": { + "blocks_between_payments": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, "denom": { "$ref": "#/definitions/Denom" }, @@ -24,11 +29,6 @@ "funded": { "type": "boolean" }, - "payment_block_delta": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, "payment_per_block": { "$ref": "#/definitions/Uint128" }, diff --git a/contracts/stake-cw20-external-rewards/schema/info_response.json b/contracts/stake-cw20-external-rewards/schema/info_response.json index be5076aed..a6e02a29c 100644 --- a/contracts/stake-cw20-external-rewards/schema/info_response.json +++ b/contracts/stake-cw20-external-rewards/schema/info_response.json @@ -3,15 +3,21 @@ "title": "InfoResponse", "type": "object", "required": [ + "blocks_between_payments", "denom", "end_block", - "payment_block_delta", + "funded", "payment_per_block", "staking_contract", "start_block", "total_amount" ], "properties": { + "blocks_between_payments": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, "denom": { "$ref": "#/definitions/Denom" }, @@ -20,10 +26,8 @@ "format": "uint64", "minimum": 0.0 }, - "payment_block_delta": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 + "funded": { + "type": "boolean" }, "payment_per_block": { "$ref": "#/definitions/Uint128"