From e2b8f1cb8e54f27f2250b57ced6a87240db3e126 Mon Sep 17 00:00:00 2001 From: Art3miX <40179351+Art3miX@users.noreply.github.com> Date: Thu, 5 Dec 2024 22:18:03 +0200 Subject: [PATCH] Rebalancer fixes 0.1.7 (#107) --- .cargo/{config => config.toml} | 0 Cargo.lock | 237 +++++++++++------- Cargo.toml | 2 +- README.md | 28 ++- contracts/account/schema/valence-account.json | 2 +- contracts/auction/auction/schema/auction.json | 2 +- .../schema/auctions-manager.json | 21 +- .../price_oracle/schema/price-oracle.json | 65 ++++- .../auction/price_oracle/src/contract.rs | 76 ++++-- contracts/auction/price_oracle/src/msg.rs | 2 + contracts/auction/price_oracle/src/state.rs | 6 +- .../rebalancer/schema/rebalancer.json | 100 +++++++- .../services/rebalancer/src/rebalance.rs | 48 ++-- .../schema/services-manager.json | 21 +- packages/auction-package/src/helpers.rs | 9 + packages/auction-package/src/lib.rs | 14 +- packages/cw-pid/Cargo.toml | 13 + packages/cw-pid/src/lib.rs | 1 + packages/cw-pid/src/pid.rs | 63 +++++ .../src/services/rebalancer.rs | 54 +++- scripts/add_service_to_manager.sh | 7 + scripts/init.sh | 36 ++- scripts/migrate.sh | 12 +- scripts/new_auction.sh | 10 +- scripts/register_to_service.sh | 2 +- scripts/update_oracle_addr.sh | 11 +- scripts/update_price.sh | 9 +- scripts/upload.sh | 8 +- .../live_debugging/test_specific_config.rs | 1 + tests/rust-tests/src/suite/suite_auction.rs | 10 + tests/rust-tests/src/suite/suite_builder.rs | 1 + .../rust-tests/src/test_service_management.rs | 3 + .../src/tests_auctions/test_astro.rs | 10 +- .../src/tests_auctions/test_oracle.rs | 77 ++++++ .../src/tests_rebalancer/test_management.rs | 6 +- 35 files changed, 781 insertions(+), 186 deletions(-) rename .cargo/{config => config.toml} (100%) create mode 100644 packages/cw-pid/Cargo.toml create mode 100644 packages/cw-pid/src/lib.rs create mode 100644 packages/cw-pid/src/pid.rs diff --git a/.cargo/config b/.cargo/config.toml similarity index 100% rename from .cargo/config rename to .cargo/config.toml diff --git a/Cargo.lock b/Cargo.lock index 569b71a6..1a9856e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -30,9 +30,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.86" +version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" +checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" [[package]] name = "astroport" @@ -153,7 +153,7 @@ dependencies = [ [[package]] name = "auction" -version = "0.1.6" +version = "0.1.7" dependencies = [ "anyhow", "auction-package", @@ -170,7 +170,7 @@ dependencies = [ [[package]] name = "auction-package" -version = "0.1.6" +version = "0.1.7" dependencies = [ "cosmwasm-schema", "cosmwasm-std", @@ -182,7 +182,7 @@ dependencies = [ [[package]] name = "auctions-manager" -version = "0.1.6" +version = "0.1.7" dependencies = [ "anyhow", "auction", @@ -201,9 +201,9 @@ dependencies = [ [[package]] name = "autocfg" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "base16ct" @@ -267,9 +267,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" [[package]] name = "bytemuck" -version = "1.16.1" +version = "1.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e" +checksum = "8b37c88a63ffd85d15b406896cc343916d7cf57838a847b3a6f2ca5d39a5695a" [[package]] name = "byteorder" @@ -279,15 +279,18 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.6.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" +checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" [[package]] name = "cc" -version = "1.1.6" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f" +checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" +dependencies = [ + "shlex", +] [[package]] name = "cfg-if" @@ -327,18 +330,17 @@ checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] name = "core-foundation-sys" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cosmwasm-crypto" -version = "1.5.5" +version = "1.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd50718a2b6830ce9eb5d465de5a018a12e71729d66b70807ce97e6dd14f931d" +checksum = "58535cbcd599b3c193e3967c8292fe1dbbb5de7c2a2d87380661091dd4744044" dependencies = [ "digest 0.10.7", - "ecdsa", "ed25519-zebra", "k256", "rand_core 0.6.4", @@ -347,18 +349,18 @@ dependencies = [ [[package]] name = "cosmwasm-derive" -version = "1.5.5" +version = "1.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "242e98e7a231c122e08f300d9db3262d1007b51758a8732cd6210b3e9faa4f3a" +checksum = "a8e07de16c800ac82fd188d055ecdb923ead0cf33960d3350089260bb982c09f" dependencies = [ "syn 1.0.109", ] [[package]] name = "cosmwasm-schema" -version = "1.5.5" +version = "1.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7879036156092ad1c22fe0d7316efc5a5eceec2bc3906462a2560215f2a2f929" +checksum = "93d388adfa9cb449557a92e9318121ac1a481fc4f599213b03a5b62699b403b4" dependencies = [ "cosmwasm-schema-derive", "schemars", @@ -369,9 +371,9 @@ dependencies = [ [[package]] name = "cosmwasm-schema-derive" -version = "1.5.5" +version = "1.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb57855fbfc83327f8445ae0d413b1a05ac0d68c396ab4d122b2abd7bb82cb6" +checksum = "2411b389e56e6484f81ba955b758d02522d620c98fc960c4bd2251d48b7aa19f" dependencies = [ "proc-macro2", "quote", @@ -380,9 +382,9 @@ dependencies = [ [[package]] name = "cosmwasm-std" -version = "1.5.5" +version = "1.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c1556156fdf892a55cced6115968b961eaaadd6f724a2c2cb7d1e168e32dd3" +checksum = "c21fde95ccd20044a23c0ac6fd8c941f3e8c158169dc94b5aa6491a2d9551a8d" dependencies = [ "base64", "bech32 0.9.1", @@ -412,9 +414,9 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.2.12" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" +checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" dependencies = [ "libc", ] @@ -480,6 +482,16 @@ dependencies = [ "thiserror", ] +[[package]] +name = "cw-pid" +version = "0.1.7" +dependencies = [ + "cosmwasm-std", + "serde", + "serde-wasm-bindgen", + "wasm-bindgen", +] + [[package]] name = "cw-storage-plus" version = "0.15.1" @@ -819,9 +831,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.60" +version = "0.1.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -878,24 +890,24 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.11" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" [[package]] name = "js-sys" -version = "0.3.69" +version = "0.3.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" dependencies = [ "wasm-bindgen", ] [[package]] name = "k256" -version = "0.13.1" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cadb76004ed8e97623117f3df85b17aaa6626ab0b0831e6573f104df16cd1bcc" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" dependencies = [ "cfg-if", "ecdsa", @@ -913,9 +925,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.155" +version = "0.2.165" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +checksum = "fcb4d3d38eab6c5239a362fa8bae48c03baf980a6e7079f063942d563ef3533e" [[package]] name = "log" @@ -923,6 +935,12 @@ version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + [[package]] name = "num-traits" version = "0.2.19" @@ -934,9 +952,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.19.0" +version = "1.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" [[package]] name = "opaque-debug" @@ -956,13 +974,16 @@ dependencies = [ [[package]] name = "ppv-lite86" -version = "0.2.17" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy", +] [[package]] name = "price-oracle" -version = "0.1.6" +version = "0.1.7" dependencies = [ "anyhow", "astroport 2.9.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -980,9 +1001,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.86" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] @@ -1007,7 +1028,7 @@ dependencies = [ "itertools 0.12.1", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.89", ] [[package]] @@ -1021,9 +1042,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.36" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] @@ -1066,7 +1087,7 @@ dependencies = [ [[package]] name = "rebalancer" -version = "0.1.6" +version = "0.1.7" dependencies = [ "anyhow", "auction", @@ -1096,9 +1117,9 @@ dependencies = [ [[package]] name = "rgb" -version = "0.8.45" +version = "0.8.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ade4539f42266ded9e755c605bdddf546242b2c961b03b06a7375260788a0523" +checksum = "57397d16646700483b67d2dd6511d79318f9d057fdbd21a4066aeac8b41d310a" dependencies = [ "bytemuck", ] @@ -1130,7 +1151,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 2.0.72", + "syn 2.0.89", ] [[package]] @@ -1155,9 +1176,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.204" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" +checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" dependencies = [ "serde_derive", ] @@ -1171,15 +1192,26 @@ dependencies = [ "serde", ] +[[package]] +name = "serde-wasm-bindgen" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b4c031cd0d9014307d82b8abf653c0290fbdaeb4c02d00c63cf52f728628bf" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + [[package]] name = "serde_derive" -version = "1.0.204" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" +checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.89", ] [[package]] @@ -1190,23 +1222,24 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.89", ] [[package]] name = "serde_json" -version = "1.0.120" +version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" +checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" dependencies = [ "itoa", + "memchr", "ryu", "serde", ] [[package]] name = "services-manager" -version = "0.1.6" +version = "0.1.7" dependencies = [ "anyhow", "cosmwasm-schema", @@ -1245,6 +1278,12 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "signature" version = "2.2.0" @@ -1311,9 +1350,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.72" +version = "2.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" +checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" dependencies = [ "proc-macro2", "quote", @@ -1332,22 +1371,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.63" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.63" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.89", ] [[package]] @@ -1370,13 +1409,13 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.12" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" +checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" [[package]] name = "valence-account" -version = "0.1.6" +version = "0.1.7" dependencies = [ "anyhow", "cosmwasm-schema", @@ -1392,7 +1431,7 @@ dependencies = [ [[package]] name = "valence-macros" -version = "0.1.6" +version = "0.1.7" dependencies = [ "cosmwasm-schema", "cosmwasm-std", @@ -1403,7 +1442,7 @@ dependencies = [ [[package]] name = "valence-package" -version = "0.1.6" +version = "0.1.7" dependencies = [ "auction-package", "cosmwasm-schema", @@ -1417,7 +1456,7 @@ dependencies = [ [[package]] name = "valence-tests" -version = "0.1.6" +version = "0.1.7" dependencies = [ "anyhow", "astroport 2.9.5 (git+https://github.com/astroport-fi/astroport-core.git?tag=v2.9.5)", @@ -1450,9 +1489,9 @@ dependencies = [ [[package]] name = "version_check" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "wasi" @@ -1462,34 +1501,35 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.92" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" dependencies = [ "cfg-if", + "once_cell", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.92" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.89", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.92" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1497,22 +1537,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.92" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.89", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.92" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" +checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" [[package]] name = "windows-core" @@ -1653,6 +1693,27 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + [[package]] name = "zeroize" version = "1.8.1" diff --git a/Cargo.toml b/Cargo.toml index 0e11f515..e2d4be6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ [workspace.package] edition = "2021" license = "BSL" -version = "0.1.6" +version = "0.1.7" repository = "https://github.com/timewave-computer/valence-services" rust-version = "1.66" diff --git a/README.md b/README.md index 227f11dc..b4d4ae71 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,33 @@ The Rebalancer sends funds to be auctioned daily. If you are a market maker inte - [untrn, newt] - `neutron1zvw9l8c82hnvwsntpuy89p86ztfmmudd9usfmnpa2tnqws74zsxq56sczm` - [uusdc, newt] - `neutron1vu04szc78ae0nplwpuxjr6j592hn2d60zqtuts7w3ah6kajtxd2q2vfv59` -## Audits +## Neutron Testnet Contracts -Valence Services have been rigorously tested and audited. Find audits [here](./audits/) +[![Check Set-Up & Build](https://github.com/timewave-computer/valence-services/actions/workflows/check.yml/badge.svg)](https://github.com/timewave-computer/valence-services/actions/workflows/check.yml) + +### Code ids + +- auctions-manager - `5673` +- auction - `5679` +- services-manager - `5674` +- rebalancer - `8367` +- oracle - `8371` +- account - `5677` + +### Addresses + +- Services manager - `neutron13ncggwefau3xla04vlugy20meap7g7a9lf2d2sxwgwvgr9mnn3yqkpjzs6` +- Auctions manager - `neutron1669ftav8rv4hjuak89w04k7f0f7m9qq9564s00ld4m8dvhsr5hfsxy3x46` +- Rebalancer - `neutron1y9aurkegmqlqwhsnwctee4w4aja7n64yuat800p8yys509pyl0fsvrmydm` +- Oracle - `neutron1g4qcmk65nw57hmqlzk6cejnftg20zmctky0l2epdfz3npw3x2cmqprul6f` +- Account - `neutron1gc3tt3edg3drsc3aa22du9pa9f9s2gx6reu2hvq7s6yrdmy8zqjssfj52p` + +### Auctions addresses + +denom - `factory/neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68/rebalancer-test` + +- [untrn, test] - `neutron10p7d4ca0a5a3plx0d3dw0qmrnldfxwgq8q48205za6pgyhmqqzasg58fg4` +- [test, untrn] - `neutron1s859kh0cgte55fmgtksylw5khv8yxvhslpxmpqdy46fv8q7wxj8qtplru4` ## Security diff --git a/contracts/account/schema/valence-account.json b/contracts/account/schema/valence-account.json index e59b4336..07de2ea6 100644 --- a/contracts/account/schema/valence-account.json +++ b/contracts/account/schema/valence-account.json @@ -1,6 +1,6 @@ { "contract_name": "valence-account", - "contract_version": "0.1.5", + "contract_version": "0.1.7", "idl_version": "1.0.0", "instantiate": { "$schema": "http://json-schema.org/draft-07/schema#", diff --git a/contracts/auction/auction/schema/auction.json b/contracts/auction/auction/schema/auction.json index 7a4e4ac9..8f60841c 100644 --- a/contracts/auction/auction/schema/auction.json +++ b/contracts/auction/auction/schema/auction.json @@ -1,6 +1,6 @@ { "contract_name": "auction", - "contract_version": "0.1.5", + "contract_version": "0.1.7", "idl_version": "1.0.0", "instantiate": { "$schema": "http://json-schema.org/draft-07/schema#", diff --git a/contracts/auction/auctions_manager/schema/auctions-manager.json b/contracts/auction/auctions_manager/schema/auctions-manager.json index db1ab2ad..53b46dc1 100644 --- a/contracts/auction/auctions_manager/schema/auctions-manager.json +++ b/contracts/auction/auctions_manager/schema/auctions-manager.json @@ -1,6 +1,6 @@ { "contract_name": "auctions-manager", - "contract_version": "0.1.5", + "contract_version": "0.1.7", "idl_version": "1.0.0", "instantiate": { "$schema": "http://json-schema.org/draft-07/schema#", @@ -185,12 +185,6 @@ "definitions": { "AdminMsgs": { "oneOf": [ - { - "type": "string", - "enum": [ - "cancel_admin_change" - ] - }, { "type": "object", "required": [ @@ -488,6 +482,19 @@ } }, "additionalProperties": false + }, + { + "type": "object", + "required": [ + "cancel_admin_change" + ], + "properties": { + "cancel_admin_change": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false } ] }, diff --git a/contracts/auction/price_oracle/schema/price-oracle.json b/contracts/auction/price_oracle/schema/price-oracle.json index 8c832cbd..22445153 100644 --- a/contracts/auction/price_oracle/schema/price-oracle.json +++ b/contracts/auction/price_oracle/schema/price-oracle.json @@ -1,6 +1,6 @@ { "contract_name": "price-oracle", - "contract_version": "0.1.5", + "contract_version": "0.1.7", "idl_version": "1.0.0", "instantiate": { "$schema": "http://json-schema.org/draft-07/schema#", @@ -359,6 +359,27 @@ }, "additionalProperties": false }, + { + "type": "object", + "required": [ + "get_local_price" + ], + "properties": { + "get_local_price": { + "type": "object", + "required": [ + "pair" + ], + "properties": { + "pair": { + "$ref": "#/definitions/Pair" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, { "type": "object", "required": [ @@ -522,6 +543,48 @@ } } }, + "get_local_price": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Array_of_Price", + "type": "array", + "items": { + "$ref": "#/definitions/Price" + }, + "definitions": { + "Decimal": { + "description": "A fixed-point decimal value with 18 fractional digits, i.e. Decimal(1_000_000_000_000_000_000) == 1.0\n\nThe greatest possible value that can be represented is 340282366920938463463.374607431768211455 (which is (2^128 - 1) / 10^18)", + "type": "string" + }, + "Price": { + "type": "object", + "required": [ + "price", + "time" + ], + "properties": { + "price": { + "$ref": "#/definitions/Decimal" + }, + "time": { + "$ref": "#/definitions/Timestamp" + } + }, + "additionalProperties": false + }, + "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" + } + } + }, "get_price": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Price", diff --git a/contracts/auction/price_oracle/src/contract.rs b/contracts/auction/price_oracle/src/contract.rs index 65db8c85..dfdb3fb0 100644 --- a/contracts/auction/price_oracle/src/contract.rs +++ b/contracts/auction/price_oracle/src/contract.rs @@ -16,11 +16,13 @@ use valence_package::event_indexing::{ValenceEvent, ValenceGenericEvent}; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; -use crate::state::{Config, PriceStep, ASTRO_PRICE_PATHS, CONFIG}; +use crate::state::{Config, PriceStep, ASTRO_PRICE_PATHS, CONFIG, LOCAL_PRICES}; const CONTRACT_NAME: &str = "crates.io:oracle"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); +const TWAP_PRICE_MAX_LEN: usize = 10; + #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, @@ -47,7 +49,7 @@ pub fn instantiate( #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( - deps: DepsMut, + mut deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, @@ -58,6 +60,7 @@ pub fn execute( let config = CONFIG.load(deps.storage)?; + // We get the prices from the auction let auction_addr = PAIRS .query( &deps.querier, @@ -65,13 +68,14 @@ pub fn execute( pair.clone(), )? .ok_or(ContractError::PairAuctionNotFound)?; - let twap_prices = TWAP_PRICES.query(&deps.querier, auction_addr)?; + let auction_twap_prices = TWAP_PRICES.query(&deps.querier, auction_addr)?; let source; - let price = if can_update_price_from_auction(&config, &env, &twap_prices) { + // We get last price either form auction or astroport + let last_price = if can_update_price_from_auction(&config, &env, &auction_twap_prices) { source = "auction"; - get_avg_price(twap_prices) + auction_twap_prices[0].clone() } else { let steps = ASTRO_PRICE_PATHS .load(deps.storage, pair.clone()) @@ -80,12 +84,17 @@ pub fn execute( get_price_from_astroport(deps.as_ref(), &env, steps)? }; + let local_prices = update_local_price(deps.branch(), pair.clone(), last_price.clone())?; + + // Calculate the average price + let avg_price = get_avg_price(local_prices); + // Save price - PRICES.save(deps.storage, pair.clone(), &price)?; + PRICES.save(deps.storage, pair.clone(), &avg_price)?; let event = ValenceEvent::OracleUpdatePrice { pair: pair.clone(), - price: price.price, + price: avg_price.price, source: source.to_string(), }; @@ -120,19 +129,21 @@ pub fn execute( Err(_) => Ok(()), }?; + let price = Price { + price, + time: env.block.time, + }; + let local_prices = update_local_price(deps.branch(), pair.clone(), price.clone())?; + + // Calculate the average price + let avg_price = get_avg_price(local_prices); + // Save price - PRICES.save( - deps.storage, - pair.clone(), - &Price { - price, - time: env.block.time, - }, - )?; + PRICES.save(deps.storage, pair.clone(), &avg_price)?; let event = ValenceEvent::OracleUpdatePrice { pair, - price, + price: price.price, source: "manual".to_string(), }; @@ -248,6 +259,30 @@ fn can_update_price_from_auction( true } +fn update_local_price( + deps: DepsMut, + pair: Pair, + price: Price, +) -> Result, cosmwasm_std::StdError> { + // Update the oracle local prices and add last price + let mut local_prices = match LOCAL_PRICES.load(deps.storage, pair.clone()) { + Ok(prices) => prices, + Err(_) => VecDeque::new(), + }; + + // if we have the max amount of prices already, remove the last one first + if local_prices.len() >= TWAP_PRICE_MAX_LEN { + local_prices.pop_back(); + } + + // Push the last price into the vector + local_prices.push_front(price.clone()); + + // Save the new list of prices + LOCAL_PRICES.save(deps.storage, pair.clone(), &local_prices)?; + Ok(local_prices) +} + fn get_avg_price(vec: VecDeque) -> Price { let (total_count, prices_sum) = vec.iter().fold( (Decimal::zero(), Decimal::zero()), @@ -288,8 +323,8 @@ fn get_price_from_astroport( .checked_add(res.spread_amount)?, 0, )?; - deps.api.debug(format!("res: {:?}", res).as_str()); - deps.api.debug(format!("Price step: {:?}", price).as_str()); + // deps.api.debug(format!("res: {:?}", res).as_str()); + // deps.api.debug(format!("Price step: {:?}", price).as_str()); Ok(price) }, @@ -314,6 +349,11 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result { + let price: Vec = LOCAL_PRICES.load(deps.storage, pair)?.into(); + + Ok(to_json_binary(&price)?) + } QueryMsg::GetAllPrices { from, limit } => { let from = from.map(Bound::::exclusive); let prices = PRICES diff --git a/contracts/auction/price_oracle/src/msg.rs b/contracts/auction/price_oracle/src/msg.rs index cf9fe177..371a912d 100644 --- a/contracts/auction/price_oracle/src/msg.rs +++ b/contracts/auction/price_oracle/src/msg.rs @@ -48,6 +48,8 @@ pub enum QueryMsg { /// Get the minimum amount users can auction #[returns(Price)] GetPrice { pair: Pair }, + #[returns(Vec)] + GetLocalPrice { pair: Pair }, #[returns(Vec<(Pair, Price)>)] GetAllPrices { from: Option, diff --git a/contracts/auction/price_oracle/src/state.rs b/contracts/auction/price_oracle/src/state.rs index fa328535..2e7a0fd2 100644 --- a/contracts/auction/price_oracle/src/state.rs +++ b/contracts/auction/price_oracle/src/state.rs @@ -1,10 +1,14 @@ -use auction_package::Pair; +use std::collections::VecDeque; + +use auction_package::{Pair, Price}; use cosmwasm_schema::cw_serde; use cosmwasm_std::Addr; use cw_storage_plus::{Item, Map}; pub const CONFIG: Item = Item::new("config"); pub const ASTRO_PRICE_PATHS: Map> = Map::new("astro_price_paths"); +/// Local last 10 prices to be calculated for the average +pub const LOCAL_PRICES: Map> = Map::new("local_prices"); #[cw_serde] pub struct Config { diff --git a/contracts/services/rebalancer/schema/rebalancer.json b/contracts/services/rebalancer/schema/rebalancer.json index c260e782..da349de1 100644 --- a/contracts/services/rebalancer/schema/rebalancer.json +++ b/contracts/services/rebalancer/schema/rebalancer.json @@ -1,6 +1,6 @@ { "contract_name": "rebalancer", - "contract_version": "0.1.5", + "contract_version": "0.1.7", "idl_version": "1.0.0", "instantiate": { "$schema": "http://json-schema.org/draft-07/schema#", @@ -109,12 +109,6 @@ "title": "ExecuteMsg", "description": "Rebalancer execute msgs.", "oneOf": [ - { - "type": "string", - "enum": [ - "approve_admin_change" - ] - }, { "type": "object", "required": [ @@ -150,6 +144,19 @@ }, "additionalProperties": false }, + { + "type": "object", + "required": [ + "approve_admin_change" + ], + "properties": { + "approve_admin_change": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, { "description": "Register this account to the service.", "type": "object", @@ -443,14 +450,15 @@ "maxItems": 2, "minItems": 2 }, + "RebalancerAccountType": { + "type": "string", + "enum": [ + "regular", + "program" + ] + }, "RebalancerAdminMsg": { "oneOf": [ - { - "type": "string", - "enum": [ - "cancel_admin_change" - ] - }, { "type": "object", "required": [ @@ -644,6 +652,19 @@ } }, "additionalProperties": false + }, + { + "type": "object", + "required": [ + "cancel_admin_change" + ], + "properties": { + "cancel_admin_change": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false } ] }, @@ -656,6 +677,14 @@ "targets" ], "properties": { + "account_type": { + "default": "regular", + "allOf": [ + { + "$ref": "#/definitions/RebalancerAccountType" + } + ] + }, "base_denom": { "description": "Base denom we will be calculating everything based on", "type": "string" @@ -1161,6 +1190,13 @@ }, "additionalProperties": false }, + "RebalancerAccountType": { + "type": "string", + "enum": [ + "regular", + "program" + ] + }, "RebalancerConfig": { "type": "object", "required": [ @@ -1173,6 +1209,14 @@ "targets" ], "properties": { + "account_type": { + "default": "regular", + "allOf": [ + { + "$ref": "#/definitions/RebalancerAccountType" + } + ] + }, "base_denom": { "description": "The base denom we will be calculating everything based on", "type": "string" @@ -1272,6 +1316,14 @@ "targets" ], "properties": { + "account_type": { + "default": "regular", + "allOf": [ + { + "$ref": "#/definitions/RebalancerAccountType" + } + ] + }, "base_denom": { "description": "The base denom we will be calculating everything based on", "type": "string" @@ -1409,6 +1461,13 @@ }, "additionalProperties": false }, + "RebalancerAccountType": { + "type": "string", + "enum": [ + "regular", + "program" + ] + }, "SignedDecimal": { "description": "A signed fixed-point decimal value with 18 fractional digits, i.e. SignedDecimal(1_000_000_000_000_000_000) == 1.0\n\nThe greatest possible value that can be represented is 170141183460469231731.687303715884105727 (which is (2^127 - 1) / 10^18) and the smallest is -170141183460469231731.687303715884105728 (which is -2^127 / 10^18).", "type": "string" @@ -1605,6 +1664,13 @@ } ] }, + "RebalancerAccountType": { + "type": "string", + "enum": [ + "regular", + "program" + ] + }, "RebalancerConfig": { "type": "object", "required": [ @@ -1617,6 +1683,14 @@ "targets" ], "properties": { + "account_type": { + "default": "regular", + "allOf": [ + { + "$ref": "#/definitions/RebalancerAccountType" + } + ] + }, "base_denom": { "description": "The base denom we will be calculating everything based on", "type": "string" diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index 8b748194..0989f7bb 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -311,24 +311,44 @@ pub fn do_rebalance( // is independent of other trade msg // This means 1 trade might fail while another pass, which means rebalance strategy was not executed 100% this cycle // but this will be corrected on the next rebalance cycle. - let msg = if !msgs.is_empty() { - Some(SubMsg::reply_on_error( - WasmMsg::Execute { - contract_addr: account.to_string(), - msg: to_json_binary( - &valence_package::msgs::core_execute::AccountBaseExecuteMsg::SendFundsByService { - msgs, - atomic: false, - }, - )?, - funds: vec![], - }, - REPLY_DEFAULT_REBALANCE, - )) + let reb_msg = if !msgs.is_empty() { + match config.account_type { + valence_package::services::rebalancer::RebalancerAccountType::Regular => { + Some(to_json_binary( + &valence_package::msgs::core_execute::AccountBaseExecuteMsg::SendFundsByService { + msgs, + atomic: false, + }, + )?) + }, + valence_package::services::rebalancer::RebalancerAccountType::Program => { + let msgs = msgs.into_iter().map(|msg| { + SubMsg::reply_on_error(msg, 0) + }).collect(); + + Some(to_json_binary( + &valence_package::services::rebalancer::MockProgramExecuteMsg::ExecuteSubmsgs { + msgs, + payload: None, + }, + )?) + }, + } } else { None }; + let msg = reb_msg.map(|reb_msg| { + SubMsg::reply_on_error( + WasmMsg::Execute { + contract_addr: account.to_string(), + msg: reb_msg, + funds: vec![], + }, + REPLY_DEFAULT_REBALANCE, + ) + }); + // We edit config to save data for the next rebalance calculation config.last_rebalance = env.block.time; diff --git a/contracts/services_manager/schema/services-manager.json b/contracts/services_manager/schema/services-manager.json index bfdeee81..2e158f4a 100644 --- a/contracts/services_manager/schema/services-manager.json +++ b/contracts/services_manager/schema/services-manager.json @@ -1,6 +1,6 @@ { "contract_name": "services-manager", - "contract_version": "0.1.5", + "contract_version": "0.1.7", "idl_version": "1.0.0", "instantiate": { "$schema": "http://json-schema.org/draft-07/schema#", @@ -247,12 +247,6 @@ "ServicesManagerAdminMsg": { "description": "Admin messages for services manager", "oneOf": [ - { - "type": "string", - "enum": [ - "cancel_admin_change" - ] - }, { "description": "Add a service to the services manager", "type": "object", @@ -387,6 +381,19 @@ }, "additionalProperties": false }, + { + "type": "object", + "required": [ + "cancel_admin_change" + ], + "properties": { + "cancel_admin_change": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, { "type": "object", "required": [ diff --git a/packages/auction-package/src/helpers.rs b/packages/auction-package/src/helpers.rs index 11635c66..48ee549f 100644 --- a/packages/auction-package/src/helpers.rs +++ b/packages/auction-package/src/helpers.rs @@ -29,6 +29,15 @@ pub struct ChainHaltConfig { pub block_avg: Decimal, } +impl Default for ChainHaltConfig { + fn default() -> Self { + Self { + cap: 86000_u128, + block_avg: Decimal::one() + Decimal::one(), + } + } +} + #[cw_serde] pub struct AuctionConfig { pub is_paused: bool, diff --git a/packages/auction-package/src/lib.rs b/packages/auction-package/src/lib.rs index 6b5ed9f3..d8020015 100644 --- a/packages/auction-package/src/lib.rs +++ b/packages/auction-package/src/lib.rs @@ -1,4 +1,4 @@ -use std::fmt::Display; +use std::{fmt::Display, str::FromStr}; use cosmwasm_schema::cw_serde; use cosmwasm_std::{Decimal, Timestamp}; @@ -49,6 +49,18 @@ pub struct PriceFreshnessStrategy { pub multipliers: Vec<(Decimal, Decimal)>, } +impl Default for PriceFreshnessStrategy { + fn default() -> Self { + Self { + limit: Decimal::from_atomics(3_u128, 0).unwrap(), + multipliers: vec![( + Decimal::from_atomics(1_u128, 0).unwrap(), + Decimal::from_str("1.5").unwrap(), + )], + } + } +} + #[cw_serde] pub struct Price { pub price: Decimal, diff --git a/packages/cw-pid/Cargo.toml b/packages/cw-pid/Cargo.toml new file mode 100644 index 00000000..43d1ed28 --- /dev/null +++ b/packages/cw-pid/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "cw-pid" +version = { workspace = true } +edition = { workspace = true } +authors = ["Art3miX "] +description = "Package for valence set of contracts" +license = { workspace = true } + +[dependencies] +cosmwasm-std = { workspace = true } +serde = { workspace = true } +serde-wasm-bindgen = "0.4" +wasm-bindgen = "0.2" diff --git a/packages/cw-pid/src/lib.rs b/packages/cw-pid/src/lib.rs new file mode 100644 index 00000000..88fdeade --- /dev/null +++ b/packages/cw-pid/src/lib.rs @@ -0,0 +1 @@ +pub mod pid; diff --git a/packages/cw-pid/src/pid.rs b/packages/cw-pid/src/pid.rs new file mode 100644 index 00000000..58701d82 --- /dev/null +++ b/packages/cw-pid/src/pid.rs @@ -0,0 +1,63 @@ +use cosmwasm_std::SignedDecimal; +use serde::{Deserialize, Serialize}; +use wasm_bindgen::JsValue; + +#[derive(Serialize, Deserialize)] +pub struct PID { + p: u32, + i: u32, + d: u32, +} + +impl PID { + pub fn into_signed_decimal(&self) -> SignedPID { + let p = SignedDecimal::bps(self.p as i64); + let i = SignedDecimal::bps(self.i as i64); + let d = SignedDecimal::bps(self.d as i64); + + SignedPID { p, i, d } + } +} + +pub struct SignedPID { + p: SignedDecimal, + i: SignedDecimal, + d: SignedDecimal, +} + +#[derive(Serialize, Deserialize)] +pub struct Input { + pid: PID, + input: SignedDecimal, + target: SignedDecimal, + dt: SignedDecimal, + last_i: SignedDecimal, + last_input: SignedDecimal, +} + +#[derive(Serialize, Deserialize)] +pub struct Output { + value: SignedDecimal, + i: SignedDecimal, +} + +pub fn pid(input_js: JsValue) -> Output { + let input: Input = serde_wasm_bindgen::from_value(input_js).unwrap(); + let pid = input.pid.into_signed_decimal(); + let error = input.target - input.input; + + let p = error * pid.p; + let i = input.last_i + (error * pid.i * input.dt); + let mut d = if input.last_input.is_zero() { + SignedDecimal::zero() + } else { + input.input - input.last_input + }; + + d = d * pid.d / input.dt; + + Output { + value: p + i - d, + i, + } +} diff --git a/packages/valence-package/src/services/rebalancer.rs b/packages/valence-package/src/services/rebalancer.rs index 6798c72a..ce022929 100644 --- a/packages/valence-package/src/services/rebalancer.rs +++ b/packages/valence-package/src/services/rebalancer.rs @@ -1,8 +1,8 @@ use auction_package::Pair; use cosmwasm_schema::cw_serde; use cosmwasm_std::{ - coins, Addr, Api, BankMsg, CosmosMsg, Decimal, Env, MessageInfo, SignedDecimal, Timestamp, - Uint128, + coins, Addr, Api, BankMsg, CosmosMsg, Decimal, Env, MessageInfo, SignedDecimal, SubMsg, + Timestamp, Uint128, }; use cw_utils::{must_pay, Expiration}; use std::borrow::Borrow; @@ -53,6 +53,14 @@ pub enum RebalancerAdminMsg { CancelAdminChange {}, } +#[cw_serde] +#[derive(Default)] +pub enum RebalancerAccountType { + #[default] + Regular, + Program, +} + #[cw_serde] pub struct RebalancerData { /// The trustee address that can pause/resume the service @@ -67,6 +75,8 @@ pub struct RebalancerData { pub max_limit_bps: Option, // BPS /// The strategy to use when overriding targets pub target_override_strategy: TargetOverrideStrategy, + #[serde(default)] + pub account_type: RebalancerAccountType, } #[cw_serde] @@ -104,6 +114,7 @@ impl RebalancerData { last_rebalance: Timestamp::from_seconds(0), has_min_balance, target_override_strategy: self.target_override_strategy, + account_type: self.account_type, }) } } @@ -124,6 +135,8 @@ pub struct RebalancerConfig { pub last_rebalance: Timestamp, pub has_min_balance: bool, pub target_override_strategy: TargetOverrideStrategy, + #[serde(default)] + pub account_type: RebalancerAccountType, } #[cw_serde] @@ -459,9 +472,21 @@ impl RebalanceTrade { } } +#[cw_serde] +pub enum MockProgramExecuteMsg { + ExecuteSubmsgs { + msgs: Vec, + // json encoded + payload: Option, + }, +} + #[cfg(test)] mod test { - use crate::error::ValenceError; + use cosmwasm_schema::cw_serde; + use cosmwasm_std::{from_json, to_json_binary, Addr}; + + use crate::{error::ValenceError, services::rebalancer::RebalancerAccountType}; use super::PID; @@ -495,4 +520,27 @@ mod test { assert_eq!(err, ValenceError::PIDErrorOver) } + + #[test] + fn test_parse() { + #[cw_serde] + struct Data1 { + /// the address that can pause and resume the service + pub trustee: Option, + } + + #[cw_serde] + struct Data2 { + /// the address that can pause and resume the service + pub trustee: Option, + #[serde(default)] + pub account_type: RebalancerAccountType, + } + + let one = Data1 { trustee: None }; + + let parse = to_json_binary(&one).unwrap(); + let two = from_json::(&parse).unwrap(); + println!("{:?}", two); + } } diff --git a/scripts/add_service_to_manager.sh b/scripts/add_service_to_manager.sh index 68df4ed6..029a5609 100755 --- a/scripts/add_service_to_manager.sh +++ b/scripts/add_service_to_manager.sh @@ -21,6 +21,13 @@ elif [[ "$CHAIN" == 'neutron' || "$CHAIN" == 'ntrn' ]]; then FEES="1000untrn" ADDR_SERVICES_MANAGER="neutron1gantvpnat0la8kkkzrnj48d5d8wxdjllh5r2w4r2hcrpwy00s69quypupa" +elif [[ "$CHAIN" == 'ntrn-testnet' ]]; then + BINARY="neutrond" + GAS_PRICES="0.075untrn" + OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" + FEES="1000untrn" + + ADDR_SERVICES_MANAGER="neutron13ncggwefau3xla04vlugy20meap7g7a9lf2d2sxwgwvgr9mnn3yqkpjzs6" else echo "Unknown chain" fi diff --git a/scripts/init.sh b/scripts/init.sh index 69515b51..410c0f9a 100755 --- a/scripts/init.sh +++ b/scripts/init.sh @@ -43,6 +43,25 @@ elif [[ "$CHAIN" == 'neutron' || "$CHAIN" == 'ntrn' ]]; then # General data per chain WHITELISTED_DENOMS='["untrn", "ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"]' WHITELISTED_BASE_DENOMS='[{"denom": "untrn", "min_balance_limit": "10000000"}, {"denom": "ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9", "min_balance_limit": "10000000"}]' +elif [[ "$CHAIN" == 'ntrn-testnet' ]]; then + BINARY="neutrond" + GAS_PRICES="0.075untrn" + OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" + + CODE_ID_ACCOUNT=5677 + CODE_ID_SERVICES_MANAGER=5674 + CODE_ID_REBALANCER=5675 + CODE_ID_ORACLE=5676 + CODE_ID_AUCTION=5679 + CODE_ID_AUCTIONS_MANAGER=5673 + + # Contracts addresses for init below + ADDR_SERVICES_MANAGER="neutron13ncggwefau3xla04vlugy20meap7g7a9lf2d2sxwgwvgr9mnn3yqkpjzs6" + ADDR_AUCTIONS_MANAGER="neutron1669ftav8rv4hjuak89w04k7f0f7m9qq9564s00ld4m8dvhsr5hfsxy3x46" + + # General data per chain + WHITELISTED_DENOMS='["untrn", "factory/neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68/rebalancer-test"]' + WHITELISTED_BASE_DENOMS='[{"denom": "untrn", "min_balance_limit": "1000"}, {"denom": "factory/neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68/rebalancer-test", "min_balance_limit": "1000"}]' else echo "Unknown chain" fi @@ -74,15 +93,16 @@ elif [[ "$COMMAND" == 'services-manager' ]]; then $BINARY tx wasm init $CODE_ID_SERVICES_MANAGER "$init_msg" --label "Valence services manager" \ --admin $OWNER_ADDR --from $OWNER_ADDR $EXECUTE_FLAGS - ################################################ ############### Auctions Manager ############### ################################################ elif [[ "$COMMAND" == 'auctions-manager' ]]; then init_msg=$(jq -n \ --argjson auction_code_id $CODE_ID_AUCTION \ + --arg server_addr $OWNER_ADDR \ '{ auction_code_id: $auction_code_id, - min_auction_amount: [["untrn", "20000"], ["ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9", "10000"]] + min_auction_amount: [["untrn", {"send": "1000", "start_auction": "1000"}], ["factory/neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68/rebalancer-test", {"send": "1000", "start_auction": "1000"}]], + server_addr: $server_addr }') $BINARY tx wasm init $CODE_ID_AUCTIONS_MANAGER "$init_msg" --label "Valence auctions manager" \ @@ -108,9 +128,9 @@ elif [[ "$COMMAND" == 'rebalancer' ]]; then base_denom_whitelist: $whitelist_base_denom, cycle_period: 60, fees: { - denom: "untrn", - register_fee: "1000000", - resume_fee: "1000000" + denom: "factory/neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68/rebalancer-test", + register_fee: "1000", + resume_fee: "1000" }, }') @@ -126,7 +146,11 @@ elif [[ "$COMMAND" == 'oracle' ]]; then init_msg=$( jq -n \ --arg auctions_manager_addr "$ADDR_AUCTIONS_MANAGER" \ - '{auctions_manager_addr: $auctions_manager_addr}' + '{ + auctions_manager_addr: $auctions_manager_addr, + seconds_allow_manual_change: 60, + seconds_auction_prices_fresh: 360 + }' ) $BINARY tx wasm init $CODE_ID_ORACLE "$init_msg" --label "Valence oracle" \ diff --git a/scripts/migrate.sh b/scripts/migrate.sh index 163a83fb..1d9c5d23 100755 --- a/scripts/migrate.sh +++ b/scripts/migrate.sh @@ -15,12 +15,12 @@ SERVICES_MANAGER_ADDR="neutron1gantvpnat0la8kkkzrnj48d5d8wxdjllh5r2w4r2hcrpwy00s AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" # Code ids -REBALANCER_CODE_ID=1501 -ORACLE_CODE_ID=1505 -SERVICES_MANAGER_CODE_ID=1503 -AUCTIONS_MANAGER_CODE_ID=1502 -AUCTION_CODE_ID=1504 -ACCOUNT_CODE_ID=1506 +SERVICES_MANAGER_CODE_ID=1615 +REBALANCER_CODE_ID=1616 +AUCTIONS_MANAGER_CODE_ID=1614 +AUCTION_CODE_ID=1617 +ORACLE_CODE_ID=1619 +ACCOUNT_CODE_ID=1618 # array of pairs we have to migrate declare -a PAIRS=( diff --git a/scripts/new_auction.sh b/scripts/new_auction.sh index fff6083c..44ac5c7e 100755 --- a/scripts/new_auction.sh +++ b/scripts/new_auction.sh @@ -15,6 +15,12 @@ elif [[ "$CHAIN" == 'neutron' || "$CHAIN" == 'ntrn' ]]; then OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" ADDR_AUCTIONS_MANAGER="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" +elif [[ "$CHAIN" == 'ntrn-testnet' ]]; then + BINARY="neutrond" + GAS_PRICES="0.075untrn" + OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" + + ADDR_AUCTIONS_MANAGER="neutron1669ftav8rv4hjuak89w04k7f0f7m9qq9564s00ld4m8dvhsr5hfsxy3x46" else echo "Unknown chain" fi @@ -23,8 +29,8 @@ EXECUTE_FLAGS="--gas-prices $GAS_PRICES --gas auto --gas-adjustment 1.4 -y" # EXECUTE_FLAGS="--fees $FEES --gas auto --gas-adjustment 1.4 -y" ## You can change value manually and uncomment it here -PAIR='["ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81", "factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt"]' -LABEL="auction USDC/NEWT" +PAIR='["factory/neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68/rebalancer-test", "untrn"]' +LABEL="auction TEST/NTRN" AUCTION_STRATEGY='{ "start_price_perc": 5000, "end_price_perc": 5000 }' CHAIN_HALT='{ "cap": "14400", "block_avg": "3" }' PRICE_FRESHNESS='{ "limit": "3", "multipliers": [["2", "2"], ["1", "1.5"]] }' diff --git a/scripts/register_to_service.sh b/scripts/register_to_service.sh index e52b3b95..ef3fbee8 100755 --- a/scripts/register_to_service.sh +++ b/scripts/register_to_service.sh @@ -5,7 +5,7 @@ execute_msg=$(jq -n \ '{ "register_to_service": { "service_name": "rebalancer", - "data": "ewoiYmFzZV9kZW5vbSI6ICJpYmMvQzRDRkY0NkZENkRFMzVDQTRDRjRDRTAzMUU2NDNDOEZEQzlCQTRCOTlBRTU5OEU5QjBFRDk4RkUzQTIzMTlGOSIsCiJwaWQiOiB7ICJwIjogIjAuMSIsICJpIjogIjAiLCAiZCI6ICIwIiB9LAoidGFyZ2V0X292ZXJyaWRlX3N0cmF0ZWd5IjogInByb3BvcnRpb25hbCIsCiJ0YXJnZXRzIjogWwp7CiJkZW5vbSI6ICJpYmMvQzRDRkY0NkZENkRFMzVDQTRDRjRDRTAzMUU2NDNDOEZEQzlCQTRCOTlBRTU5OEU5QjBFRDk4RkUzQTIzMTlGOSIsCiJicHMiOiA1MDAwCn0sCnsgImRlbm9tIjogInVudHJuIiwgImJwcyI6IDUwMDAgfQpdCn0=" + "data": "ewoiYmFzZV9kZW5vbSI6ICJmYWN0b3J5L25ldXRyb24xcGh4MHN6NzA4azN0NnhkbnljOThoZ2t5aHJhNHRwNDRldDVzNjgvcmViYWxhbmNlci10ZXN0IiwKInBpZCI6IHsgInAiOiAiMC4xIiwgImkiOiAiMCIsICJkIjogIjAiIH0sCiJ0YXJnZXRfb3ZlcnJpZGVfc3RyYXRlZ3kiOiAicHJvcG9ydGlvbmFsIiwKInRhcmdldHMiOiBbCnsKImRlbm9tIjogImZhY3RvcnkvbmV1dHJvbjFwaHgwc3o3MDhrM3Q2eGRueWM5OGhna3locmE0dHA0NGV0NXM2OC9yZWJhbGFuY2VyLXRlc3QiLAoiYnBzIjogNTAwMAp9LAp7ICJkZW5vbSI6ICJ1bnRybiIsICJicHMiOiA1MDAwIH0KXQp9" } }') diff --git a/scripts/update_oracle_addr.sh b/scripts/update_oracle_addr.sh index 1edef92b..274cecdb 100755 --- a/scripts/update_oracle_addr.sh +++ b/scripts/update_oracle_addr.sh @@ -20,18 +20,23 @@ elif [[ "$CHAIN" == 'neutron' || "$CHAIN" == 'ntrn' ]]; then FEES="1000untrn" ADDR_AUCTIONS_MANAGER="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" +elif [[ "$CHAIN" == 'ntrn-testnet' ]]; then + BINARY="neutrond" + GAS_PRICES="0.075untrn" + OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" + + ADDR_AUCTIONS_MANAGER="neutron1669ftav8rv4hjuak89w04k7f0f7m9qq9564s00ld4m8dvhsr5hfsxy3x46" else echo "Unknown chain" fi EXECUTE_FLAGS="--gas-prices $GAS_PRICES --gas auto --gas-adjustment 1.4 -y" -# EXECUTE_FLAGS="--fees $FEES --gas auto --gas-adjustment 1.4 -y" execute_msg=$(jq -n \ - --arg oracle_Addr "$ORACLE_ADDR" \ + --arg oracle_addr "$ORACLE_ADDR" \ '{admin: { update_oracle: { - oracle_addr: $oracle_Addr, + oracle_addr: $oracle_addr, } }}') diff --git a/scripts/update_price.sh b/scripts/update_price.sh index 8e293865..2e77bec3 100755 --- a/scripts/update_price.sh +++ b/scripts/update_price.sh @@ -23,6 +23,13 @@ elif [[ "$CHAIN" == 'neutron' || "$CHAIN" == 'ntrn' ]]; then FEES="1000untrn" ORACLE_ADDR="neutron1s8uqyh0mmh8g66s2dectf56c08y6fvusp39undp8kf4v678ededsy6tstf" +elif [[ "$CHAIN" == 'ntrn-testnet' ]]; then + BINARY="neutrond" + GAS_PRICES="0.075untrn" + OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" + FEES="1000untrn" + + ORACLE_ADDR="neutron1g4qcmk65nw57hmqlzk6cejnftg20zmctky0l2epdfz3npw3x2cmqprul6f" else echo "Unknown chain" fi @@ -45,7 +52,7 @@ else --arg pair1 "$PAIR1" \ --arg pair2 "$PAIR2" \ --arg price "$PRICE" \ - '{update_price: { + '{manual_price_update: { pair: [$pair1, $pair2], price: $price, }}') diff --git a/scripts/upload.sh b/scripts/upload.sh index e97614ee..d5e7b006 100755 --- a/scripts/upload.sh +++ b/scripts/upload.sh @@ -18,7 +18,14 @@ elif [[ "$CHAIN" == 'neutron' || "$CHAIN" == 'ntrn' ]]; then OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" +elif [[ "$CHAIN" == 'ntrn-testnet' ]]; then + BINARY="neutrond" + GAS_PRICES="0.075untrn" + OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" + AUCTIONS_MANAGER_ADDR="neutron1669ftav8rv4hjuak89w04k7f0f7m9qq9564s00ld4m8dvhsr5hfsxy3x46" + else + echo "Unknown chain" fi @@ -43,7 +50,6 @@ REBALANCER_FILE_NAME="$ARTIFACTS_PATH/rebalancer.wasm" if [[ "$COMMAND" == 'account' ]]; then $BINARY tx wasm s $ACCOUNT_FILE_NAME --from $OWNER_ADDR $ACCOUNT_EXECUTE_FLAGS elif [[ "$COMMAND" == 'auction' ]]; then - # Auction needs to be instantiated by the manager, so need to change the --instantiate-anyof-addresses $BINARY tx wasm s $AUCTION_FILE_NAME --from $OWNER_ADDR $EXECUTE_FLAGS elif [[ "$COMMAND" == 'auctions-manager' ]]; then $BINARY tx wasm s $AUCTIONS_MANAGER_FILE_NAME --from $OWNER_ADDR $EXECUTE_FLAGS diff --git a/tests/rust-tests/src/live_debugging/test_specific_config.rs b/tests/rust-tests/src/live_debugging/test_specific_config.rs index 0a99cb49..ca1fc563 100644 --- a/tests/rust-tests/src/live_debugging/test_specific_config.rs +++ b/tests/rust-tests/src/live_debugging/test_specific_config.rs @@ -1,3 +1,4 @@ +#![allow(clippy::all)] // Test a specific config of an account with the state of the system // This test should give us an idea of how the next rebalance would work, and give us // a manualy way to check what trades the rebalancer is calculating diff --git a/tests/rust-tests/src/suite/suite_auction.rs b/tests/rust-tests/src/suite/suite_auction.rs index 475b57fd..ea0d0246 100644 --- a/tests/rust-tests/src/suite/suite_auction.rs +++ b/tests/rust-tests/src/suite/suite_auction.rs @@ -690,6 +690,16 @@ impl Suite { .unwrap() } + pub fn query_oracle_local_price(&self, pair: Pair) -> Vec { + self.app + .wrap() + .query_wasm_smart( + self.oracle_addr.clone(), + &price_oracle::msg::QueryMsg::GetLocalPrice { pair }, + ) + .unwrap() + } + pub fn query_oracle_all_prices( &self, from: Option, diff --git a/tests/rust-tests/src/suite/suite_builder.rs b/tests/rust-tests/src/suite/suite_builder.rs index 44d53c77..9fc2a38d 100644 --- a/tests/rust-tests/src/suite/suite_builder.rs +++ b/tests/rust-tests/src/suite/suite_builder.rs @@ -138,6 +138,7 @@ impl SuiteBuilder { }, max_limit_bps: None, target_override_strategy: TargetOverrideStrategy::Proportional, + account_type: Default::default(), } } diff --git a/tests/rust-tests/src/test_service_management.rs b/tests/rust-tests/src/test_service_management.rs index 4a6d0509..8b0e2767 100644 --- a/tests/rust-tests/src/test_service_management.rs +++ b/tests/rust-tests/src/test_service_management.rs @@ -121,6 +121,7 @@ fn test_register() { last_rebalance: Timestamp::from_seconds(0), has_min_balance: false, target_override_strategy: TargetOverrideStrategy::Proportional, + account_type: Default::default(), }, ); @@ -167,6 +168,7 @@ fn test_register() { last_rebalance: Timestamp::from_seconds(0), has_min_balance: false, target_override_strategy: TargetOverrideStrategy::Proportional, + account_type: Default::default(), }, ); @@ -425,6 +427,7 @@ fn test_update() { last_rebalance: Timestamp::from_seconds(0), has_min_balance: true, target_override_strategy: TargetOverrideStrategy::Priority, + account_type: Default::default(), }, ) } diff --git a/tests/rust-tests/src/tests_auctions/test_astro.rs b/tests/rust-tests/src/tests_auctions/test_astro.rs index 716ca177..d9d1de70 100644 --- a/tests/rust-tests/src/tests_auctions/test_astro.rs +++ b/tests/rust-tests/src/tests_auctions/test_astro.rs @@ -45,7 +45,7 @@ fn test_add_path_for_pair() { fn test_basic_astro_default() { let mut suite = SuiteBuilder::default().build_basic(true); - let old_oracle_price = suite.query_oracle_price(suite.pair.clone()); + let old_oracle_last_local_price = suite.query_oracle_local_price(suite.pair.clone())[0].clone(); // This should error because we don't have astro path for the price yet // and no auction ran so far let err = suite.update_price_err(suite.pair.clone()); @@ -91,16 +91,16 @@ fn test_basic_astro_default() { // Make sure the pool price is not the same as the old price // To confirm the price actually changed later - assert_ne!(pool_price, old_oracle_price.price); + assert_ne!(pool_price, old_oracle_last_local_price.price); // Try to update again suite.update_price(suite.pair.clone()).unwrap(); // Verify we do get an acceptable price (query price from pool) - let oracle_price = suite.query_oracle_price(suite.pair.clone()); + let oracle_last_local_price = suite.query_oracle_local_price(suite.pair.clone())[0].clone(); println!("pool_price: {:?}", pool_price); - println!("oracle_price: {:?}", oracle_price); - assert_eq!(oracle_price.price, pool_price); + println!("oracle_price: {:?}", oracle_last_local_price); + assert_eq!(oracle_last_local_price.price, pool_price); } // Test for a pair that doesn't have a direct pool, so the astro path is 2 pools diff --git a/tests/rust-tests/src/tests_auctions/test_oracle.rs b/tests/rust-tests/src/tests_auctions/test_oracle.rs index 5ef4e056..52c4147c 100644 --- a/tests/rust-tests/src/tests_auctions/test_oracle.rs +++ b/tests/rust-tests/src/tests_auctions/test_oracle.rs @@ -1,6 +1,9 @@ +use std::borrow::BorrowMut; + use cosmwasm_std::{coins, Addr, Decimal}; use cw_multi_test::Executor; use cw_utils::Expiration; +use price_oracle::state::PriceStep; use crate::suite::{ suite::{Suite, DAY, DEFAULT_BLOCK_TIME}, @@ -323,3 +326,77 @@ fn test_update_config() { assert_eq!(new_oracle_config.seconds_allow_manual_change, 12); assert_eq!(new_oracle_config.seconds_auction_prices_fresh, 455); } + +#[test] +fn test_local_prices() { + let mut suite = Suite::default(); + let funds = coins(100_u128, suite.pair.0.clone()); + + // do 3 auctions + suite.finalize_auction(&funds); + suite.finalize_auction(&funds); + suite.finalize_auction(&funds); + + // Update the price from auction + suite.update_price(suite.pair.clone()).unwrap(); + + // Register the astro path + let path = vec![PriceStep { + denom1: suite.pair.0.to_string(), + denom2: suite.pair.1.to_string(), + pool_address: suite + .astro_pools + .get(&suite.pair.clone().into()) + .unwrap() + .clone(), + }]; + suite + .add_astro_path_to_oracle(suite.pair.clone(), path) + .unwrap(); + + // Randomize the pool a little to get a "nice" price + let mut rng = rand::thread_rng(); + + for _ in 0..10 { + suite.do_random_swap( + rng.borrow_mut(), + suite.pair.clone(), + 100_000_u128, + 1_000_000_u128, + ); + } + + let pool_price = suite.query_astro_pool_price( + suite + .astro_pools + .get(&suite.pair.clone().into()) + .unwrap() + .clone(), + suite.pair.clone(), + ); + + // make sure the last price on local, is not the price from the pool + let local_prices = suite.query_oracle_local_price(suite.pair.clone()); + assert_ne!(local_prices[0].price, pool_price); + + // Update price, should get it from astro + suite.update_block(DAY / DEFAULT_BLOCK_TIME * 2); + + // Update the price from auction + suite.update_price(suite.pair.clone()).unwrap(); + + let local_prices = suite.query_oracle_local_price(suite.pair.clone()); + + // We should have 2 prices because we updated prices twice + assert_eq!(local_prices.len(), 3); + // The first price should be the pool price + assert_eq!(local_prices[0].price, pool_price); + + // make sure the actual price is the avg of the local prices + let oracle_price = suite.query_oracle_price(suite.pair.clone()); + assert_eq!( + oracle_price.price, + (local_prices[0].price + local_prices[1].price + local_prices[2].price) + / Decimal::from_atomics(3_u128, 0).unwrap() + ); +} diff --git a/tests/rust-tests/src/tests_rebalancer/test_management.rs b/tests/rust-tests/src/tests_rebalancer/test_management.rs index 4ad3cef4..1fe7bd4d 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_management.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_management.rs @@ -265,7 +265,7 @@ fn test_update_whitelist() { let whitelist = suite.query_rebalancer_whitelists().unwrap(); // lets make sure the whitelist is what we expect for the tests - assert!(whitelist.denom_whitelist.contains(&ATOM.to_string())); + assert!(whitelist.denom_whitelist.contains(ATOM)); assert!(whitelist.denom_whitelist.len() == 3); assert!(whitelist .base_denom_whitelist @@ -282,8 +282,8 @@ fn test_update_whitelist() { .unwrap(); let whitelist = suite.query_rebalancer_whitelists().unwrap(); - assert!(!whitelist.denom_whitelist.contains(&ATOM.to_string())); - assert!(!whitelist.denom_whitelist.contains(&NTRN.to_string())); + assert!(!whitelist.denom_whitelist.contains(ATOM)); + assert!(!whitelist.denom_whitelist.contains(NTRN)); assert!(whitelist.denom_whitelist.len() == 2); // remove atom, add random