From af75fa5fe2edcb7191f1cdaf29b88ec7aac7e4d9 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:38:11 +0100 Subject: [PATCH 01/19] Add initial constants and error codes for Bitcoin Yield Aggregator contract - Define contract owner constant - Add error codes for various contract operations including authorization, amount validation, balance checks, protocol whitelisting, strategy management, and token validation --- Clarinet.toml | 22 ++++++++++++---------- contracts/btc-yielld-aggregator.clar | 23 +++++++++++++++++++++++ tests/btc-yielld-aggregator_test.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 10 deletions(-) create mode 100644 contracts/btc-yielld-aggregator.clar create mode 100644 tests/btc-yielld-aggregator_test.ts diff --git a/Clarinet.toml b/Clarinet.toml index 55283db..b7b2505 100644 --- a/Clarinet.toml +++ b/Clarinet.toml @@ -1,20 +1,22 @@ - [project] name = "bitcoin_yield_aggregator" authors = [] +description = "" telemetry = true +requirements = [] +[contracts.btc-yielld-aggregator] +path = "contracts/btc-yielld-aggregator.clar" +depends_on = [] + +[repl] +costs_version = 2 +parser_version = 2 + [repl.analysis] passes = ["check_checker"] + [repl.analysis.check_checker] -# If true, inputs are trusted after tx_sender has been checked. +strict = false trusted_sender = false -# If true, inputs are trusted after contract-caller has been checked. trusted_caller = false -# If true, untrusted data may be passed into a private function without a -# warning, if it gets checked inside. This check will also propagate up to the -# caller. callee_filter = false - -# [contracts.counter] -# path = "contracts/counter.clar" -# depends_on = [] diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar new file mode 100644 index 0000000..d9da4ed --- /dev/null +++ b/contracts/btc-yielld-aggregator.clar @@ -0,0 +1,23 @@ +;; Title: Bitcoin Yield Aggregator +;; Summary: A comprehensive DeFi yield strategy management system +;; Description: This contract enables users to deposit tokens into various yield-generating protocols, +;; manages protocol allocations, and distributes rewards. It includes features for protocol whitelisting, +;; emergency shutdown, and dynamic APY management with robust security measures. + +;; Constants +(define-constant contract-owner tx-sender) + +;; Error Codes +(define-constant ERR-NOT-AUTHORIZED (err u1000)) +(define-constant ERR-INVALID-AMOUNT (err u1001)) +(define-constant ERR-INSUFFICIENT-BALANCE (err u1002)) +(define-constant ERR-PROTOCOL-NOT-WHITELISTED (err u1003)) +(define-constant ERR-STRATEGY-DISABLED (err u1004)) +(define-constant ERR-MAX-DEPOSIT-REACHED (err u1005)) +(define-constant ERR-MIN-DEPOSIT-NOT-MET (err u1006)) +(define-constant ERR-INVALID-PROTOCOL-ID (err u1007)) +(define-constant ERR-PROTOCOL-EXISTS (err u1008)) +(define-constant ERR-INVALID-APY (err u1009)) +(define-constant ERR-INVALID-NAME (err u1010)) +(define-constant ERR-INVALID-TOKEN (err u1011)) +(define-constant ERR-TOKEN-NOT-WHITELISTED (err u1012)) \ No newline at end of file diff --git a/tests/btc-yielld-aggregator_test.ts b/tests/btc-yielld-aggregator_test.ts new file mode 100644 index 0000000..9a18ae0 --- /dev/null +++ b/tests/btc-yielld-aggregator_test.ts @@ -0,0 +1,26 @@ + +import { Clarinet, Tx, Chain, Account, types } from 'https://deno.land/x/clarinet@v0.14.0/index.ts'; +import { assertEquals } from 'https://deno.land/std@0.90.0/testing/asserts.ts'; + +Clarinet.test({ + name: "Ensure that <...>", + async fn(chain: Chain, accounts: Map) { + let block = chain.mineBlock([ + /* + * Add transactions with: + * Tx.contractCall(...) + */ + ]); + assertEquals(block.receipts.length, 0); + assertEquals(block.height, 2); + + block = chain.mineBlock([ + /* + * Add transactions with: + * Tx.contractCall(...) + */ + ]); + assertEquals(block.receipts.length, 0); + assertEquals(block.height, 3); + }, +}); From 874898888aa843e46d1d2095a4b6f532c9e2886f Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:42:25 +0100 Subject: [PATCH 02/19] Add protocol status and configuration constants - Define constants for protocol status (active/inactive) - Add configuration constants for maximum protocol ID, maximum APY, and minimum APY --- contracts/btc-yielld-aggregator.clar | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index d9da4ed..b129ca1 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -20,4 +20,13 @@ (define-constant ERR-INVALID-APY (err u1009)) (define-constant ERR-INVALID-NAME (err u1010)) (define-constant ERR-INVALID-TOKEN (err u1011)) -(define-constant ERR-TOKEN-NOT-WHITELISTED (err u1012)) \ No newline at end of file +(define-constant ERR-TOKEN-NOT-WHITELISTED (err u1012)) + +;; Protocol Status Constants +(define-constant PROTOCOL-ACTIVE true) +(define-constant PROTOCOL-INACTIVE false) + +;; Protocol Configuration Constants +(define-constant MAX-PROTOCOL-ID u100) +(define-constant MAX-APY u10000) ;; 100% APY in basis points +(define-constant MIN-APY u0) \ No newline at end of file From 77a59d073d728c718d40176aba3deeaa552d1d78 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:43:16 +0100 Subject: [PATCH 03/19] Add data variables and maps for Bitcoin Yield Aggregator contract - Define data variables for total TVL, platform fee rate, minimum and maximum deposit, and emergency shutdown status - Add data maps for user deposits, user rewards, protocols, strategy allocations, and whitelisted tokens --- contracts/btc-yielld-aggregator.clar | 30 +++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index b129ca1..d6c2155 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -29,4 +29,32 @@ ;; Protocol Configuration Constants (define-constant MAX-PROTOCOL-ID u100) (define-constant MAX-APY u10000) ;; 100% APY in basis points -(define-constant MIN-APY u0) \ No newline at end of file +(define-constant MIN-APY u0) + +;; Data Variables +(define-data-var total-tvl uint u0) +(define-data-var platform-fee-rate uint u100) ;; 1% (base 10000) +(define-data-var min-deposit uint u100000) +(define-data-var max-deposit uint u1000000000) +(define-data-var emergency-shutdown bool false) + +;; Data Maps +(define-map user-deposits + { user: principal } + { amount: uint, last-deposit-block: uint }) + +(define-map user-rewards + { user: principal } + { pending: uint, claimed: uint }) + +(define-map protocols + { protocol-id: uint } + { name: (string-ascii 64), active: bool, apy: uint }) + +(define-map strategy-allocations + { protocol-id: uint } + { allocation: uint }) + +(define-map whitelisted-tokens + { token: principal } + { approved: bool }) \ No newline at end of file From c2b6e6ab853e0176babb9202f13f2ab8a0e0c49e Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:44:11 +0100 Subject: [PATCH 04/19] Add SIP-010 token interface definition - Define SIP-010 trait with methods for transfer, get-balance, get-decimals, get-name, get-symbol, and get-total-supply --- contracts/btc-yielld-aggregator.clar | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index d6c2155..0f7cae8 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -57,4 +57,16 @@ (define-map whitelisted-tokens { token: principal } - { approved: bool }) \ No newline at end of file + { approved: bool }) + +;; SIP-010 Token Interface +(define-trait sip-010-trait + ( + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + (get-balance (principal) (response uint uint)) + (get-decimals () (response uint uint)) + (get-name () (response (string-ascii 32) uint)) + (get-symbol () (response (string-ascii 32) uint)) + (get-total-supply () (response uint uint)) + ) +) \ No newline at end of file From 4c4bc76ad13e4c68d8cb135a4e40fe5e46071d78 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:44:44 +0100 Subject: [PATCH 05/19] Add authorization and validation functions - Define private function to check if the sender is the contract owner - Add validation functions for protocol ID, APY, and name - Define function to check if a protocol exists --- contracts/btc-yielld-aggregator.clar | 31 ++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 0f7cae8..600d18f 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -69,4 +69,35 @@ (get-symbol () (response (string-ascii 32) uint)) (get-total-supply () (response uint uint)) ) +) + +;; Authorization Functions +(define-private (is-contract-owner) + (is-eq tx-sender contract-owner) +) + +;; Validation Functions +(define-private (is-valid-protocol-id (protocol-id uint)) + (and + (> protocol-id u0) + (<= protocol-id MAX-PROTOCOL-ID) + ) +) + +(define-private (is-valid-apy (apy uint)) + (and + (>= apy MIN-APY) + (<= apy MAX-APY) + ) +) + +(define-private (is-valid-name (name (string-ascii 64))) + (and + (not (is-eq name "")) + (<= (len name) u64) + ) +) + +(define-private (protocol-exists (protocol-id uint)) + (is-some (map-get? protocols { protocol-id: protocol-id })) ) \ No newline at end of file From 681a2b1bdef7d203f87b631ce97345317c01e4e0 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:45:18 +0100 Subject: [PATCH 06/19] Add protocol management functions - Define public function to add a new protocol with validation checks - Add public function to update the status of an existing protocol --- contracts/btc-yielld-aggregator.clar | 36 ++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 600d18f..6ba4640 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -100,4 +100,40 @@ (define-private (protocol-exists (protocol-id uint)) (is-some (map-get? protocols { protocol-id: protocol-id })) +) + +;; Protocol Management Functions +(define-public (add-protocol (protocol-id uint) (name (string-ascii 64)) (initial-apy uint)) + (begin + (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) + (asserts! (is-valid-protocol-id protocol-id) ERR-INVALID-PROTOCOL-ID) + (asserts! (not (protocol-exists protocol-id)) ERR-PROTOCOL-EXISTS) + (asserts! (is-valid-name name) ERR-INVALID-NAME) + (asserts! (is-valid-apy initial-apy) ERR-INVALID-APY) + + (map-set protocols { protocol-id: protocol-id } + { + name: name, + active: PROTOCOL-ACTIVE, + apy: initial-apy + } + ) + (map-set strategy-allocations { protocol-id: protocol-id } { allocation: u0 }) + (ok true) + ) +) + +(define-public (update-protocol-status (protocol-id uint) (active bool)) + (begin + (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) + (asserts! (is-valid-protocol-id protocol-id) ERR-INVALID-PROTOCOL-ID) + (asserts! (protocol-exists protocol-id) ERR-INVALID-PROTOCOL-ID) + + (let ((protocol (unwrap-panic (get-protocol protocol-id)))) + (map-set protocols { protocol-id: protocol-id } + (merge protocol { active: active }) + ) + ) + (ok true) + ) ) \ No newline at end of file From 97aca5ee989a46af7eb7be3b319b17c242185615 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:45:50 +0100 Subject: [PATCH 07/19] Add function to update protocol APY - Define public function to update the APY of an existing protocol with validation checks --- contracts/btc-yielld-aggregator.clar | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 6ba4640..3dc441c 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -136,4 +136,20 @@ ) (ok true) ) +) + +(define-public (update-protocol-apy (protocol-id uint) (new-apy uint)) + (begin + (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) + (asserts! (is-valid-protocol-id protocol-id) ERR-INVALID-PROTOCOL-ID) + (asserts! (protocol-exists protocol-id) ERR-INVALID-PROTOCOL-ID) + (asserts! (is-valid-apy new-apy) ERR-INVALID-APY) + + (let ((protocol (unwrap-panic (get-protocol protocol-id)))) + (map-set protocols { protocol-id: protocol-id } + (merge protocol { apy: new-apy }) + ) + ) + (ok true) + ) ) \ No newline at end of file From 4bda43706a775f026d7b97a36dc9f6b295aecafd Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:46:59 +0100 Subject: [PATCH 08/19] Add token management function - Define private function to validate if a token implements the SIP-010 trait and is whitelisted --- contracts/btc-yielld-aggregator.clar | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 3dc441c..24787f0 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -152,4 +152,17 @@ ) (ok true) ) +) + +;; Token Management Functions +(define-private (validate-token (token-trait )) + (let + ( + (token-contract (contract-of token-trait)) + (token-info (map-get? whitelisted-tokens { token: token-contract })) + ) + (asserts! (is-some token-info) ERR-TOKEN-NOT-WHITELISTED) + (asserts! (get approved (unwrap-panic token-info)) ERR-PROTOCOL-NOT-WHITELISTED) + (ok true) + ) ) \ No newline at end of file From 604374b31f9f6721e74ac344be45ab93981153e3 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:47:41 +0100 Subject: [PATCH 09/19] Add deposit and withdrawal management functions - Define public function to handle deposits with validation checks and token transfer - Add public function to handle withdrawals with balance checks and token transfer --- contracts/btc-yielld-aggregator.clar | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 24787f0..3e843a8 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -165,4 +165,59 @@ (asserts! (get approved (unwrap-panic token-info)) ERR-PROTOCOL-NOT-WHITELISTED) (ok true) ) +) + +;; Deposit Management Functions +(define-public (deposit (token-trait ) (amount uint)) + (let + ( + (user-principal tx-sender) + (current-deposit (default-to { amount: u0, last-deposit-block: u0 } + (map-get? user-deposits { user: user-principal }))) + ) + (try! (validate-token token-trait)) + (asserts! (not (var-get emergency-shutdown)) ERR-STRATEGY-DISABLED) + (asserts! (>= amount (var-get min-deposit)) ERR-MIN-DEPOSIT-NOT-MET) + (asserts! (<= (+ amount (get amount current-deposit)) (var-get max-deposit)) ERR-MAX-DEPOSIT-REACHED) + + (try! (safe-token-transfer token-trait amount user-principal (as-contract tx-sender))) + + (map-set user-deposits + { user: user-principal } + { + amount: (+ amount (get amount current-deposit)), + last-deposit-block: block-height + }) + + (var-set total-tvl (+ (var-get total-tvl) amount)) + + (try! (rebalance-protocols)) + (ok true) + ) +) + +(define-public (withdraw (token-trait ) (amount uint)) + (let + ( + (user-principal tx-sender) + (current-deposit (default-to { amount: u0, last-deposit-block: u0 } + (map-get? user-deposits { user: user-principal }))) + ) + (try! (validate-token token-trait)) + (asserts! (<= amount (get amount current-deposit)) ERR-INSUFFICIENT-BALANCE) + + (map-set user-deposits + { user: user-principal } + { + amount: (- (get amount current-deposit) amount), + last-deposit-block: (get last-deposit-block current-deposit) + }) + + (var-set total-tvl (- (var-get total-tvl) amount)) + + (as-contract + (try! (safe-token-transfer token-trait amount tx-sender user-principal))) + + (ok true) + ) ) \ No newline at end of file From ea43fce6b306a06dfd9b131ffd7ce63dbb7a1f1f Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:48:24 +0100 Subject: [PATCH 10/19] Add token transfer helper function - Define private function to safely transfer tokens by validating the token and calling the transfer method --- contracts/btc-yielld-aggregator.clar | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 3e843a8..c00b742 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -220,4 +220,12 @@ (ok true) ) +) + +;; Token Transfer Helper +(define-private (safe-token-transfer (token-trait ) (amount uint) (sender principal) (recipient principal)) + (begin + (try! (validate-token token-trait)) + (contract-call? token-trait transfer amount sender recipient none) + ) ) \ No newline at end of file From 4018d943ce0779db54ef6057dc589b61bb97c557 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:50:20 +0100 Subject: [PATCH 11/19] Add reward management function - Define private function to calculate rewards based on user deposit, weighted APY, and number of blocks --- contracts/btc-yielld-aggregator.clar | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index c00b742..ff233c2 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -228,4 +228,15 @@ (try! (validate-token token-trait)) (contract-call? token-trait transfer amount sender recipient none) ) +) + +;; Reward Management Functions +(define-private (calculate-rewards (user principal) (blocks uint)) + (let + ( + (user-deposit (unwrap-panic (get-user-deposit user))) + (weighted-apy (get-weighted-apy)) + ) + (/ (* (get amount user-deposit) weighted-apy blocks) (* u10000 u144 u365)) + ) ) \ No newline at end of file From 3cf8e60375a313ff42574a736da0380bbb7cda9d Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:50:58 +0100 Subject: [PATCH 12/19] Add function to claim rewards - Define public function to claim rewards for the user by calculating rewards, validating the token, and transferring the rewards --- contracts/btc-yielld-aggregator.clar | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index ff233c2..a16ab36 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -239,4 +239,34 @@ ) (/ (* (get amount user-deposit) weighted-apy blocks) (* u10000 u144 u365)) ) +) + +(define-public (claim-rewards (token-trait )) + (let + ( + (user-principal tx-sender) + (rewards (calculate-rewards user-principal (- block-height + (get last-deposit-block (unwrap-panic (get-user-deposit user-principal)))))) + ) + (try! (validate-token token-trait)) + (asserts! (> rewards u0) ERR-INVALID-AMOUNT) + + (map-set user-rewards + { user: user-principal } + { + pending: u0, + claimed: (+ rewards + (get claimed (default-to { pending: u0, claimed: u0 } + (map-get? user-rewards { user: user-principal })))) + }) + + (as-contract + (try! (contract-call? token-trait transfer + rewards + tx-sender + user-principal + none))) + + (ok rewards) + ) ) \ No newline at end of file From 0a7da24f55abf67dcf82afd422236288b607b326 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:51:48 +0100 Subject: [PATCH 13/19] Add protocol optimization functions - Define private function to rebalance protocols by checking total allocations - Add private functions to calculate weighted APY and weighted APY for individual protocols --- contracts/btc-yielld-aggregator.clar | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index a16ab36..c67a3c1 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -269,4 +269,33 @@ (ok rewards) ) +) + +;; Protocol Optimization Functions +(define-private (rebalance-protocols) + (let + ( + (total-allocations (fold + (map get-protocol-allocation (get-protocol-list)) u0)) + ) + (asserts! (<= total-allocations u10000) ERR-INVALID-AMOUNT) + (ok true) + ) +) + +(define-private (get-weighted-apy) + (fold + (map get-weighted-protocol-apy (get-protocol-list)) u0) +) + +(define-private (get-weighted-protocol-apy (protocol-id uint)) + (let + ( + (protocol (unwrap-panic (get-protocol protocol-id))) + (allocation (get allocation (unwrap-panic + (map-get? strategy-allocations { protocol-id: protocol-id })))) + ) + (if (get active protocol) + (/ (* (get apy protocol) allocation) u10000) + u0 + ) + ) ) \ No newline at end of file From 4ba561b79e2feec8370c261a8d421e31fa57bd42 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:53:49 +0100 Subject: [PATCH 14/19] Add read-only functions - Define read-only functions to get protocol details, user deposit, total TVL, and check if a token is whitelisted --- contracts/btc-yielld-aggregator.clar | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index c67a3c1..3b777f7 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -298,4 +298,21 @@ u0 ) ) +) + +;; Read-Only Functions +(define-read-only (get-protocol (protocol-id uint)) + (map-get? protocols { protocol-id: protocol-id }) +) + +(define-read-only (get-user-deposit (user principal)) + (map-get? user-deposits { user: user }) +) + +(define-read-only (get-total-tvl) + (var-get total-tvl) +) + +(define-read-only (is-whitelisted (token )) + (default-to false (get approved (map-get? whitelisted-tokens { token: (contract-of token) }))) ) \ No newline at end of file From 686cc9ff0f369356684fccd710c2a549489d4582 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:54:28 +0100 Subject: [PATCH 15/19] Add administrative functions - Define public functions to set platform fee, toggle emergency shutdown, and whitelist tokens with authorization checks --- contracts/btc-yielld-aggregator.clar | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 3b777f7..5b33911 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -315,4 +315,30 @@ (define-read-only (is-whitelisted (token )) (default-to false (get approved (map-get? whitelisted-tokens { token: (contract-of token) }))) +) + +;; Administrative Functions +(define-public (set-platform-fee (new-fee uint)) + (begin + (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) + (asserts! (<= new-fee u1000) ERR-INVALID-AMOUNT) + (var-set platform-fee-rate new-fee) + (ok true) + ) +) + +(define-public (set-emergency-shutdown (shutdown bool)) + (begin + (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) + (var-set emergency-shutdown shutdown) + (ok true) + ) +) + +(define-public (whitelist-token (token principal)) + (begin + (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) + (map-set whitelisted-tokens { token: token } { approved: true }) + (ok true) + ) ) \ No newline at end of file From ea20cf22ebb7e60dff5538378fd3de3e7ee3612c Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 12:55:22 +0100 Subject: [PATCH 16/19] Add helper functions - Define private functions to get a list of protocol IDs and to get the allocation for a given protocol ID --- contracts/btc-yielld-aggregator.clar | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 5b33911..4a9576e 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -341,4 +341,14 @@ (map-set whitelisted-tokens { token: token } { approved: true }) (ok true) ) +) + +;; Helper Functions +(define-private (get-protocol-list) + (list u1 u2 u3 u4 u5) +) + +(define-private (get-protocol-allocation (protocol-id uint)) + (get allocation (default-to { allocation: u0 } + (map-get? strategy-allocations { protocol-id: protocol-id }))) ) \ No newline at end of file From 27b411344582d02b0feabe51edc076f04dd79352 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 13:53:50 +0100 Subject: [PATCH 17/19] Enhance Bitcoin Yield Aggregator with additional validation and security features - Add validation functions for protocol ID, APY, and name - Implement protocol management functions for adding and updating protocols - Include token management functions for validating and transferring tokens - Add deposit and withdrawal management functions with comprehensive checks - Implement reward management functions for calculating and claiming rewards - Add protocol optimization functions for rebalancing and calculating weighted APY - Include read-only functions for retrieving protocol details, user deposits, and TVL - Add administrative functions for setting platform fee, toggling emergency shutdown, and whitelisting tokens - Implement helper functions for protocol list and allocation retrieval --- contracts/btc-yielld-aggregator.clar | 210 +++++++++++++++++++++++---- 1 file changed, 178 insertions(+), 32 deletions(-) diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yielld-aggregator.clar index 4a9576e..ac45382 100644 --- a/contracts/btc-yielld-aggregator.clar +++ b/contracts/btc-yielld-aggregator.clar @@ -1,13 +1,23 @@ -;; Title: Bitcoin Yield Aggregator -;; Summary: A comprehensive DeFi yield strategy management system -;; Description: This contract enables users to deposit tokens into various yield-generating protocols, -;; manages protocol allocations, and distributes rewards. It includes features for protocol whitelisting, -;; emergency shutdown, and dynamic APY management with robust security measures. - -;; Constants +;; Bitcoin Yield Aggregator +;; +;; A secure and efficient DeFi yield strategy management system that enables users to: +;; - Deposit tokens into various yield-generating protocols +;; - Manage protocol allocations dynamically +;; - Earn and claim rewards based on protocol performance +;; - Benefit from automated strategy rebalancing +;; +;; Security Features: +;; - Protocol whitelisting +;; - Emergency shutdown mechanism +;; - Rate limiting +;; - Comprehensive input validation +;; - Balance verification +;; - SIP-010 compliance checks + +;; Principal Constants (define-constant contract-owner tx-sender) -;; Error Codes +;; Error Constants (define-constant ERR-NOT-AUTHORIZED (err u1000)) (define-constant ERR-INVALID-AMOUNT (err u1001)) (define-constant ERR-INSUFFICIENT-BALANCE (err u1002)) @@ -21,19 +31,25 @@ (define-constant ERR-INVALID-NAME (err u1010)) (define-constant ERR-INVALID-TOKEN (err u1011)) (define-constant ERR-TOKEN-NOT-WHITELISTED (err u1012)) - -;; Protocol Status Constants +(define-constant ERR-ZERO-AMOUNT (err u1013)) +(define-constant ERR-INVALID-USER (err u1014)) +(define-constant ERR-ALREADY-WHITELISTED (err u1015)) +(define-constant ERR-AMOUNT-TOO-LARGE (err u1016)) +(define-constant ERR-INVALID-STATE (err u1017)) +(define-constant ERR-RATE-LIMITED (err u1018)) + +;; Protocol Constants (define-constant PROTOCOL-ACTIVE true) (define-constant PROTOCOL-INACTIVE false) - -;; Protocol Configuration Constants (define-constant MAX-PROTOCOL-ID u100) -(define-constant MAX-APY u10000) ;; 100% APY in basis points +(define-constant MAX-APY u10000) (define-constant MIN-APY u0) +(define-constant MAX-TOKEN-TRANSFER u1000000000000) +(define-constant MIN-REQUIRED-RESPONSES u3) -;; Data Variables +;; State Variables (define-data-var total-tvl uint u0) -(define-data-var platform-fee-rate uint u100) ;; 1% (base 10000) +(define-data-var platform-fee-rate uint u100) (define-data-var min-deposit uint u100000) (define-data-var max-deposit uint u1000000000) (define-data-var emergency-shutdown bool false) @@ -59,6 +75,10 @@ { token: principal } { approved: bool }) +(define-map user-operations + { user: principal } + { last-operation: uint, count: uint }) + ;; SIP-010 Token Interface (define-trait sip-010-trait ( @@ -102,6 +122,28 @@ (is-some (map-get? protocols { protocol-id: protocol-id })) ) +(define-private (check-valid-amount (amount uint)) + (begin + (asserts! (> amount u0) ERR-ZERO-AMOUNT) + (asserts! (<= amount MAX-TOKEN-TRANSFER) ERR-AMOUNT-TOO-LARGE) + (ok amount) + ) +) + +(define-private (check-valid-user (user principal)) + (begin + (asserts! (not (is-eq user (as-contract tx-sender))) ERR-INVALID-USER) + (ok user) + ) +) + +(define-private (check-contract-state) + (begin + (asserts! (not (var-get emergency-shutdown)) ERR-STRATEGY-DISABLED) + (ok true) + ) +) + ;; Protocol Management Functions (define-public (add-protocol (protocol-id uint) (name (string-ascii 64)) (initial-apy uint)) (begin @@ -156,14 +198,28 @@ ;; Token Management Functions (define-private (validate-token (token-trait )) - (let + (let ( (token-contract (contract-of token-trait)) (token-info (map-get? whitelisted-tokens { token: token-contract })) ) (asserts! (is-some token-info) ERR-TOKEN-NOT-WHITELISTED) (asserts! (get approved (unwrap-panic token-info)) ERR-PROTOCOL-NOT-WHITELISTED) - (ok true) + + (let + ( + (name-response (try! (contract-call? token-trait get-name))) + (symbol-response (try! (contract-call? token-trait get-symbol))) + (decimals-response (try! (contract-call? token-trait get-decimals))) + ) + (asserts! (and + (> (len name-response) u0) + (> (len symbol-response) u0) + (>= decimals-response u0) + ) ERR-INVALID-TOKEN) + ) + + (ok token-contract) ) ) @@ -172,14 +228,22 @@ (let ( (user-principal tx-sender) - (current-deposit (default-to { amount: u0, last-deposit-block: u0 } + (current-deposit (default-to { amount: u0, last-deposit-block: u0 } (map-get? user-deposits { user: user-principal }))) ) - (try! (validate-token token-trait)) - (asserts! (not (var-get emergency-shutdown)) ERR-STRATEGY-DISABLED) + (try! (check-valid-amount amount)) + (try! (check-valid-user user-principal)) + (try! (validate-token-extended token-trait)) + (try! (check-rate-limit user-principal)) + (try! (check-contract-state)) + (asserts! (>= amount (var-get min-deposit)) ERR-MIN-DEPOSIT-NOT-MET) (asserts! (<= (+ amount (get amount current-deposit)) (var-get max-deposit)) ERR-MAX-DEPOSIT-REACHED) - + + (let ((user-balance (try! (contract-call? token-trait get-balance user-principal)))) + (asserts! (>= user-balance amount) ERR-INSUFFICIENT-BALANCE) + ) + (try! (safe-token-transfer token-trait amount user-principal (as-contract tx-sender))) (map-set user-deposits @@ -190,6 +254,7 @@ }) (var-set total-tvl (+ (var-get total-tvl) amount)) + (update-rate-limit user-principal) (try! (rebalance-protocols)) (ok true) @@ -203,9 +268,16 @@ (current-deposit (default-to { amount: u0, last-deposit-block: u0 } (map-get? user-deposits { user: user-principal }))) ) - (try! (validate-token token-trait)) + (try! (check-valid-amount amount)) + (try! (check-valid-user user-principal)) + (try! (validate-token-extended token-trait)) + (try! (check-rate-limit user-principal)) (asserts! (<= amount (get amount current-deposit)) ERR-INSUFFICIENT-BALANCE) - + + (let ((contract-balance (try! (contract-call? token-trait get-balance (as-contract tx-sender))))) + (asserts! (>= contract-balance amount) ERR-INSUFFICIENT-BALANCE) + ) + (map-set user-deposits { user: user-principal } { @@ -214,6 +286,7 @@ }) (var-set total-tvl (- (var-get total-tvl) amount)) + (update-rate-limit user-principal) (as-contract (try! (safe-token-transfer token-trait amount tx-sender user-principal))) @@ -225,7 +298,14 @@ ;; Token Transfer Helper (define-private (safe-token-transfer (token-trait ) (amount uint) (sender principal) (recipient principal)) (begin + (asserts! (not (var-get emergency-shutdown)) ERR-STRATEGY-DISABLED) + (try! (check-valid-amount amount)) + (try! (check-valid-user recipient)) (try! (validate-token token-trait)) + + (let ((sender-balance (unwrap-panic (contract-call? token-trait get-balance sender)))) + (asserts! (>= sender-balance amount) ERR-INSUFFICIENT-BALANCE) + ) (contract-call? token-trait transfer amount sender recipient none) ) ) @@ -248,9 +328,14 @@ (rewards (calculate-rewards user-principal (- block-height (get last-deposit-block (unwrap-panic (get-user-deposit user-principal)))))) ) - (try! (validate-token token-trait)) + (try! (validate-token-extended token-trait)) + (try! (check-rate-limit user-principal)) (asserts! (> rewards u0) ERR-INVALID-AMOUNT) + (let ((contract-balance (try! (contract-call? token-trait get-balance (as-contract tx-sender))))) + (asserts! (>= contract-balance rewards) ERR-INSUFFICIENT-BALANCE) + ) + (map-set user-rewards { user: user-principal } { @@ -260,12 +345,10 @@ (map-get? user-rewards { user: user-principal })))) }) + (update-rate-limit user-principal) + (as-contract - (try! (contract-call? token-trait transfer - rewards - tx-sender - user-principal - none))) + (try! (safe-token-transfer token-trait rewards tx-sender user-principal))) (ok rewards) ) @@ -330,16 +413,31 @@ (define-public (set-emergency-shutdown (shutdown bool)) (begin (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) + (asserts! (not (is-eq shutdown (var-get emergency-shutdown))) ERR-INVALID-STATE) + (print { event: "emergency-shutdown", status: shutdown }) (var-set emergency-shutdown shutdown) (ok true) ) ) -(define-public (whitelist-token (token principal)) +(define-public (whitelist-token (token )) (begin (asserts! (is-contract-owner) ERR-NOT-AUTHORIZED) - (map-set whitelisted-tokens { token: token } { approved: true }) - (ok true) + (let + ( + (token-contract (contract-of token)) + ) + (asserts! (not (is-whitelisted token)) ERR-ALREADY-WHITELISTED) + + (try! (contract-call? token get-name)) + (try! (contract-call? token get-symbol)) + (try! (contract-call? token get-decimals)) + (try! (contract-call? token get-total-supply)) + + (map-set whitelisted-tokens { token: token-contract } { approved: true }) + (print { event: "token-whitelisted", token: token-contract }) + (ok true) + ) ) ) @@ -351,4 +449,52 @@ (define-private (get-protocol-allocation (protocol-id uint)) (get allocation (default-to { allocation: u0 } (map-get? strategy-allocations { protocol-id: protocol-id }))) +) + +(define-private (check-rate-limit (user principal)) + (let ((user-ops (default-to { last-operation: u0, count: u0 } + (map-get? user-operations { user: user })))) + (asserts! (or + (> block-height (+ (get last-operation user-ops) u144)) + (< (get count user-ops) u10) + ) ERR-RATE-LIMITED) + (ok true) + ) +) + +(define-private (update-rate-limit (user principal)) + (let ((user-ops (default-to { last-operation: u0, count: u0 } + (map-get? user-operations { user: user })))) + (map-set user-operations + { user: user } + { + last-operation: block-height, + count: (if (> block-height (+ (get last-operation user-ops) u144)) + u1 + (+ (get count user-ops) u1)) + } + ) + ) +) + +(define-private (validate-token-extended (token-trait )) + (let + ( + (token-contract (contract-of token-trait)) + (token-info (map-get? whitelisted-tokens { token: token-contract })) + ) + (try! (validate-token token-trait)) + + (asserts! (not (is-eq token-contract (as-contract tx-sender))) ERR-INVALID-TOKEN) + + (let ((total-supply (try! (contract-call? token-trait get-total-supply)))) + (asserts! (> total-supply u0) ERR-INVALID-TOKEN) + ) + + (let ((decimals (try! (contract-call? token-trait get-decimals)))) + (asserts! (and (>= decimals u6) (<= decimals u18)) ERR-INVALID-TOKEN) + ) + + (ok token-contract) + ) ) \ No newline at end of file From c0701ba05d239f6a6bfcd102448c52c85408cf14 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 14:06:00 +0100 Subject: [PATCH 18/19] Fix typo in Bitcoin Yield Aggregator contract path --- Clarinet.toml | 4 ++-- .../{btc-yielld-aggregator.clar => btc-yield-aggregator.clar} | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename contracts/{btc-yielld-aggregator.clar => btc-yield-aggregator.clar} (100%) diff --git a/Clarinet.toml b/Clarinet.toml index b7b2505..69a0789 100644 --- a/Clarinet.toml +++ b/Clarinet.toml @@ -4,8 +4,8 @@ authors = [] description = "" telemetry = true requirements = [] -[contracts.btc-yielld-aggregator] -path = "contracts/btc-yielld-aggregator.clar" +[contracts.btc-yield-aggregator] +path = "contracts/btc-yield-aggregator.clar" depends_on = [] [repl] diff --git a/contracts/btc-yielld-aggregator.clar b/contracts/btc-yield-aggregator.clar similarity index 100% rename from contracts/btc-yielld-aggregator.clar rename to contracts/btc-yield-aggregator.clar From b20c37c2b68267923bdcf4b33a538c8509b84948 Mon Sep 17 00:00:00 2001 From: david-cmd-byte Date: Sun, 29 Dec 2024 14:08:45 +0100 Subject: [PATCH 19/19] Add Code of Conduct, Contributing Guidelines, License, Security Policy, and Technical Specification documents --- CODE_OF_CONDUCT.md | 35 ++++++++++ CONTRIBUTING.md | 55 ++++++++++++++++ LICENSE | 20 ++++++ README.md | 88 +++++++++++++++++++++++++ SECURITY.md | 44 +++++++++++++ docs/technical-specification.md | 112 ++++++++++++++++++++++++++++++++ 6 files changed, 354 insertions(+) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 docs/technical-specification.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..63fd76d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,35 @@ +# Code of Conduct + +## Our Pledge + +We pledge to make participation in our project and community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information without explicit permission +- Other conduct which could reasonably be considered inappropriate + +## Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project team. All complaints will be reviewed and investigated promptly and fairly. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0848430 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing Guidelines + +Thank you for considering contributing to the Bitcoin Yield Aggregator! + +## How to Contribute + +1. Fork the repository +2. Create a feature branch +3. Commit your changes +4. Push to your branch +5. Open a Pull Request + +## Development Process + +### Smart Contract Development + +1. Follow Clarity best practices +2. Maintain comprehensive test coverage +3. Document all functions and state changes +4. Verify security considerations + +### Testing + +- Write unit tests for all functions +- Include integration tests +- Test edge cases and failure scenarios +- Verify gas optimization + +### Documentation + +- Update technical documentation +- Add inline code comments +- Update README if needed +- Document breaking changes + +## Pull Request Process + +1. Update documentation +2. Add tests for new features +3. Ensure CI passes +4. Get review from maintainers +5. Address feedback + +## Security + +- Report security issues privately +- Follow responsible disclosure +- See SECURITY.md for details + +## Code Style + +- Follow Clarity style guide +- Use meaningful variable names +- Keep functions focused and small +- Add appropriate error handling diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6fde465 --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2024 David Akuma +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7cb7dd5 --- /dev/null +++ b/README.md @@ -0,0 +1,88 @@ +# Bitcoin Yield Aggregator + +A secure and efficient DeFi yield strategy management system built on Bitcoin using Clarity smart contracts. + +## Overview + +The Bitcoin Yield Aggregator enables users to: + +- Deposit tokens into various yield-generating protocols +- Manage protocol allocations dynamically +- Earn and claim rewards based on protocol performance +- Benefit from automated strategy rebalancing + +## Key Features + +- **Protocol Management**: Add, update, and manage yield-generating protocols +- **Token Integration**: SIP-010 compliant token support with whitelisting +- **Secure Deposits**: Rate-limited deposits with comprehensive validation +- **Dynamic Rewards**: APY-based reward calculation and distribution +- **Emergency Controls**: Emergency shutdown mechanism for risk management +- **Rate Limiting**: Protection against abuse through operation rate limiting + +## Security Features + +- Protocol whitelisting +- Emergency shutdown mechanism +- Rate limiting +- Comprehensive input validation +- Balance verification +- SIP-010 compliance checks + +## Getting Started + +### Prerequisites + +- Stacks blockchain environment +- SIP-010 compliant tokens +- Clarity smart contract knowledge + +### Contract Deployment + +1. Deploy the contract to the Stacks blockchain +2. Set initial parameters (platform fee, deposit limits) +3. Whitelist supported tokens +4. Add yield-generating protocols + +### Usage + +```clarity +;; Deposit tokens +(contract-call? .yield-aggregator deposit token-trait amount) + +;; Withdraw tokens +(contract-call? .yield-aggregator withdraw token-trait amount) + +;; Claim rewards +(contract-call? .yield-aggregator claim-rewards token-trait) +``` + +## Architecture + +The contract is structured into several key components: + +- Protocol Management +- Token Management +- Deposit/Withdrawal Handling +- Reward Distribution +- Administrative Controls + +## Technical Documentation + +For detailed technical specifications, see [Technical Specification](docs/technical-specification.md) + +## Security + +See [SECURITY.md](SECURITY.md) for security policies and procedures. + +## Contributing + +Please read [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines. + +## License + +This project is licensed under the MIT License - see [LICENSE](LICENSE) for details. + +## Code of Conduct + +Please read our [Code of Conduct](CODE_OF_CONDUCT.md) for community guidelines. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..19c0250 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,44 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 1.0.x | :white_check_mark: | + +## Reporting a Vulnerability + +1. **Do Not** file a public issue +2. Email davidakuma30@gmail.com + +3. Include detailed description +4. We will respond within 48 hours +5. Please allow time for fix before disclosure + +## Security Measures + +- Regular security audits +- Comprehensive testing +- Rate limiting +- Input validation +- Balance verification +- Emergency shutdown mechanism + +## Best Practices + +- Use whitelisted tokens only +- Monitor transaction limits +- Verify contract state +- Check return values +- Validate inputs + +## Emergency Procedures + +In case of critical vulnerabilities: + +1. Emergency shutdown activated +2. All operations suspended +3. Funds secured +4. Issue investigated +5. Fix implemented +6. System gradually restored diff --git a/docs/technical-specification.md b/docs/technical-specification.md new file mode 100644 index 0000000..f1fca78 --- /dev/null +++ b/docs/technical-specification.md @@ -0,0 +1,112 @@ +# Technical Specification + +## Contract Overview + +The Bitcoin Yield Aggregator is a DeFi protocol for managing yield-generating strategies on Bitcoin using Clarity smart contracts. + +## Core Components + +### State Management + +```clarity +;; TVL and Platform Parameters +(define-data-var total-tvl uint u0) +(define-data-var platform-fee-rate uint u100) +(define-data-var min-deposit uint u100000) +(define-data-var max-deposit uint u1000000000) +(define-data-var emergency-shutdown bool false) +``` + +### Data Structures + +```clarity +;; User Deposits +(define-map user-deposits + { user: principal } + { amount: uint, last-deposit-block: uint }) + +;; Protocol Configuration +(define-map protocols + { protocol-id: uint } + { name: (string-ascii 64), active: bool, apy: uint }) +``` + +## Key Functions + +### Deposit Management + +- `deposit`: Process user deposits +- `withdraw`: Handle withdrawals +- `safe-token-transfer`: Secure token transfers + +### Reward System + +- `calculate-rewards`: Compute user rewards +- `claim-rewards`: Process reward claims +- `get-weighted-apy`: Calculate effective APY + +### Protocol Management + +- `add-protocol`: Add new protocols +- `update-protocol-status`: Manage protocol state +- `update-protocol-apy`: Update yield rates + +## Security Features + +### Rate Limiting + +- Maximum 10 operations per 144 blocks +- Cooldown period enforcement +- Operation counting + +### Input Validation + +- Amount bounds checking +- Protocol ID validation +- Token compliance verification + +### Balance Verification + +- User balance checks +- Contract balance verification +- TVL monitoring + +## Error Handling + +### Error Codes + +```clarity +(define-constant ERR-NOT-AUTHORIZED (err u1000)) +(define-constant ERR-INVALID-AMOUNT (err u1001)) +;; ... additional error codes +``` + +## Integration Guide + +### Token Requirements + +- SIP-010 compliance +- Minimum 6 decimals +- Maximum 18 decimals +- Non-zero total supply + +### Protocol Integration + +1. Protocol whitelisting +2. APY configuration +3. Allocation setup +4. Status management + +## Performance Considerations + +### Gas Optimization + +- Efficient data structures +- Minimal state changes +- Optimized calculations + +### Scalability + +- Rate limiting design +- Balance thresholds +- Protocol limits