├── contracts ├── __init__.py ├── amm │ ├── __init__.py │ ├── constants.py │ ├── contract_strings.py │ ├── amm.md │ ├── stable_pool.py │ ├── subroutines.py │ ├── moving_ratio_stable_pool.py │ ├── stable_swap_math.py │ └── manager.py ├── utils │ ├── __init__.py │ ├── permissionless_sender_logic_sig.py │ ├── factory_logic_sig.py │ ├── constants.py │ └── wrapped_var.py ├── governance │ ├── __init__.py │ ├── constants.py │ ├── contract_strings.py │ ├── proposal.py │ ├── governance.md │ ├── subroutines.py │ ├── proposal_factory.py │ └── voting_escrow.py └── v2_staking │ ├── __init__.py │ ├── constants.py │ ├── contract_strings.py │ ├── staking.md │ ├── subroutines.py │ └── staking_contract.py ├── algofi-audits ├── README.md ├── dex │ ├── NCC_Group_Algofi_AMM_Nanoswap_March_2022.pdf │ ├── NCC_Group_Algofi_AMM_Summary_February_2022.pdf │ ├── Runtime_Verification_Algofi_AMM_February_2022.pdf │ └── Runtime_Verification_Algofi_AMM_NanoSwap_March_2022.pdf ├── lending_v1 │ ├── Coinspect_Algofi_Vault_March_2022.pdf │ └── Runtime_Verification_Algofi_Lending_December_2021.pdf ├── governance │ └── Certik_Algofi_Governance_September_2022.pdf └── lending_v2 │ └── Runtime_Verification_Algofi_Lending_V2_July_2022.pdf ├── .flake8 ├── requirements.txt ├── pyproject.toml ├── .isort.cfg ├── README.md ├── .gitignore └── LICENSE /contracts/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /contracts/amm/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /contracts/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /contracts/governance/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /contracts/v2_staking/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algofi-audits/README.md: -------------------------------------------------------------------------------- 1 | # audits 2 | Audit reports for the protocol -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E501, W503, E203, F541, W293, W291, F405, F403 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | py-algorand-sdk==1.18.0 2 | pyteal==0.18.1 3 | black==23.7.0 -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["poetry-core", "setuptools", "wheel"] 3 | 4 | 5 | [tool.black] 6 | line-length = 79 -------------------------------------------------------------------------------- /algofi-audits/dex/NCC_Group_Algofi_AMM_Nanoswap_March_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/dex/NCC_Group_Algofi_AMM_Nanoswap_March_2022.pdf -------------------------------------------------------------------------------- /algofi-audits/lending_v1/Coinspect_Algofi_Vault_March_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/lending_v1/Coinspect_Algofi_Vault_March_2022.pdf -------------------------------------------------------------------------------- /algofi-audits/dex/NCC_Group_Algofi_AMM_Summary_February_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/dex/NCC_Group_Algofi_AMM_Summary_February_2022.pdf -------------------------------------------------------------------------------- /algofi-audits/dex/Runtime_Verification_Algofi_AMM_February_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/dex/Runtime_Verification_Algofi_AMM_February_2022.pdf -------------------------------------------------------------------------------- /algofi-audits/governance/Certik_Algofi_Governance_September_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/governance/Certik_Algofi_Governance_September_2022.pdf -------------------------------------------------------------------------------- /algofi-audits/dex/Runtime_Verification_Algofi_AMM_NanoSwap_March_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/dex/Runtime_Verification_Algofi_AMM_NanoSwap_March_2022.pdf -------------------------------------------------------------------------------- /algofi-audits/lending_v1/Runtime_Verification_Algofi_Lending_December_2021.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/lending_v1/Runtime_Verification_Algofi_Lending_December_2021.pdf -------------------------------------------------------------------------------- /algofi-audits/lending_v2/Runtime_Verification_Algofi_Lending_V2_July_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algofiorg/smart-contracts/HEAD/algofi-audits/lending_v2/Runtime_Verification_Algofi_Lending_V2_July_2022.pdf -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | profile = black 3 | multi_line_output = 3 4 | include_trailing_comma = true 5 | force_grid_wrap = 0 6 | use_parentheses = true 7 | ensure_newline_before_comments = true 8 | line_length = 79 9 | sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER 10 | skip = .tox,__pycache__,*.pyc,venv*/*,reports,venv,env,node_modules,.env,.venv,dist -------------------------------------------------------------------------------- /contracts/v2_staking/constants.py: -------------------------------------------------------------------------------- 1 | """Constants for the staking contracts""" 2 | from pyteal import * 3 | 4 | from contracts.utils.constants import * 5 | 6 | # DEV MODE FLAG 7 | DEV_MODE = False 8 | 9 | 10 | class StakingScratchSlots: 11 | rewards_program_index = 0 12 | amount_staked = 1 13 | 14 | rewards_to_issue = 10 15 | rewards_available = 11 16 | -------------------------------------------------------------------------------- /contracts/utils/permissionless_sender_logic_sig.py: -------------------------------------------------------------------------------- 1 | """A permissionless sender logic sig.""" 2 | 3 | from pyteal import * 4 | 5 | 6 | class PermissionlessSender: 7 | def approval_program(self): 8 | return Seq( 9 | [ 10 | Assert(Txn.type_enum() == TxnType.ApplicationCall), 11 | Assert(Txn.on_completion() == OnComplete.NoOp), 12 | Assert(Txn.close_remainder_to() == Global.zero_address()), 13 | Assert(Txn.rekey_to() == Global.zero_address()), 14 | Approve(), 15 | ] 16 | ) 17 | -------------------------------------------------------------------------------- /contracts/governance/constants.py: -------------------------------------------------------------------------------- 1 | """Defines constants used in the governance contracts.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.utils.constants import * 6 | 7 | # DEV MODE FLAG 8 | DEV_MODE = True 9 | 10 | # LOCK TIME CONSTANTS 11 | MIN_LOCK_TIME_SECONDS = Int(30 if DEV_MODE else 60 * 60 * 24 * 7) 12 | MAX_LOCK_TIME_SECONDS = Int(600 if DEV_MODE else 60 * 60 * 24 * 365 * 4) 13 | 14 | # GOVERNANCE CONSTANTS 15 | MIN_BALANCE_PROPOSAL = Int(606500) 16 | PROPOSAL_CREATION_DELAY = Int(0) 17 | 18 | # CONTRACT SCHEMAS 19 | GLOBAL_BYTES_PROPOSAL_CONTRACT = Int(14) 20 | GLOBAL_INTS_PROPOSAL_CONTRACT = Int(14) 21 | LOCAL_BYTES_PROPOSAL_CONTRACT = Int(0) 22 | LOCAL_INTS_PROPOSAL_CONTRACT = Int(2) 23 | 24 | 25 | # SCRATCH SLOTS 26 | class AdminContractScratchSlots: 27 | """A class containing scratch slots for the admin contract.""" 28 | 29 | delegatee_storage_address = 0 30 | proposal_app_id = 1 31 | min_balance = 2 32 | closeout_user_address = 3 33 | 34 | 35 | class ProposalFactoryScratchSlots: 36 | """A class containing scratch slots for the proposal factory contract.""" 37 | 38 | min_balance = 0 39 | -------------------------------------------------------------------------------- /contracts/utils/factory_logic_sig.py: -------------------------------------------------------------------------------- 1 | """Logic sig to register a pool with the manager""" 2 | 3 | from pyteal import * 4 | 5 | 6 | class PoolFactoryLogicSig: 7 | def __init__( 8 | self, manager_app_id, asset_1_id, asset_2_id, pool_validator_index 9 | ): 10 | self.manager_app_id = Int(manager_app_id) 11 | self.asset_1_id = Int(asset_1_id) 12 | self.asset_2_id = Int(asset_2_id) 13 | self.pool_validator_index = Int(pool_validator_index) 14 | 15 | """ 16 | Verify that the only transaction permitted from this logic sig address is 17 | an opt in call to the designated manager with the expected application args 18 | and no rekey 19 | """ 20 | 21 | def approval_program(self): 22 | return Seq( 23 | [ 24 | Assert(self.asset_1_id < self.asset_2_id), 25 | Assert(Txn.type_enum() == TxnType.ApplicationCall), 26 | Assert(Txn.on_completion() == OnComplete.OptIn), 27 | Assert(Txn.application_id() == self.manager_app_id), 28 | Assert(Btoi(Txn.application_args[0]) == self.asset_1_id), 29 | Assert(Btoi(Txn.application_args[1]) == self.asset_2_id), 30 | Assert( 31 | Btoi(Txn.application_args[2]) == self.pool_validator_index 32 | ), 33 | Assert(Txn.rekey_to() == Global.zero_address()), 34 | Int(1), 35 | ] 36 | ) 37 | -------------------------------------------------------------------------------- /contracts/utils/constants.py: -------------------------------------------------------------------------------- 1 | """Utility constants""" 2 | 3 | from pyteal import * 4 | 5 | # CONSTANTS 6 | TRUE = Int(1) 7 | FALSE = Int(0) 8 | SECONDS_PER_YEAR = Int(365 * 24 * 60 * 60) 9 | BYTES_ZERO = BytesZero(Int(64)) 10 | ZERO_FEE = Int(0) 11 | ZERO_AMOUNT = Int(0) 12 | MAX_INT_U64 = Int(2**64 - 1) 13 | 14 | # SCALE FACTORS 15 | FIXED_18_SCALE_FACTOR = Int(1_000_000_000_000_000_000) 16 | FIXED_15_SCALE_FACTOR = Int(1_000_000_000_000_000) 17 | FIXED_12_SCALE_FACTOR = Int(1_000_000_000_000) 18 | FIXED_9_SCALE_FACTOR = Int(1_000_000_000) 19 | FIXED_6_SCALE_FACTOR = Int(1_000_000) 20 | FIXED_3_SCALE_FACTOR = Int(1_000) 21 | 22 | # ASSET PARAMS 23 | ALGO_ASSET_ID = Int(1) 24 | LP_DECIMALS = Int(6) 25 | MAX_CIRCULATION = Int(2**64 - 1) 26 | B_ASSET_DECIMALS = Int(6) 27 | URL = Bytes("") 28 | 29 | 30 | # TXN INDICES 31 | def relative_index(offset): 32 | if offset > 0: 33 | return Txn.group_index() + Int(offset) 34 | else: 35 | return Txn.group_index() - Int(abs(offset)) 36 | 37 | 38 | FIRST_TRANSACTION = Int(0) 39 | TWO_PREVIOUS_TRANSACTION = relative_index(-2) 40 | PREVIOUS_TRANSACTION = relative_index(-1) 41 | NEXT_TRANSACTION = relative_index(1) 42 | TWO_SUBSEQUENT_TRANSACTION = relative_index(2) 43 | FINAL_TRANSACTION = Global.group_size() - Int(1) 44 | 45 | # TIME CONSTANTS 46 | UNSET_TIME = Int(0) 47 | UNSET_INT = Int(0) 48 | UNSET = Int(0) 49 | UNSET_BYTES = BytesZero(Int(64)) 50 | ZERO_FEE = Int(0) 51 | ZERO_AMOUNT = Int(0) 52 | MAX_INT_U64 = Int(2**64 - 1) 53 | -------------------------------------------------------------------------------- /contracts/v2_staking/contract_strings.py: -------------------------------------------------------------------------------- 1 | """Strings for the staking contract.""" "" 2 | 3 | 4 | class StakingStrings: 5 | """A class containing strings for the staking contract.""" 6 | 7 | asset_id = "ai" 8 | boost_multiplier = "lm" 9 | boost_multiplier_app_id = "bmai" 10 | claim_rewards = "cr" 11 | dao_address = "da" 12 | emergency_dao_address = "eda" 13 | external_boost_multiplier = "bm" 14 | farm_ops = "fo" 15 | initialize_rewards_escrow_account = "irea" 16 | latest_time = "lt" 17 | opt_into_asset = "oia" 18 | reclaim_rewards_assets = "rra" 19 | rewards_asset_id_prefix = "rai_" 20 | rewards_coefficient_prefix = "rc_" 21 | rewards_escrow_account = "rea" 22 | rewards_issued_prefix = "ri_" 23 | rewards_paid_prefix = "rp_" 24 | rewards_per_second_prefix = "rps_" 25 | rewards_program_count = "rpc" 26 | rewards_program_counter_prefix = "rpc_" 27 | rps_pusher = "rpsp" 28 | scaled_total_staked = "sts" 29 | set_rewards_program = "srp" 30 | set_rps_pusher = "srpsp" 31 | set_voting_escrow_app_id = "sveai" 32 | stake = "s" 33 | total_staked = "ts" 34 | units_staked = "us" 35 | unstake = "u" 36 | update_boost_multiplier = "ulm" 37 | update_rewards_per_second = "urps" 38 | update_target_user = "utu" 39 | user_rewards_coefficient_prefix = "urc_" 40 | user_rewards_program_counter_prefix = "urpc_" 41 | user_scaled_total_staked = "usts" 42 | user_total_staked = "uts" 43 | user_unclaimed_rewards_prefix = "uur_" 44 | voting_escrow_app_id = "veai" 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Smart Contracts 2 | 3 | Featured is a comprehensive decentralized application ecosystem built on the Algorand blockchain. It leverages Algorand Smart Contracts (ASC1), using PyTeal, a Python language binding for ASC1. The project consists of several key modules, each handling a specific function within the ecosystem: 4 | 5 | ## Automated Market Maker (AMM) 6 | 7 | The AMM module employs an approval program that approves transactions and updates to the AMM pool. It handles various operations related to pool, burn, swap, and flash loan operations. AMM also includes StableSwap modifications to maintain the stability of asset values within the pool. You can read more about the AMM module in the [documentation](contracts/amm/amm.md). 8 | 9 | ## Governance 10 | 11 | The Governance module is a decentralized protocol for creating, voting on, and executing proposals. It includes a `ProposalFactory` for creating new proposals and a `Proposal` class that represents an individual proposal. The logic within these classes orchestrates the creation and voting process on the proposals, managing the opt-in process, voting, delegation, validation, and close-out processes. Detailed information about the Governance module can be found in the [documentation](contracts/governance/governance.md). 12 | 13 | ## Staking Protocol 14 | 15 | The Staking Protocol module offers a mechanism for users to stake and unstake assets and claim rewards. The `StakingContract` class manages the core staking functions and handles the rewards program for the contract. The logic in this class governs the flow of transactions and updates, based on the state of the contract and the type of operation being performed. More details about the Staking Protocol can be found in the [documentation](contracts/v2_staking/staking.md). -------------------------------------------------------------------------------- /contracts/amm/constants.py: -------------------------------------------------------------------------------- 1 | """Constants for AMM.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.utils.constants import * 6 | 7 | # POOL SCHEMA 8 | POOL_GLOBAL_NUM_BYTES = Int(4) 9 | POOL_GLOBAL_NUM_UINTS = Int(32) 10 | 11 | # INTIALIZATION GROUP TXN INDICES 12 | N_FUND_MANAGER_TXN = 0 13 | N_FUND_LOGIC_SIG_TXN = 1 14 | N_OPT_IN_LOGIC_SIG_TXN = 2 15 | N_INITIALIZE_POOL_TXN = 3 16 | 17 | # MANAGER PARAMS 18 | MAX_VALIDATOR_COUNT = Int(8) 19 | DEFAULT_RESERVE_FACTOR = Int(175000) 20 | 21 | # POOL PARAMS 22 | MAX_ASSET_RATIO = Int(1000000000) 23 | DEFAULT_SWAP_FEE_PCT_SCALED = Int(2500) 24 | MIN_POOL_BALANCE = Int(1000) 25 | DEFAULT_PARAM_UPDATE_DELAY = Int(5) 26 | MAX_AMPLIFICATION_FACTOR = Int(400_000_000) 27 | 28 | # STABLE POOL PARAMS 29 | DEFAULT_STABLESWAP_FEE_PCT_SCALED = Int(1000) 30 | 31 | # ADMIN PARAMS 32 | INIT_FLASH_LOAN_FEE = Int(1000) 33 | INIT_MAX_FLASH_LOAN_RATIO = Int(100000) 34 | 35 | 36 | # POOL TRANSACTION INDICES 37 | def relative_index(offset): 38 | if offset > 0: 39 | return Txn.group_index() + Int(offset) 40 | else: 41 | return Txn.group_index() - Int(abs(offset)) 42 | 43 | 44 | # POOL 45 | # 1 - asset1 in 46 | # 2 - asset2 in 47 | # 3 - pool 48 | # 4 - redeem asset1 residual 49 | # 5 - redeem asset2 residual 50 | POOL__ASSET1_IN_IDX = relative_index(-2) 51 | POOL__ASSET2_IN_IDX = relative_index(-1) 52 | POOL__REDEEM_POOL_ASSET1_RESIDUAL_IDX = relative_index(1) 53 | POOL__REDEEM_POOL_ASSET2_RESIDUAL_IDX = relative_index(2) 54 | 55 | # POOL Redeem 56 | REDEEM_POOL_ASSET1_RESIDUAL__POOL_IDX = relative_index(-1) 57 | 58 | REDEEM_POOL_ASSET2_RESIDUAL__POOL_IDX = relative_index(-2) 59 | 60 | # BURN 61 | # 1 - lp in 62 | # 2 - burn asset 1 out 63 | # 3 - burn asset 2 out 64 | BURN_ASSET1_OUT__LP_IN_IDX = relative_index(-1) 65 | BURN_ASSET1_OUT__BURN_ASSET2_OUT_IDX = relative_index(1) 66 | 67 | BURN_ASSET2_OUT__LP_IN_IDX = relative_index(-2) 68 | BURN_ASSET2_OUT__BURN_ASSET1_OUT_IDX = relative_index(-1) 69 | 70 | # SWAP 71 | # 1 - asset in 72 | # 2 - swap 73 | # 3 - redeem residual (swap_for_exact only) 74 | SWAP__SWAP_IN_IDX = relative_index(-1) 75 | SWAP__REDEEM_SWAP_RESIDUAL_IDX = relative_index(1) 76 | 77 | # SWAP Redeem 78 | REDEEM_SWAP_RESIDUAL__SWAP_IDX = relative_index(-1) 79 | 80 | # FLASH LOAN 81 | # 1 - flash loan 82 | # ... 83 | # FINAL - flash loan repay txn 84 | FLASH_LOAN_IDX = Int(0) 85 | FLASH_LOAN_REPAY_IDX = Global.group_size() - Int(1) 86 | -------------------------------------------------------------------------------- /contracts/amm/contract_strings.py: -------------------------------------------------------------------------------- 1 | """Defines the contract strings for the AMM contracts.""" 2 | 3 | 4 | class AMMPoolStrings: 5 | """AMM Pool contract strings.""" 6 | 7 | admin = "a" 8 | asset1_id = "a1" 9 | asset1_reserve = "a1r" 10 | asset2_id = "a2" 11 | asset2_reserve = "a2r" 12 | asset_1_to_asset_2_exchange = "e" 13 | balance_1 = "b1" 14 | balance_2 = "b2" 15 | burn_asset1_out = "ba1o" 16 | burn_asset2_out = "ba2o" 17 | cumsum_fees_asset1 = "cf1" 18 | cumsum_fees_asset2 = "cf2" 19 | cumsum_time_weighted_asset1_to_asset2_price = "ct12" 20 | cumsum_time_weighted_asset2_to_asset1_price = "ct21" 21 | cumsum_volume_asset1 = "cv1" 22 | cumsum_volume_asset2 = "cv2" 23 | cumsum_volume_weighted_asset1_to_asset2_price = "cv12" 24 | cumsum_volume_weighted_asset2_to_asset1_price = "cv21" 25 | flash_loan = "fl" 26 | flash_loan_fee = "flf" 27 | future_amplification_factor = "faf" 28 | future_amplification_factor_time = "fat" 29 | increase_param_update_delay = "ipu" 30 | initial_amplification_factor = "iaf" 31 | initial_amplification_factor_time = "iat" 32 | initialize_pool = "ip" 33 | initialized = "i" 34 | latest_time = "lt" 35 | lp_circulation = "lc" 36 | lp_id = "l" 37 | manager = "m" 38 | manager_app_id_var = "ma" 39 | max_flash_loan_ratio = "mflr" 40 | next_swap_fee_pct_scaled = "nsfp" 41 | opt_into_assets = "o" 42 | param_update_delay = "pu" 43 | pool = "p" 44 | ramp_amplification_factor = "raf" 45 | redeem_pool_asset1_residual = "rpa1r" 46 | redeem_pool_asset2_residual = "rpa2r" 47 | redeem_swap_residual = "rsr" 48 | remove_reserves = "rr" 49 | reserve_factor = "rf" 50 | schedule_swap_fee_update = "ssf" 51 | swap_exact_for = "sef" 52 | swap_fee_pct_scaled_var = "sfp" 53 | swap_fee_update_time = "sft" 54 | swap_for_exact = "sfe" 55 | update_swap_fee = "usf" 56 | validator_index = "vi" 57 | 58 | 59 | class AMMManagerStrings: 60 | """AMM Manager contract strings.""" 61 | 62 | admin = "a" 63 | farm_ops = "fo" 64 | flash_loan_fee = "flf" 65 | initialize_pool = "ip" 66 | max_flash_loan_ratio = "mflr" 67 | pool_hash_prefix = "ph_" 68 | registered_asset_1_id = "a1" 69 | registered_asset_2_id = "a2" 70 | registered_pool_id = "p" 71 | reserve_factor = "rf" 72 | set_flash_loan_fee = "sflf" 73 | set_max_flash_loan_ratio = "smflr" 74 | set_reserve_factor = "srf" 75 | set_validator = "sv" 76 | validator_index = "vi" 77 | -------------------------------------------------------------------------------- /contracts/v2_staking/staking.md: -------------------------------------------------------------------------------- 1 | # README.md 2 | 3 | ## Overview 4 | 5 | The provided code forms part of a decentralized staking protocol built on the Algorand blockchain. This protocol employs Algorand Smart Contracts (ASC1) written in PyTeal, a Python language binding for ASC1. The staking protocol involves mechanisms for creating, maintaining, and interacting with various staking contracts, each representing a different asset. 6 | 7 | This staking protocol supports standard staking contracts, where users can stake and unstake volatile assets, and claim rewards. The staking contracts have administrative functions to update staking parameters and manage the contract, alongside user functions to stake, unstake, and claim rewards. 8 | 9 | The code for this decentralized staking protocol is primarily contained within the `StakingContract` class. 10 | 11 | ## `StakingContract` Class 12 | 13 | The `StakingContract` class represents a staking contract within the protocol. It handles the core staking functions such as stake and unstake operations, claiming of rewards, updating staking parameters, and managing the rewards program. 14 | 15 | The `StakingContract` class also manages the rewards program for the contract, allowing users to earn rewards by participating in the staking activities. 16 | 17 | ## `StakingContract` Logic 18 | 19 | The logic in the `StakingContract` class governs the functioning of the protocol. It dictates the conditional flow of transactions and updates, based on the state of the contract and the type of operation being performed. 20 | 21 | In the `StakingContract` class, the logic handles operations such as setting the DAO address, initializing the rewards escrow account, setting the voting escrow application ID, setting the rewards program, updating rewards per second, opting into an asset, reclaiming rewards assets, handling a variety of staking transactions such as stake, unstake, claim rewards, and user functions including opt-in and close-out processes. 22 | 23 | ## Staking Contract Operations 24 | 25 | The staking contract operations are designed to incentivize users to participate in the protocol. The protocol automatically handles the distribution of rewards to active users based on their staked assets. 26 | 27 | Users can interact with the protocol in various ways. They can stake assets to earn rewards, unstake assets, and claim their rewards. The protocol also provides users with the ability to opt in and opt out of the staking contract, which gives them flexibility in participating in the protocol. 28 | 29 | In the staking contract, the rewards per second is a key parameter that affects the overall staking and reward distribution dynamics. The protocol allows the admin to set this rate, providing a mechanism to manage the rewards distribution in the staking contract. 30 | 31 | ## Further Information 32 | 33 | For more information on decentralized staking protocols, Algorand Smart Contracts, and PyTeal, refer to the following resources: 34 | 35 | - [What is Staking?](https://www.coinbase.com/learn/crypto-basics/what-is-staking) 36 | - [Algorand Smart Contracts](https://developer.algorand.org/docs/features/asc1/) 37 | - [PyTeal Documentation](https://pyteal.readthedocs.io/en/latest/) -------------------------------------------------------------------------------- /contracts/utils/wrapped_var.py: -------------------------------------------------------------------------------- 1 | """A wrapper for global and local variables.""" 2 | from pyteal import * 3 | 4 | GLOBAL_VAR = "GLOBAL_VAR" 5 | GLOBAL_EX_VAR = "GLOBAL_EX_VAR" 6 | LOCAL_VAR = "LOCAL_VAR" 7 | LOCAL_EX_VAR = "LOCAL_EX_VAR" 8 | 9 | 10 | class WrappedVar: 11 | """Wraps a TEAL global variable.""" 12 | 13 | def __init__( 14 | self, name, var_type, index=None, app_id=None, name_to_bytes=True 15 | ): 16 | self.name = name 17 | self.var_type = var_type 18 | self.name_to_bytes = name_to_bytes 19 | if ( 20 | self.var_type == LOCAL_VAR 21 | or self.var_type == GLOBAL_EX_VAR 22 | or self.var_type == LOCAL_EX_VAR 23 | ): 24 | assert index, "must pass an index" 25 | self.index = index 26 | if self.var_type == LOCAL_EX_VAR: 27 | assert app_id, "must pass an app id" 28 | self.app_id = app_id 29 | 30 | def put(self, val): 31 | """Puts a value into the variable.""" 32 | 33 | if self.var_type == GLOBAL_VAR: 34 | return ( 35 | App.globalPut(Bytes(self.name), val) 36 | if self.name_to_bytes 37 | else App.globalPut(self.name, val) 38 | ) 39 | if self.var_type == LOCAL_VAR: 40 | return ( 41 | App.localPut(self.index, Bytes(self.name), val) 42 | if self.name_to_bytes 43 | else App.localPut(self.index, self.name, val) 44 | ) 45 | 46 | def get(self, app_id=None): 47 | """Gets a value from the variable.""" 48 | 49 | if self.var_type == GLOBAL_VAR: 50 | return ( 51 | App.globalGet(Bytes(self.name)) 52 | if self.name_to_bytes 53 | else App.globalGet(self.name) 54 | ) 55 | if self.var_type == GLOBAL_EX_VAR: 56 | return ( 57 | App.globalGetEx(self.index, Bytes(self.name)) 58 | if self.name_to_bytes 59 | else App.globalGetEx(self.index, self.name) 60 | ) 61 | if self.var_type == LOCAL_VAR: 62 | return ( 63 | App.localGet(self.index, Bytes(self.name)) 64 | if self.name_to_bytes 65 | else App.localGet(self.index, self.name) 66 | ) 67 | if self.var_type == LOCAL_EX_VAR: 68 | return ( 69 | App.localGetEx(self.index, self.app_id, Bytes(self.name)) 70 | if self.name_to_bytes 71 | else App.localGetEx(self.index, self.app_id, self.name) 72 | ) 73 | 74 | def delete(self): 75 | """Deletes the variable.""" 76 | 77 | if self.var_type == GLOBAL_VAR: 78 | return ( 79 | App.globalDel(Bytes(self.name)) 80 | if self.name_to_bytes 81 | else App.globalDel(self.name) 82 | ) 83 | if self.var_type == LOCAL_VAR: 84 | return ( 85 | App.localDel(self.index, Bytes(self.name)) 86 | if self.name_to_bytes 87 | else App.localDel(self.index, self.name) 88 | ) 89 | -------------------------------------------------------------------------------- /contracts/governance/contract_strings.py: -------------------------------------------------------------------------------- 1 | """Defines the strings used in the governance contracts.""" 2 | 3 | 4 | class VotingEscrowStrings: 5 | admin_contract_app_id = "acid" 6 | asset_id = "ai" 7 | claim = "c" 8 | dao_address = "da" 9 | emergency_dao_address = "eda" 10 | extend_lock = "el" 11 | increase_lock_amount = "ila" 12 | lock = "l" 13 | set_admin_contract_app_id = "sacai" 14 | set_gov_token_id = "sgti" 15 | total_locked = "tl" 16 | total_vebank = "tv" 17 | update_vebank_data = "uvb" 18 | user_amount_locked = "aal" 19 | user_amount_vebank = "aav" 20 | user_boost_multiplier = "bm" 21 | user_last_update_time = "ulut" 22 | user_lock_duration = "uld" 23 | user_lock_start_time = "ulst" 24 | 25 | 26 | class ProposalStrings: 27 | create_transaction = "ct" 28 | creator_of_proposal = "cop" 29 | for_or_against = "foa" 30 | link = "l" 31 | opt_into_admin = "oia" 32 | proposer = "p" 33 | template_id = "ti" 34 | title = "t" 35 | user_close_out = "uco" 36 | user_vote = "uv" 37 | voting_amount = "vamt" 38 | 39 | 40 | class AdminContractStrings: 41 | admin = "a" 42 | cancel_proposal = "cp" 43 | canceled_by_emergency_dao = "cbed" 44 | close_out_from_proposal = "cofp" 45 | delegate = "d" 46 | delegated_vote = "devo" 47 | delegating_to = "dt" 48 | delegator_count = "dc" 49 | emergency_dao_address = "eda" 50 | emergency_multisig = "em" 51 | execute = "e" 52 | executed = "ex" 53 | execution_time = "ext" 54 | fast_track_proposal = "ftp" 55 | last_proposal_creation_time = "lpct" 56 | num_proposals_opted_into = "npoi" 57 | open_to_delegation = "otd" 58 | proposal_app_id = "pai" 59 | proposal_contract_opt_in = "coi" 60 | proposal_creation_delay = "pcd" 61 | proposal_duration = "pd" 62 | proposal_execution_delay = "ped" 63 | proposal_factory_address = "pfa" 64 | proposal_rejected = "pr" 65 | quorum_value = "qv" 66 | set_executed = "sex" 67 | set_not_open_to_delegation = "snotd" 68 | set_open_to_delegation = "sotd" 69 | set_proposal_creation_delay = "spcd" 70 | set_proposal_duration = "spd" 71 | set_proposal_execution_delay = "sped" 72 | set_proposal_factory_address = "spfi" 73 | set_quorum_value = "sqv" 74 | set_super_majority = "ssm" 75 | set_voting_escrow_app_id = "sveai" 76 | storage_account = "sa" 77 | storage_account_close_out = "saco" 78 | storage_account_opt_in = "saoi" 79 | super_majority = "sm" 80 | undelegate = "ud" 81 | update_user_vebank = "uuv" 82 | user_account = "ua" 83 | user_close_out = "uco" 84 | user_opt_in = "uoi" 85 | validate = "va" 86 | vebank = "vb" 87 | vote = "vo" 88 | vote_close_time = "vct" 89 | votes_against = "va" 90 | votes_for = "vf" 91 | voting_escrow_app_id = "veai" 92 | 93 | 94 | class ProposalFactoryStrings: 95 | admin = "a" 96 | admin_app_id = "aai" 97 | create_proposal = "cp" 98 | dao_address = "da" 99 | emergency_dao_address = "eda" 100 | gov_token = "gt" 101 | minimum_ve_bank_to_propose = "mvbtp" 102 | proposal_template = "pt" 103 | set_admin_app_id = "saai" 104 | set_minimum_ve_bank_to_propose = "smvbtp" 105 | set_proposal_template = "spt" 106 | set_voting_escrow_app_id = "sveai" 107 | validate_user_account = "vua" 108 | voting_escrow_app_id = "veai" 109 | -------------------------------------------------------------------------------- /contracts/amm/amm.md: -------------------------------------------------------------------------------- 1 | # README.md 2 | 3 | ## Overview 4 | 5 | The code excerpt is part of an Automated Market Maker (AMM) pool system built on the Algorand blockchain. It employs Algorand Smart Contracts (ASC1) expressed in PyTeal, a Python language binding for ASC1. 6 | 7 | This document offers a thorough analysis of the `approval_program` function, with a focus on non-administrative operations. 8 | 9 | ## AMM Implementation 10 | 11 | The `approval_program` method orchestrates the logic for approving transactions and updates to the AMM pool. It returns a program that represents a conditional statement, inspecting the pool's state and the operation being performed, and consequently invoking the appropriate function for that operation. 12 | 13 | Here's an in-depth look into the non-administrative operations handled by AMM: 14 | 15 | ### Pool Operations 16 | 17 | - `pool`: This operation manages general functionality related to the AMM pool, handled by the `on_pool` method. 18 | - `redeem_pool_asset1_residual`: This operation is responsible for redeeming residuals for a specific asset (asset1) in the pool, governed by the `on_redeem_pool_asset1_residual` method. 19 | - `redeem_pool_asset2_residual`: This operation is analogous to the previous one but for a different asset (asset2), as implemented by the `on_redeem_pool_asset2_residual` method. 20 | 21 | ### Burn Operations 22 | 23 | - `burn_asset1_out`: This operation destroys or "burns" a quantity of asset1, as governed by the `on_burn_asset1_out` method. 24 | - `burn_asset2_out`: This operation burns a quantity of asset2, as implemented by the `on_burn_asset2_out` method. 25 | 26 | ### Swap Operations 27 | 28 | - `swap_for_exact`: This operation swaps one asset for an exact quantity of another, handled by the `on_swap` method. 29 | - `swap_exact_for`: This operation swaps an exact quantity of one asset for another, as executed by the `on_swap` method. 30 | - `redeem_swap_residual`: This operation handles the redemption of residuals from a swap operation, as implemented by the `on_redeem_swap_residual` method. 31 | 32 | ### Flash Loan Operations 33 | 34 | - `flash_loan`: This operation manages flash loan transactions, where a loan is issued and repaid within the same transaction block. The specific implementation is handled by the `on_flash_loan` method. 35 | 36 | 37 | ## StableSwap Modifications 38 | 39 | In a StableSwap scenario, the calculations for operations in the pool are modified to maintain the stability of asset values. This is achieved using a different price calculation formula and an amplification factor that can be adjusted over time. 40 | 41 | These modifications are implemented in three key mathematical methods: 42 | 43 | - `compute_D`: This method calculates the StableSwap invariant `D` using an iterative calculation that converges to a solution. The StableSwap invariant `D` is a measure of the total liquidity available in the pool. 44 | - `compute_other_asset_output_stable_swap`: This method calculates the amount of the other asset that will be received in a swap operation. This calculation uses a quadratic equation that is solved iteratively. 45 | - `interpolate_amplification_factor`: This method calculates the current amplification factor based on the initial and future amplification factors and their respective timestamps. The amplification factor influences the price curve of the swap operation. 46 | 47 | ## Further Information 48 | 49 | For more details on AMM, Algorand Smart Contracts, and PyTeal, please refer to the following resources: 50 | 51 | - [Automated Market Makers](https://www.investopedia.com/terms/a/automated-market-maker-amm.asp) 52 | - [Algorand Smart Contracts](https://developer.algorand.org/docs/features/asc1/) 53 | - [PyTeal Documentation](https://pyteal.readthedocs.io/en/latest/) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /contracts/governance/proposal.py: -------------------------------------------------------------------------------- 1 | """Module containing the logic for proposals.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.governance.contract_strings import ( 6 | AdminContractStrings, 7 | ProposalStrings, 8 | ) 9 | from contracts.governance.subroutines import * 10 | from contracts.utils.wrapped_var import * 11 | 12 | 13 | # Subroutines 14 | @Subroutine(TealType.none) 15 | def opt_proposal_contract_into_admin( 16 | admin_app_id, proposer, proposer_admin_storage_account 17 | ): 18 | """Defines a sub-routine for opting a proposal contract into the admin contract.""" 19 | return Seq( 20 | InnerTxnBuilder.Begin(), 21 | InnerTxnBuilder.SetFields( 22 | { 23 | TxnField.type_enum: TxnType.ApplicationCall, 24 | TxnField.sender: Global.current_application_address(), 25 | TxnField.application_id: admin_app_id, 26 | TxnField.on_completion: OnComplete.OptIn, 27 | TxnField.application_args: [ 28 | Bytes(AdminContractStrings.proposal_contract_opt_in) 29 | ], 30 | TxnField.applications: [], 31 | TxnField.accounts: [proposer, proposer_admin_storage_account], 32 | TxnField.fee: Int(0), 33 | } 34 | ), 35 | InnerTxnBuilder.Submit(), 36 | ) 37 | 38 | 39 | class Proposal: 40 | """Defines the proposal contract.""" 41 | 42 | def __init__(self, admin_app_id): 43 | # ADMIN APP ID 44 | self.admin_app_id = Int(admin_app_id) 45 | 46 | # GLOBAL BYTES 47 | self.title = WrappedVar(ProposalStrings.title, GLOBAL_VAR) 48 | self.link = WrappedVar(ProposalStrings.link, GLOBAL_VAR) 49 | 50 | # LOCAL INTS 51 | self.for_or_against = WrappedVar( 52 | ProposalStrings.for_or_against, LOCAL_VAR, Int(0) 53 | ) 54 | self.voting_amount = WrappedVar( 55 | ProposalStrings.voting_amount, LOCAL_VAR, Int(0) 56 | ) 57 | 58 | # CREATE 59 | 60 | def on_creation(self): 61 | """Creates the proposal contract.""" 62 | title = Txn.application_args[0] 63 | link = Txn.application_args[1] 64 | 65 | return Seq(self.title.put(title), self.link.put(link), Approve()) 66 | 67 | # ADMIN 68 | 69 | def on_opt_into_admin(self): 70 | """Opts the proposal contract into the admin contract.""" 71 | proposer = Txn.accounts[1] 72 | proposer_admin_storage_account = Txn.accounts[2] 73 | 74 | return Seq( 75 | # verify sender is creator 76 | MagicAssert(Txn.sender() == Global.creator_address()), 77 | # opt into admin 78 | opt_proposal_contract_into_admin( 79 | self.admin_app_id, proposer, proposer_admin_storage_account 80 | ), 81 | Approve(), 82 | ) 83 | 84 | # OPT IN / CLOSE OUT 85 | 86 | def on_user_vote(self): 87 | """Stores the user's vote.""" 88 | for_or_against = Btoi(Txn.application_args[1]) 89 | voting_amount = Btoi(Txn.application_args[2]) 90 | 91 | return Seq( 92 | # verify caller is admin 93 | MagicAssert(Global.caller_app_id() == self.admin_app_id), 94 | # store proposal state 95 | self.for_or_against.put(for_or_against), 96 | self.voting_amount.put(voting_amount), 97 | Approve(), 98 | ) 99 | 100 | def on_user_close_out(self): 101 | """Calls close out.""" 102 | return Seq( 103 | # verify caller is admin 104 | MagicAssert(Global.caller_app_id() == self.admin_app_id), 105 | Approve(), 106 | ) 107 | 108 | # APPROVAL 109 | 110 | def approval_program(self): 111 | """The approval program for the proposal contract.""" 112 | # check on complete 113 | is_update_application = ( 114 | Txn.on_completion() == OnComplete.UpdateApplication 115 | ) 116 | is_delete_application = ( 117 | Txn.on_completion() == OnComplete.DeleteApplication 118 | ) 119 | is_no_op = Txn.on_completion() == OnComplete.NoOp 120 | is_opt_in = Txn.on_completion() == OnComplete.OptIn 121 | is_close_out = Txn.on_completion() == OnComplete.CloseOut 122 | # type of call 123 | type_of_call = Txn.application_args[0] 124 | 125 | program = Cond( 126 | [Txn.application_id() == Int(0), self.on_creation()], 127 | [is_delete_application, Reject()], 128 | [is_update_application, Reject()], 129 | [ 130 | is_opt_in, 131 | Cond( 132 | [ 133 | type_of_call == Bytes(ProposalStrings.user_vote), 134 | self.on_user_vote(), 135 | ] 136 | ), 137 | ], 138 | [ 139 | is_no_op, 140 | Cond( 141 | [ 142 | type_of_call 143 | == Bytes(ProposalStrings.opt_into_admin), 144 | self.on_opt_into_admin(), 145 | ] 146 | ), 147 | ], 148 | [ 149 | is_close_out, 150 | Cond( 151 | [ 152 | type_of_call 153 | == Bytes(ProposalStrings.user_close_out), 154 | self.on_user_close_out(), 155 | ] 156 | ), 157 | ], 158 | ) 159 | 160 | return program 161 | 162 | def clear_state_program(self): 163 | return Approve() 164 | -------------------------------------------------------------------------------- /contracts/governance/governance.md: -------------------------------------------------------------------------------- 1 | # README.md 2 | 3 | ## Overview 4 | 5 | The provided code is part of a decentralized governance protocol built on the Algorand blockchain. This protocol involves the use of Algorand Smart Contracts (ASC1) written in PyTeal, a Python language binding for ASC1. The governance protocol includes mechanisms for creating, voting on, and executing proposals, which are vital components of decentralized governance. 6 | 7 | Decentralized governance refers to the method by which decisions are made within a decentralized network. It involves the use of blockchain technology to allow participants, also known as stakeholders, to manage the protocol. This management typically involves voting on various protocol proposals such as changes to system parameters, feature improvements, or other updates. 8 | 9 | There are two main components related to the handling of proposals in this code: the `ProposalFactory` and the `Proposal` classes. The `ProposalFactory` is responsible for creating new proposals, while each instance of the `Proposal` class represents an individual proposal. 10 | 11 | ## `ProposalFactory` Class 12 | 13 | The `ProposalFactory` is responsible for validating user accounts and creating new proposals. It manages the creation of a new proposal when a user triggers the `create_proposal` function. This function checks if the user has enough voting power (vebank) to propose a new proposal, and if they do, it creates a new proposal contract. 14 | 15 | The `ProposalFactory` also sets various parameters in the protocol, such as the proposal template, the voting escrow app ID, the admin app ID, and the minimum vebank required to propose. 16 | 17 | ## `Proposal` Class 18 | 19 | The `Proposal` class represents an individual proposal within the governance protocol. It holds the state of the proposal, including the title, link, and the amount of votes for or against it. 20 | 21 | Each `Proposal` has several key methods: 22 | 23 | - `on_creation`: This method is called when a new proposal is created, setting the title and link of the proposal. 24 | - `on_opt_into_admin`: This method is used to opt the proposal into the admin contract. 25 | - `on_user_vote`: This method is used when a user votes on the proposal, storing the vote direction (for or against) and the amount of the vote. 26 | - `on_user_close_out`: This method is used when a user closes out from the proposal. 27 | 28 | ## Governance Protocol 29 | 30 | The Governance Protocol function is the primary function that dictates the logic of the governance protocol. The function returns a program that evaluates a conditional statement, examining the state of the contract and the type of operation being performed. Based on these conditions, it calls the corresponding function for that operation. 31 | 32 | Here's an in-depth look into the operations handled in the Governance Protocol: 33 | 34 | ### Opt-in Functions 35 | 36 | The Governance Protocol handles opt-in actions for users, storage accounts, and proposal contracts, enabling them to participate in the governance protocol. 37 | 38 | - `user_opt_in`: This function sets the user's storage account, sets the account as not open to delegation, and initializes other parameters related to the user's participation in the governance protocol. 39 | - `storage_account_opt_in`: This function manages the opt-in process for a storage account into the protocol, validating the associated transactions and rekeying to the current application. 40 | - `proposal_contract_opt_in`: This function manages the opt-in process for a proposal contract. It verifies the proposal's creator, initializes the proposal state, and updates the last proposal creation time. 41 | 42 | ### Close-out Functions 43 | 44 | The Governance Protocol also manages the actions related to closing out users and storage accounts: 45 | 46 | - `user_close_out`: This function handles the process when a user's storage account is closed out. It ensures the storage account has been closed out of all proposals and rekeys the storage account to the user. 47 | - `storage_account_close_out`: This function manages the process when a storage account is closed out, ensuring that it has been properly closed out. 48 | 49 | ### User Functions 50 | 51 | The Governance Protocol handles a variety of user actions related to the governance protocol: 52 | 53 | - `update_user_vebank`: This function updates a user's vebank (voting escrow bank), a representation of their voting power within the protocol. 54 | - `vote`: This function enables users to vote on a proposal, updating vote totals and the number of proposals the user has participated in. 55 | - `delegate`: This function allows a user to delegate their voting power to another user who is open to delegation. 56 | - `validate`: This function validates a user's vote after voting has closed, checking whether the vote passed and setting the proposal's status accordingly. 57 | - `undelegate`: This function allows a user to withdraw their delegation from another user. 58 | - `delegated_vote`: This function enables a user to vote on behalf of another user, assuming that the latter has delegated their voting power to the former. 59 | - `close_out_from_proposal`: This function manages the process of a user closing out from a proposal, decrementing the number of proposals they have participated in. 60 | - `set_open_to_delegation`: This function allows a user to declare themselves open to having other users delegate their voting power to them. 61 | - `set_not_open_to_delegation`: This function allows a user to declare themselves not open to delegation. 62 | 63 | ## `ProposalFactory` and `Proposal` Logic 64 | 65 | The logic in both the `ProposalFactory` and `Proposal` classes also contains significant logic governing the functioning of the protocol. They dictate the conditional flow of transactions and updates, based on the state of the contract and the type of operation being performed. 66 | 67 | In the `ProposalFactory`, the logic handles operations such as the setting of various protocol parameters and the creation of new proposals. In the `Proposal` class, it manages operations such as the creation of a proposal, voting on a proposal, and closing out from a proposal. -------------------------------------------------------------------------------- /contracts/v2_staking/subroutines.py: -------------------------------------------------------------------------------- 1 | from inspect import currentframe 2 | 3 | from pyteal import * 4 | 5 | from contracts.v2_staking.constants import DEV_MODE 6 | 7 | 8 | def increment(var, amount): 9 | if type(var) == ScratchVar: 10 | return var.store(var.load() + amount) 11 | else: 12 | return var.put(var.get() + amount) 13 | 14 | 15 | def decrement(var, amount): 16 | if type(var) == ScratchVar: 17 | return var.store(var.load() - amount) 18 | else: 19 | return var.put(var.get() - amount) 20 | 21 | 22 | def maximum(var1, var2): 23 | return If(var1 > var2).Then(var1).Else(var2) 24 | 25 | 26 | def minimum(var1, var2): 27 | return If(var1 < var2).Then(var1).Else(var2) 28 | 29 | 30 | def MagicAssert(a): 31 | if DEV_MODE: 32 | return Assert(And(a, Int(currentframe().f_back.f_lineno))) 33 | else: 34 | return Assert(a) 35 | 36 | 37 | # VALIDATION HELPER FUNCTIONS 38 | def verify_txn_is_named_application_call(idx, name): 39 | return Seq( 40 | [ 41 | MagicAssert(Gtxn[idx].on_completion() == OnComplete.NoOp), 42 | MagicAssert(Gtxn[idx].type_enum() == TxnType.ApplicationCall), 43 | MagicAssert( 44 | Gtxn[idx].application_id() == Global.current_application_id() 45 | ), 46 | MagicAssert(Gtxn[idx].application_args[0] == Bytes(name)), 47 | ] 48 | ) 49 | 50 | 51 | def verify_txn_is_sending_asa_to_contract(idx, asset_id): 52 | return Seq( 53 | [ 54 | MagicAssert(Gtxn[idx].type_enum() == TxnType.AssetTransfer), 55 | MagicAssert(Gtxn[idx].xfer_asset() == asset_id), 56 | MagicAssert( 57 | Gtxn[idx].asset_receiver() 58 | == Global.current_application_address() 59 | ), 60 | MagicAssert(Gtxn[idx].asset_amount() > Int(0)), 61 | ] 62 | ) 63 | 64 | 65 | @Subroutine(TealType.none) 66 | def verify_txn_is_payment(idx: Expr, receiver: Expr) -> Expr: 67 | return Seq( 68 | [ 69 | MagicAssert(Gtxn[idx].type_enum() == TxnType.Payment), 70 | MagicAssert(Gtxn[idx].receiver() == receiver), 71 | MagicAssert(Gtxn[idx].amount() > Int(0)), 72 | ] 73 | ) 74 | 75 | 76 | @Subroutine(TealType.none) 77 | def verify_txn_is_asset_transfer(idx: Expr, receiver: Expr, asset_id: Expr): 78 | return Seq( 79 | [ 80 | MagicAssert(Gtxn[idx].type_enum() == TxnType.AssetTransfer), 81 | MagicAssert(Gtxn[idx].asset_receiver() == receiver), 82 | MagicAssert(Gtxn[idx].xfer_asset() == asset_id), 83 | MagicAssert(Gtxn[idx].asset_amount() > Int(0)), 84 | ] 85 | ) 86 | 87 | 88 | def verify_txn_is_named_no_op_application_call( 89 | idx, name, application_id=Global.current_application_id() 90 | ): 91 | return Seq( 92 | [ 93 | MagicAssert(Gtxn[idx].type_enum() == TxnType.ApplicationCall), 94 | MagicAssert(Gtxn[idx].on_completion() == OnComplete.NoOp), 95 | MagicAssert(Gtxn[idx].application_id() == application_id), 96 | MagicAssert(Gtxn[idx].application_args[0] == Bytes(name)), 97 | ] 98 | ) 99 | 100 | 101 | def verify_txn_account(txn_idx, account_idx, expected_account): 102 | return MagicAssert(Gtxn[txn_idx].accounts[account_idx] == expected_account) 103 | 104 | 105 | # INNER TXN HELPERS 106 | 107 | 108 | @Subroutine(TealType.none) 109 | def send_asa(asset_id: Expr, amount: Expr, receiver: Expr) -> Expr: 110 | return Seq( 111 | [ 112 | InnerTxnBuilder.Begin(), 113 | InnerTxnBuilder.SetField( 114 | TxnField.type_enum, TxnType.AssetTransfer 115 | ), 116 | InnerTxnBuilder.SetField(TxnField.xfer_asset, asset_id), 117 | InnerTxnBuilder.SetField(TxnField.asset_amount, amount), 118 | InnerTxnBuilder.SetField(TxnField.asset_receiver, receiver), 119 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 120 | InnerTxnBuilder.Submit(), 121 | ] 122 | ) 123 | 124 | 125 | @Subroutine(TealType.none) 126 | def send_asa_from_address( 127 | sender: Expr, asset_id: Expr, amount: Expr, receiver: Expr 128 | ) -> Expr: 129 | return Seq( 130 | [ 131 | InnerTxnBuilder.Begin(), 132 | InnerTxnBuilder.SetField(TxnField.sender, sender), 133 | InnerTxnBuilder.SetField( 134 | TxnField.type_enum, TxnType.AssetTransfer 135 | ), 136 | InnerTxnBuilder.SetField(TxnField.xfer_asset, asset_id), 137 | InnerTxnBuilder.SetField(TxnField.asset_amount, amount), 138 | InnerTxnBuilder.SetField(TxnField.asset_receiver, receiver), 139 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 140 | InnerTxnBuilder.Submit(), 141 | ] 142 | ) 143 | 144 | 145 | @Subroutine(TealType.none) 146 | def send_algo(amount: Expr, receiver: Expr) -> Expr: 147 | return Seq( 148 | [ 149 | InnerTxnBuilder.Begin(), 150 | InnerTxnBuilder.SetField(TxnField.type_enum, TxnType.Payment), 151 | InnerTxnBuilder.SetField(TxnField.amount, amount), 152 | InnerTxnBuilder.SetField(TxnField.receiver, receiver), 153 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 154 | InnerTxnBuilder.Submit(), 155 | ] 156 | ) 157 | 158 | 159 | @Subroutine(TealType.none) 160 | def send_algo_from_address(sender: Expr, amount: Expr, receiver: Expr) -> Expr: 161 | return Seq( 162 | [ 163 | InnerTxnBuilder.Begin(), 164 | InnerTxnBuilder.SetField(TxnField.sender, sender), 165 | InnerTxnBuilder.SetField(TxnField.type_enum, TxnType.Payment), 166 | InnerTxnBuilder.SetField(TxnField.amount, amount), 167 | InnerTxnBuilder.SetField(TxnField.receiver, receiver), 168 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 169 | InnerTxnBuilder.Submit(), 170 | ] 171 | ) 172 | 173 | 174 | def send_asa_set_fields(asa_id: Expr, receiver: Expr, amount: Expr): 175 | return InnerTxnBuilder.SetFields( 176 | { 177 | TxnField.type_enum: TxnType.AssetTransfer, 178 | TxnField.xfer_asset: asa_id, 179 | TxnField.asset_receiver: receiver, 180 | TxnField.asset_amount: amount, 181 | TxnField.fee: Int(0), 182 | } 183 | ) 184 | 185 | 186 | # TODO can we change this from "into" to "into" globally 187 | @Subroutine(TealType.none) 188 | def opt_into_asa(id: Expr) -> Expr: 189 | return send_asa(id, Int(0), Global.current_application_address()) 190 | -------------------------------------------------------------------------------- /contracts/amm/stable_pool.py: -------------------------------------------------------------------------------- 1 | """Contains the Stable Pool variation of the AMM.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.amm.constants import ( 6 | DEFAULT_STABLESWAP_FEE_PCT_SCALED, 7 | MAX_AMPLIFICATION_FACTOR, 8 | ) 9 | from contracts.amm.contract_strings import AMMPoolStrings 10 | from contracts.amm.pool import AMMPool 11 | from contracts.amm.stable_swap_math import ( 12 | compute_D, 13 | compute_other_asset_output_stable_swap, 14 | interpolate_amplification_factor, 15 | ) 16 | from contracts.amm.subroutines import op_up 17 | from contracts.utils.wrapped_var import * 18 | 19 | 20 | class AMMStablePool(AMMPool): 21 | """A Stable pool variation of the AMM.""" 22 | 23 | def __init__(self, manager_app_id): 24 | super().__init__(manager_app_id, DEFAULT_STABLESWAP_FEE_PCT_SCALED) 25 | self.initial_amplification_factor = WrappedVar( 26 | AMMPoolStrings.initial_amplification_factor, GLOBAL_VAR 27 | ) 28 | self.future_amplification_factor = WrappedVar( 29 | AMMPoolStrings.future_amplification_factor, GLOBAL_VAR 30 | ) 31 | self.initial_amplification_factor_time = WrappedVar( 32 | AMMPoolStrings.initial_amplification_factor_time, GLOBAL_VAR 33 | ) 34 | self.future_amplification_factor_time = WrappedVar( 35 | AMMPoolStrings.future_amplification_factor_time, GLOBAL_VAR 36 | ) 37 | self.lp_asset_prefix = Bytes("AF-NANO-POOL-") 38 | 39 | def swap_exact_asset1_for(self, asset1_amount): 40 | """Swaps an exact amount of asset 1 for a variable amount of asset 2.""" 41 | return Seq( 42 | op_up( 43 | Txn.fee() - Int(2) * Global.min_txn_fee(), 44 | self.manager_app_id_var.get(), 45 | ), 46 | compute_other_asset_output_stable_swap( 47 | self.balance_1.get() + asset1_amount, 48 | self.balance_1.get(), 49 | self.balance_2.get(), 50 | self.get_amplification_factor(), 51 | ) 52 | - Int(1), 53 | ) 54 | 55 | def swap_exact_asset2_for(self, asset2_amount): 56 | """Swaps an exact amount of asset 2 for a variable amount of asset 1.""" 57 | return Seq( 58 | op_up( 59 | Txn.fee() - Int(2) * Global.min_txn_fee(), 60 | self.manager_app_id_var.get(), 61 | ), 62 | compute_other_asset_output_stable_swap( 63 | self.balance_2.get() + asset2_amount, 64 | self.balance_2.get(), 65 | self.balance_1.get(), 66 | self.get_amplification_factor(), 67 | ) 68 | - Int(1), 69 | ) 70 | 71 | def swap_for_exact_asset1_amount(self, asset1_amount): 72 | """Swaps for an exact amount of asset 1.""" 73 | return Seq( 74 | op_up( 75 | Txn.fee() - Int(2) * Global.min_txn_fee(), 76 | self.manager_app_id_var.get(), 77 | ), 78 | compute_other_asset_output_stable_swap( 79 | self.balance_1.get() - asset1_amount, 80 | self.balance_1.get(), 81 | self.balance_2.get(), 82 | self.get_amplification_factor(), 83 | ) 84 | + Int(1), 85 | ) 86 | 87 | def swap_for_exact_asset2_amount(self, asset2_amount): 88 | """Swaps for an exact amount of asset 2.""" 89 | return Seq( 90 | op_up( 91 | Txn.fee() - Int(2) * Global.min_txn_fee(), 92 | self.manager_app_id_var.get(), 93 | ), 94 | compute_other_asset_output_stable_swap( 95 | self.balance_2.get() - asset2_amount, 96 | self.balance_2.get(), 97 | self.balance_1.get(), 98 | self.get_amplification_factor(), 99 | ) 100 | + Int(1), 101 | ) 102 | 103 | def calculate_lp_issuance(self, pool_is_empty): 104 | """Calculates the LP issuance.""" 105 | D0_store = ScratchVar(TealType.uint64) 106 | D0_calc = compute_D( 107 | self.balance_1.get(), 108 | self.balance_2.get(), 109 | self.get_amplification_factor(), 110 | ) 111 | 112 | D1_calc = compute_D( 113 | self.balance_1.get() 114 | + self.adjusted_pool_asset1_amount_store.load(), 115 | self.balance_2.get() 116 | + self.adjusted_pool_asset2_amount_store.load(), 117 | self.get_amplification_factor(), 118 | ) 119 | 120 | lp_issued_calc = WideRatio( 121 | [self.lp_circulation.get(), D1_calc - D0_store.load()], 122 | [D0_store.load()], 123 | ) 124 | 125 | return If( 126 | pool_is_empty, 127 | self.lp_issued_store.store(D1_calc), 128 | Seq( 129 | op_up( 130 | Txn.fee() - Int(3) * Global.min_txn_fee(), 131 | self.manager_app_id, 132 | ), 133 | D0_store.store(D0_calc), 134 | self.lp_issued_store.store(lp_issued_calc), 135 | ), 136 | ) 137 | 138 | def get_amplification_factor(self): 139 | """Gets the current amplification factor.""" 140 | return interpolate_amplification_factor( 141 | self.initial_amplification_factor.get(), 142 | self.future_amplification_factor.get(), 143 | self.initial_amplification_factor_time.get(), 144 | self.future_amplification_factor_time.get(), 145 | ) 146 | 147 | def _admin_fns_list(self): 148 | """Lists the admin functions.""" 149 | return super()._admin_fns_list() + [ 150 | [ 151 | Txn.application_args[0] 152 | == Bytes(AMMPoolStrings.ramp_amplification_factor), 153 | self.on_ramp_amplification_factor(), 154 | ], 155 | ] 156 | 157 | def on_ramp_amplification_factor(self): 158 | """Raises the amplification factor.""" 159 | sender_is_admin = Txn.sender() == self.admin.get() 160 | initial_A = self.get_amplification_factor() 161 | future_A = Btoi(Txn.application_args[1]) 162 | future_time = Btoi(Txn.application_args[2]) 163 | 164 | return Seq( 165 | Assert(sender_is_admin), 166 | Assert( 167 | future_time 168 | >= Global.latest_timestamp() + self.param_update_delay.get() 169 | ), 170 | Assert(future_A > Int(0)), 171 | Assert(future_A < MAX_AMPLIFICATION_FACTOR), 172 | self.initial_amplification_factor.put(initial_A), 173 | self.future_amplification_factor.put(future_A), 174 | self.initial_amplification_factor_time.put( 175 | Global.latest_timestamp() 176 | ), 177 | self.future_amplification_factor_time.put(future_time), 178 | Int(1), 179 | ) 180 | 181 | def on_creation(self): 182 | """Creates the pool.""" 183 | amplification_factor = Btoi(Txn.application_args[2]) 184 | return Seq( 185 | self.future_amplification_factor.put(amplification_factor), 186 | super().on_creation(), 187 | ) 188 | -------------------------------------------------------------------------------- /contracts/amm/subroutines.py: -------------------------------------------------------------------------------- 1 | """Contains subroutines used in the AMM.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.amm.constants import * 6 | from contracts.amm.contract_strings import AMMManagerStrings 7 | 8 | # WIDELY USED FCNS 9 | 10 | 11 | @Subroutine(TealType.uint64) 12 | def calculate_integer_wrapped_value(current_value: Expr, addend: Expr) -> Expr: 13 | """Calculates the new value of a wrapped integer variable.""" 14 | remaining_integer_space = MAX_INT_U64 - current_value 15 | return If( 16 | addend > remaining_integer_space, 17 | Return(addend - remaining_integer_space - Int(1)), 18 | Return(current_value + addend), 19 | ) 20 | 21 | 22 | @Subroutine(TealType.none) 23 | def opt_in_to_asa(asset_id: Expr) -> Expr: 24 | """Opt in to an ASA.""" 25 | return Seq( 26 | [ 27 | InnerTxnBuilder.Begin(), 28 | InnerTxnBuilder.SetField( 29 | TxnField.type_enum, TxnType.AssetTransfer 30 | ), 31 | InnerTxnBuilder.SetField(TxnField.xfer_asset, asset_id), 32 | InnerTxnBuilder.SetField(TxnField.asset_amount, Int(0)), 33 | InnerTxnBuilder.SetField( 34 | TxnField.asset_receiver, Global.current_application_address() 35 | ), 36 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 37 | InnerTxnBuilder.Submit(), 38 | ] 39 | ) 40 | 41 | 42 | @Subroutine(TealType.none) 43 | def send_asa(asset_id: Expr, amount: Expr) -> Expr: 44 | """Send an ASA.""" 45 | return Seq( 46 | [ 47 | InnerTxnBuilder.Begin(), 48 | InnerTxnBuilder.SetField( 49 | TxnField.type_enum, TxnType.AssetTransfer 50 | ), 51 | InnerTxnBuilder.SetField(TxnField.xfer_asset, asset_id), 52 | InnerTxnBuilder.SetField(TxnField.asset_amount, amount), 53 | InnerTxnBuilder.SetField(TxnField.asset_receiver, Txn.sender()), 54 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 55 | InnerTxnBuilder.Submit(), 56 | ] 57 | ) 58 | 59 | 60 | @Subroutine(TealType.none) 61 | def send_algo(amount: Expr) -> Expr: 62 | """Send Algo.""" 63 | return Seq( 64 | [ 65 | Assert( 66 | Ge( 67 | Balance(Global.current_application_address()), 68 | amount + Global.min_balance(), 69 | ) 70 | ), 71 | InnerTxnBuilder.Begin(), 72 | InnerTxnBuilder.SetField(TxnField.type_enum, TxnType.Payment), 73 | InnerTxnBuilder.SetField(TxnField.amount, amount), 74 | InnerTxnBuilder.SetField(TxnField.receiver, Txn.sender()), 75 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 76 | InnerTxnBuilder.Submit(), 77 | ] 78 | ) 79 | 80 | 81 | @Subroutine(TealType.none) 82 | def send_algo_to_receiver(amount: Expr, receiver: Expr) -> Expr: 83 | """Send Algo to a receiver.""" 84 | return Seq( 85 | [ 86 | Assert( 87 | Ge( 88 | Balance(Global.current_application_address()), 89 | amount + Global.min_balance(), 90 | ) 91 | ), 92 | InnerTxnBuilder.Begin(), 93 | InnerTxnBuilder.SetField(TxnField.type_enum, TxnType.Payment), 94 | InnerTxnBuilder.SetField(TxnField.amount, amount), 95 | InnerTxnBuilder.SetField(TxnField.receiver, receiver), 96 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 97 | InnerTxnBuilder.Submit(), 98 | ] 99 | ) 100 | 101 | 102 | @Subroutine(TealType.none) 103 | def op_up(fee: Expr, op_farm_app_id: Expr): 104 | """Increase the available operations for the group transaction.""" 105 | i = ScratchVar(TealType.uint64) 106 | n = fee / Int(1000) 107 | return For(i.store(Int(0)), i.load() < n, i.store(i.load() + Int(1))).Do( 108 | Seq( 109 | InnerTxnBuilder.Begin(), 110 | InnerTxnBuilder.SetFields( 111 | { 112 | TxnField.type_enum: TxnType.ApplicationCall, 113 | TxnField.application_id: op_farm_app_id, 114 | TxnField.application_args: [ 115 | Bytes(AMMManagerStrings.farm_ops) 116 | ], 117 | TxnField.fee: Int(0), 118 | } 119 | ), 120 | InnerTxnBuilder.Submit(), 121 | ) 122 | ) 123 | 124 | 125 | def create_lp_asset( 126 | lp_id, lp_asset_prefix, asset1_id, asset2_id, lp_asset_name_store 127 | ): 128 | """Creates the LP asset.""" 129 | asset1_name = AssetParam.unitName(asset1_id) 130 | asset2_name = AssetParam.unitName(asset2_id) 131 | asset_names_concatenated_algo = Concat( 132 | lp_asset_prefix, 133 | Concat(Bytes("ALGO"), Concat(Bytes("-"), asset2_name.value())), 134 | ) 135 | asset_names_concatenated_asa = Concat( 136 | lp_asset_prefix, 137 | Concat(asset1_name.value(), Concat(Bytes("-"), asset2_name.value())), 138 | ) 139 | create_lp_asset_name = Seq( 140 | [ 141 | If( 142 | asset1_id == Int(1), 143 | Seq( 144 | [ 145 | asset2_name, 146 | Assert(asset2_name.hasValue()), 147 | lp_asset_name_store.store( 148 | asset_names_concatenated_algo 149 | ), 150 | ] 151 | ), 152 | Seq( 153 | [ 154 | asset1_name, 155 | asset2_name, 156 | Assert(asset1_name.hasValue()), 157 | Assert(asset2_name.hasValue()), 158 | lp_asset_name_store.store( 159 | asset_names_concatenated_asa 160 | ), 161 | ] 162 | ), 163 | ), 164 | ] 165 | ) 166 | 167 | return Seq( 168 | [ 169 | create_lp_asset_name, 170 | InnerTxnBuilder.Begin(), 171 | InnerTxnBuilder.SetField(TxnField.type_enum, TxnType.AssetConfig), 172 | InnerTxnBuilder.SetField( 173 | TxnField.config_asset_name, lp_asset_name_store.load() 174 | ), 175 | InnerTxnBuilder.SetField( 176 | TxnField.config_asset_unit_name, Bytes("AF-POOL") 177 | ), 178 | InnerTxnBuilder.SetField( 179 | TxnField.config_asset_total, MAX_CIRCULATION 180 | ), 181 | InnerTxnBuilder.SetField( 182 | TxnField.config_asset_decimals, LP_DECIMALS 183 | ), 184 | InnerTxnBuilder.SetField(TxnField.config_asset_url, URL), 185 | InnerTxnBuilder.SetField( 186 | TxnField.config_asset_manager, 187 | Global.current_application_address(), 188 | ), 189 | InnerTxnBuilder.SetField( 190 | TxnField.config_asset_reserve, 191 | Global.current_application_address(), 192 | ), 193 | InnerTxnBuilder.Submit(), 194 | lp_id.put(InnerTxn.created_asset_id()), 195 | ] 196 | ) 197 | -------------------------------------------------------------------------------- /contracts/amm/moving_ratio_stable_pool.py: -------------------------------------------------------------------------------- 1 | """A contract used modify the stable AMMPool to use a moving ratio.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.amm.constants import ( 6 | DEFAULT_STABLESWAP_FEE_PCT_SCALED, 7 | MAX_AMPLIFICATION_FACTOR, 8 | ) 9 | from contracts.amm.contract_strings import AMMPoolStrings 10 | from contracts.amm.pool import AMMPool 11 | from contracts.amm.stable_swap_math import ( 12 | compute_D, 13 | compute_other_asset_output_stable_swap, 14 | interpolate_amplification_factor, 15 | ) 16 | from contracts.amm.subroutines import op_up 17 | from contracts.utils.wrapped_var import * 18 | 19 | 20 | class AMMStablePool(AMMPool): 21 | """Stable pool contract.""" 22 | 23 | def __init__(self, manager_app_id): 24 | super().__init__(manager_app_id, DEFAULT_STABLESWAP_FEE_PCT_SCALED) 25 | self.initial_amplification_factor = WrappedVar( 26 | AMMPoolStrings.initial_amplification_factor, GLOBAL_VAR 27 | ) 28 | self.future_amplification_factor = WrappedVar( 29 | AMMPoolStrings.future_amplification_factor, GLOBAL_VAR 30 | ) 31 | self.initial_amplification_factor_time = WrappedVar( 32 | AMMPoolStrings.initial_amplification_factor_time, GLOBAL_VAR 33 | ) 34 | self.future_amplification_factor_time = WrappedVar( 35 | AMMPoolStrings.future_amplification_factor_time, GLOBAL_VAR 36 | ) 37 | self.lp_asset_prefix = Bytes("AF-NANO-POOL-") 38 | 39 | def swap_exact_asset1_for(self, asset1_amount): 40 | """Swaps an exact amount of asset 1 for a variable amount of asset 2.""" 41 | 42 | return Seq( 43 | op_up( 44 | Txn.fee() - Int(2) * Global.min_txn_fee(), 45 | self.manager_app_id_var.get(), 46 | ), 47 | compute_other_asset_output_stable_swap( 48 | self.balance_1.get() + asset1_amount, 49 | self.balance_1.get(), 50 | self.balance_2.get(), 51 | self.get_amplification_factor(), 52 | ) 53 | - Int(1), 54 | ) 55 | 56 | def swap_exact_asset2_for(self, asset2_amount): 57 | """Swaps an exact amount of asset 2 for a variable amount of asset 1.""" 58 | 59 | return Seq( 60 | op_up( 61 | Txn.fee() - Int(2) * Global.min_txn_fee(), 62 | self.manager_app_id_var.get(), 63 | ), 64 | compute_other_asset_output_stable_swap( 65 | self.balance_2.get() + asset2_amount, 66 | self.balance_2.get(), 67 | self.balance_1.get(), 68 | self.get_amplification_factor(), 69 | ) 70 | - Int(1), 71 | ) 72 | 73 | def swap_for_exact_asset1_amount(self, asset1_amount): 74 | """Swaps a variable amount of asset 2 for an exact amount of asset 1.""" 75 | 76 | return Seq( 77 | op_up( 78 | Txn.fee() - Int(2) * Global.min_txn_fee(), 79 | self.manager_app_id_var.get(), 80 | ), 81 | compute_other_asset_output_stable_swap( 82 | self.balance_1.get() - asset1_amount, 83 | self.balance_1.get(), 84 | self.balance_2.get(), 85 | self.get_amplification_factor(), 86 | ) 87 | + Int(1), 88 | ) 89 | 90 | def swap_for_exact_asset2_amount(self, asset2_amount): 91 | """Swaps a variable amount of asset 1 for an exact amount of asset 2.""" 92 | 93 | return Seq( 94 | op_up( 95 | Txn.fee() - Int(2) * Global.min_txn_fee(), 96 | self.manager_app_id_var.get(), 97 | ), 98 | compute_other_asset_output_stable_swap( 99 | self.balance_2.get() - asset2_amount, 100 | self.balance_2.get(), 101 | self.balance_1.get(), 102 | self.get_amplification_factor(), 103 | ) 104 | + Int(1), 105 | ) 106 | 107 | def calculate_lp_issuance(self, pool_is_empty): 108 | """Calculates the amount of LP tokens to issue for a given deposit.""" 109 | 110 | D0_store = ScratchVar(TealType.uint64) 111 | D0_calc = compute_D( 112 | self.balance_1.get(), 113 | self.balance_2.get(), 114 | self.get_amplification_factor(), 115 | ) 116 | 117 | D1_calc = compute_D( 118 | self.balance_1.get() 119 | + self.adjusted_pool_asset1_amount_store.load(), 120 | self.balance_2.get() 121 | + self.adjusted_pool_asset2_amount_store.load(), 122 | self.get_amplification_factor(), 123 | ) 124 | 125 | lp_issued_calc = WideRatio( 126 | [self.lp_circulation.get(), D1_calc - D0_store.load()], 127 | [D0_store.load()], 128 | ) 129 | 130 | return If( 131 | pool_is_empty, 132 | self.lp_issued_store.store(D1_calc), 133 | Seq( 134 | op_up( 135 | Txn.fee() - Int(3) * Global.min_txn_fee(), 136 | self.manager_app_id, 137 | ), 138 | D0_store.store(D0_calc), 139 | self.lp_issued_store.store(lp_issued_calc), 140 | ), 141 | ) 142 | 143 | def get_amplification_factor(self): 144 | """Gets the current amplification factor.""" 145 | 146 | return interpolate_amplification_factor( 147 | self.initial_amplification_factor.get(), 148 | self.future_amplification_factor.get(), 149 | self.initial_amplification_factor_time.get(), 150 | self.future_amplification_factor_time.get(), 151 | ) 152 | 153 | def _admin_fns_list(self): 154 | """Gets the list of admin functions.""" 155 | 156 | return super()._admin_fns_list() + [ 157 | [ 158 | Txn.application_args[0] 159 | == Bytes(AMMPoolStrings.ramp_amplification_factor), 160 | self.on_ramp_amplification_factor(), 161 | ], 162 | [ 163 | Txn.application_args[0] 164 | == Bytes(AMMPoolStrings.update_swap_fee), 165 | self.on_update_swap_fee(), 166 | ], 167 | [ 168 | Txn.application_args[0] 169 | == Bytes(AMMPoolStrings.schedule_swap_fee_update), 170 | self.on_schedule_swap_fee_update(), 171 | ], 172 | [ 173 | Txn.application_args[0] 174 | == Bytes(AMMPoolStrings.increase_param_update_delay), 175 | self.on_increase_param_delay(), 176 | ], 177 | ] 178 | 179 | def on_ramp_amplification_factor(self): 180 | """Ramps the amplification factor.""" 181 | 182 | sender_is_admin = Txn.sender() == self.admin.get() 183 | initial_A = self.get_amplification_factor() 184 | future_A = Btoi(Txn.application_args[1]) 185 | future_time = Btoi(Txn.application_args[2]) 186 | 187 | return Seq( 188 | Assert(sender_is_admin), 189 | Assert( 190 | future_time 191 | >= Global.latest_timestamp() + self.param_update_delay.get() 192 | ), 193 | Assert(future_A > Int(0)), 194 | Assert(future_A < MAX_AMPLIFICATION_FACTOR), 195 | self.initial_amplification_factor.put(initial_A), 196 | self.future_amplification_factor.put(future_A), 197 | self.initial_amplification_factor_time.put( 198 | Global.latest_timestamp() 199 | ), 200 | self.future_amplification_factor_time.put(future_time), 201 | Int(1), 202 | ) 203 | 204 | def on_creation(self): 205 | """Creates the pool.""" 206 | 207 | amplification_factor = Btoi(Txn.application_args[2]) 208 | return Seq( 209 | self.future_amplification_factor.put(amplification_factor), 210 | super().on_creation(), 211 | ) 212 | -------------------------------------------------------------------------------- /contracts/amm/stable_swap_math.py: -------------------------------------------------------------------------------- 1 | """Contains the mathematical implementation of the Stable Pool variation of the AMM.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.amm.constants import FIXED_6_SCALE_FACTOR 6 | 7 | 8 | @Subroutine(TealType.uint64) 9 | def compute_D( 10 | asset1_amount: Expr, 11 | asset2_amount: Expr, 12 | amplification_param: Expr, 13 | ): 14 | """ 15 | Computes the StableSwap invariant D in non-overflowing integer operations 16 | 17 | This is an iterative calculation which uses the following equation: 18 | A * sum(x_i) * n**n + D = A * D * n**n + D**(n+1) / (n**n * prod(x_i)) 19 | 20 | Which converges to a solution, D, where: 21 | D[j+1] = (A * n**n * sum(x_i) - D[j]**(n+1) / (n**n prod(x_i))) / (A * n**n - 1) 22 | """ 23 | n_coins = Int(2) 24 | S = asset1_amount + asset2_amount 25 | 26 | D_estimate = ScratchVar(TealType.bytes) 27 | D_prev = ScratchVar(TealType.bytes) 28 | D_prod_denom = ScratchVar(TealType.bytes) 29 | D_prod = ScratchVar(TealType.bytes) 30 | AnnS = ScratchVar(TealType.bytes) 31 | i = ScratchVar(TealType.uint64) 32 | 33 | D_prod_num_calc = BytesMul( 34 | D_prev.load(), BytesMul(D_prev.load(), D_prev.load()) 35 | ) # D**(n+1) 36 | D_prod_denom_calc = BytesMul( 37 | Itob(Exp(n_coins, n_coins)), 38 | BytesMul(Itob(asset2_amount), Itob(asset1_amount)), # nn*(P[x_i]) 39 | ) 40 | D_prod_calc = BytesDiv(D_prod_num_calc, D_prod_denom.load()) 41 | 42 | Ann_calc = amplification_param * Exp(n_coins, n_coins) 43 | AnnS_calc = BytesDiv( 44 | BytesMul(Itob(Ann_calc), Itob(S)), Itob(FIXED_6_SCALE_FACTOR) 45 | ) 46 | 47 | D_estimate_num_calc = BytesMul( 48 | BytesAdd( 49 | AnnS.load(), 50 | BytesMul(D_prod.load(), Itob(n_coins)), 51 | ), 52 | D_prev.load(), 53 | ) 54 | D_estimate_denom_calc = BytesAdd( 55 | BytesDiv( 56 | BytesMul(Itob(Ann_calc - FIXED_6_SCALE_FACTOR), D_prev.load()), 57 | Itob(FIXED_6_SCALE_FACTOR), 58 | ), 59 | BytesMul(D_prod.load(), Itob(n_coins + Int(1))), 60 | ) 61 | 62 | D_estimate_calc = BytesDiv(D_estimate_num_calc, D_estimate_denom_calc) 63 | calc = Seq( 64 | If(S == Int(0)).Then(Return(Int(0))), 65 | # Store expensive calcs that don't need to be recomputed 66 | AnnS.store(AnnS_calc), 67 | D_prod_denom.store(D_prod_denom_calc), 68 | # First guess 69 | D_estimate.store(Itob(S)), 70 | For( 71 | i.store(Int(0)), i.load() < Int(255), i.store(i.load() + Int(1)) 72 | ).Do( 73 | Seq( 74 | D_prev.store(D_estimate.load()), 75 | D_prod.store(D_prod_calc), 76 | D_estimate.store(D_estimate_calc), 77 | If(BytesGt(D_estimate.load(), D_prev.load())) 78 | .Then( 79 | If( 80 | BytesLe( 81 | BytesMinus(D_estimate.load(), D_prev.load()), 82 | Itob(Int(1)), 83 | ) 84 | ).Then(Return(Btoi(D_estimate.load()))) 85 | ) 86 | .Else( 87 | If( 88 | BytesLe( 89 | BytesMinus(D_prev.load(), D_estimate.load()), 90 | Itob(Int(1)), 91 | ) 92 | ).Then(Return(Btoi(D_estimate.load()))) 93 | ), 94 | ) 95 | ), 96 | Assert(i.load() < Int(255)), # did not converge, throw error 97 | Return(Int(0)), # unreachable code 98 | ) 99 | 100 | return calc 101 | 102 | 103 | @Subroutine(TealType.uint64) 104 | def compute_other_asset_output_stable_swap( 105 | input_asset_new_total: Expr, 106 | input_asset_previous_total: Expr, 107 | previous_output_asset_total: Expr, 108 | amplification_param: Expr, 109 | ): 110 | """ 111 | Computes the amount of the other asset that will be received in a swap 112 | 113 | The input/output nomenclature is referring to inputs to the equation, not 114 | the trade itself. In "swap for exact" case the input/output is the asset 115 | (sent to the pool)/(received from the pool). 116 | 117 | In "swap exact for" case it is the reverse - input/output is 118 | (received from the pool)/(sent to the pool) since we need to back out the 119 | amount to send to the pool from the desired received amount. 120 | 121 | Calculate x[j] if one makes x[i] = x. This is done by solving quadratic 122 | equation iteratively. 123 | x_1**2 + x_1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) 124 | x_1**2 + b*x_1 = c 125 | x_1 = (x_1**2 + c) / (2*x_1 + b) 126 | """ 127 | n_assets = Int(2) 128 | D = ScratchVar(TealType.uint64) 129 | b = ScratchVar(TealType.uint64) 130 | c = ScratchVar(TealType.bytes) 131 | new_output_asset_total_estimate = ScratchVar(TealType.uint64) 132 | new_output_asset_total_estimate_prev = ScratchVar(TealType.uint64) 133 | i = ScratchVar(TealType.uint64) 134 | 135 | Ann_calc = amplification_param * Exp(n_assets, n_assets) 136 | S = input_asset_new_total 137 | 138 | b_calc = S + WideRatio([D.load(), FIXED_6_SCALE_FACTOR], [Ann_calc]) 139 | c_calc = BytesDiv( 140 | BytesMul( 141 | Itob(D.load()), 142 | BytesMul( 143 | Itob(D.load()), 144 | BytesMul(Itob(D.load()), Itob(FIXED_6_SCALE_FACTOR)), 145 | ), 146 | ), 147 | BytesMul( 148 | Itob(input_asset_new_total), 149 | BytesMul(Itob(Ann_calc), Itob(Exp(n_assets, n_assets))), 150 | ), 151 | ) 152 | 153 | ret_calc = Seq( 154 | If( 155 | previous_output_asset_total 156 | > new_output_asset_total_estimate.load(), 157 | Return( 158 | previous_output_asset_total 159 | - new_output_asset_total_estimate.load() 160 | ), # swap for exact 161 | Return( 162 | new_output_asset_total_estimate.load() 163 | - previous_output_asset_total 164 | ), 165 | ) # swap exact for 166 | ) 167 | 168 | estimate_num_calc = BytesAdd( 169 | BytesMul( 170 | Itob(new_output_asset_total_estimate.load()), 171 | Itob(new_output_asset_total_estimate.load()), 172 | ), 173 | c.load(), 174 | ) 175 | 176 | estimate_denom_calc = Itob( 177 | Int(2) * new_output_asset_total_estimate.load() + b.load() - D.load() 178 | ) 179 | estimate_calc = Btoi(BytesDiv(estimate_num_calc, estimate_denom_calc)) 180 | 181 | calc = Seq( 182 | # Store expensive calcs that don't need to be recomputed 183 | D.store( 184 | compute_D( 185 | input_asset_previous_total, 186 | previous_output_asset_total, 187 | amplification_param, 188 | ) 189 | ), 190 | b.store(b_calc), 191 | c.store(c_calc), 192 | # First guess 193 | new_output_asset_total_estimate.store(D.load()), 194 | For( 195 | i.store(Int(0)), i.load() < Int(255), i.store(i.load() + Int(1)) 196 | ).Do( 197 | Seq( 198 | new_output_asset_total_estimate_prev.store( 199 | new_output_asset_total_estimate.load() 200 | ), 201 | new_output_asset_total_estimate.store(estimate_calc), 202 | If( 203 | new_output_asset_total_estimate.load() 204 | > new_output_asset_total_estimate_prev.load() 205 | ) 206 | .Then( 207 | If( 208 | new_output_asset_total_estimate.load() 209 | - new_output_asset_total_estimate_prev.load() 210 | <= Int(1) 211 | ).Then(ret_calc) 212 | ) 213 | .Else( 214 | If( 215 | new_output_asset_total_estimate_prev.load() 216 | - new_output_asset_total_estimate.load() 217 | <= Int(1) 218 | ).Then(ret_calc) 219 | ), 220 | ) 221 | ), 222 | Assert(i.load() < Int(255)), # did not converge, throw error 223 | Return(Int(0)), # unreachable 224 | ) 225 | 226 | return calc 227 | 228 | 229 | @Subroutine(TealType.uint64) 230 | def interpolate_amplification_factor( 231 | initial_A: Expr, future_A: Expr, initial_A_time: Expr, future_A_time: Expr 232 | ): 233 | return Seq( 234 | If(Global.latest_timestamp() < future_A_time) 235 | .Then( 236 | If(future_A > initial_A) 237 | .Then( 238 | Return( 239 | initial_A 240 | + (future_A - initial_A) 241 | * (Global.latest_timestamp() - initial_A_time) 242 | / (future_A_time - initial_A_time) 243 | ) 244 | ) 245 | .Else( 246 | Return( 247 | initial_A 248 | - (initial_A - future_A) 249 | * (Global.latest_timestamp() - initial_A_time) 250 | / (future_A_time - initial_A_time) 251 | ) 252 | ) 253 | ) 254 | .Else(Return(future_A)) 255 | ) 256 | -------------------------------------------------------------------------------- /contracts/governance/subroutines.py: -------------------------------------------------------------------------------- 1 | """Global subroutines for governance contract.""" 2 | 3 | from inspect import currentframe 4 | 5 | from pyteal import * 6 | 7 | from contracts.governance.constants import DEV_MODE 8 | from contracts.governance.contract_strings import VotingEscrowStrings 9 | 10 | 11 | def MagicAssert(a): 12 | """Checks if a condition is true. If DEV_MODE is true, also returns the line number.""" 13 | if DEV_MODE: 14 | return Assert(And(a, Int(currentframe().f_back.f_lineno))) 15 | else: 16 | return Assert(a) 17 | 18 | 19 | @Subroutine(TealType.none) 20 | def verify_txn_is_payment_and_amount(idx, receiver, amount): 21 | """Verifies that a transaction is a payment transaction with a certain amount.""" 22 | return Seq( 23 | [ 24 | MagicAssert(Gtxn[idx].type_enum() == TxnType.Payment), 25 | MagicAssert(Gtxn[idx].receiver() == receiver), 26 | MagicAssert(Gtxn[idx].amount() >= amount), 27 | ] 28 | ) 29 | 30 | 31 | @Subroutine(TealType.none) 32 | def send_update_vebank_txn(target_account, ve_app_id): 33 | """Sends a transaction to update the vebank data.""" 34 | return Seq( 35 | InnerTxnBuilder.Begin(), 36 | InnerTxnBuilder.SetFields( 37 | { 38 | TxnField.sender: Global.current_application_address(), 39 | TxnField.application_id: ve_app_id, 40 | TxnField.type_enum: TxnType.ApplicationCall, 41 | TxnField.on_completion: OnComplete.NoOp, 42 | # txn.sender is the person creating the proposal 43 | TxnField.accounts: [target_account], 44 | TxnField.application_args: [ 45 | Bytes(VotingEscrowStrings.update_vebank_data) 46 | ], 47 | TxnField.fee: Int(0), 48 | } 49 | ), 50 | InnerTxnBuilder.Submit(), 51 | ) 52 | 53 | 54 | @Subroutine(TealType.none) 55 | def send_payment_txn(sender, receiver, amount): 56 | """Sends a payment transaction.""" 57 | return Seq( 58 | InnerTxnBuilder.Begin(), 59 | InnerTxnBuilder.SetFields( 60 | { 61 | TxnField.type_enum: TxnType.Payment, 62 | TxnField.sender: sender, 63 | TxnField.amount: amount, 64 | TxnField.receiver: receiver, 65 | TxnField.fee: Int(0), 66 | } 67 | ), 68 | InnerTxnBuilder.Submit(), 69 | ) 70 | 71 | 72 | @Subroutine(TealType.none) 73 | def send_payment_with_rekey_txn(sender, receiver, amount, rekey_address): 74 | """Sends a payment transaction with a rekey address.""" 75 | return Seq( 76 | InnerTxnBuilder.Begin(), 77 | InnerTxnBuilder.SetFields( 78 | { 79 | TxnField.type_enum: TxnType.Payment, 80 | TxnField.sender: sender, 81 | TxnField.amount: amount, 82 | TxnField.receiver: receiver, 83 | TxnField.fee: Int(0), 84 | TxnField.rekey_to: rekey_address, 85 | } 86 | ), 87 | InnerTxnBuilder.Submit(), 88 | ) 89 | 90 | 91 | def increment(var, amount): 92 | """Increments a variable by a certain amount.""" 93 | if type(var) == ScratchVar: 94 | return var.store(var.load() + amount) 95 | else: 96 | return var.put(var.get() + amount) 97 | 98 | 99 | def decrement(var, amount): 100 | """Decrements a variable by a certain amount.""" 101 | if type(var) == ScratchVar: 102 | return var.store(var.load() - amount) 103 | else: 104 | return var.put(var.get() - amount) 105 | 106 | 107 | def maximum(var1, var2): 108 | """Computes the maximum of two variables.""" 109 | return If(var1 > var2).Then(var1).Else(var2) 110 | 111 | 112 | def minimum(var1, var2): 113 | """Computes the minimum of two variables.""" 114 | return If(var1 < var2).Then(var1).Else(var2) 115 | 116 | 117 | # VALIDATION HELPER FUNCTIONS 118 | def verify_txn_is_named_application_call(idx, name): 119 | """Verifies that a transaction is a named application call.""" 120 | return Seq( 121 | [ 122 | MagicAssert(Gtxn[idx].on_completion() == OnComplete.NoOp), 123 | MagicAssert(Gtxn[idx].type_enum() == TxnType.ApplicationCall), 124 | MagicAssert( 125 | Gtxn[idx].application_id() == Global.current_application_id() 126 | ), 127 | MagicAssert(Gtxn[idx].application_args[0] == Bytes(name)), 128 | ] 129 | ) 130 | 131 | 132 | def verify_txn_is_sending_asa_to_contract(idx, asset_id): 133 | """Verifies that a transaction is sending an ASA to the contract.""" 134 | return Seq( 135 | [ 136 | MagicAssert(Gtxn[idx].type_enum() == TxnType.AssetTransfer), 137 | MagicAssert(Gtxn[idx].xfer_asset() == asset_id), 138 | MagicAssert( 139 | Gtxn[idx].asset_receiver() 140 | == Global.current_application_address() 141 | ), 142 | MagicAssert(Gtxn[idx].asset_amount() > Int(0)), 143 | ] 144 | ) 145 | 146 | 147 | @Subroutine(TealType.none) 148 | def verify_txn_is_payment(idx: Expr, receiver: Expr) -> Expr: 149 | """Verifies that a transaction is a payment transaction.""" 150 | return Seq( 151 | [ 152 | MagicAssert(Gtxn[idx].type_enum() == TxnType.Payment), 153 | MagicAssert(Gtxn[idx].receiver() == receiver), 154 | MagicAssert(Gtxn[idx].amount() > Int(0)), 155 | ] 156 | ) 157 | 158 | 159 | @Subroutine(TealType.none) 160 | def verify_txn_is_asset_transfer(idx: Expr, receiver: Expr, asset_id: Expr): 161 | """verifies that a transaction is an asset transfer.""" 162 | return Seq( 163 | [ 164 | MagicAssert(Gtxn[idx].type_enum() == TxnType.AssetTransfer), 165 | MagicAssert(Gtxn[idx].asset_receiver() == receiver), 166 | MagicAssert(Gtxn[idx].xfer_asset() == asset_id), 167 | MagicAssert(Gtxn[idx].asset_amount() > Int(0)), 168 | ] 169 | ) 170 | 171 | 172 | def verify_txn_is_named_no_op_application_call( 173 | idx, name, application_id=Global.current_application_id() 174 | ): 175 | """Verifies that a transaction is a named no-op application call.""" 176 | return Seq( 177 | [ 178 | MagicAssert(Gtxn[idx].type_enum() == TxnType.ApplicationCall), 179 | MagicAssert(Gtxn[idx].on_completion() == OnComplete.NoOp), 180 | MagicAssert(Gtxn[idx].application_id() == application_id), 181 | MagicAssert(Gtxn[idx].application_args[0] == Bytes(name)), 182 | ] 183 | ) 184 | 185 | 186 | def verify_txn_account(txn_idx, account_idx, expected_account): 187 | """Verifies that a transaction has a certain account.""" 188 | return MagicAssert(Gtxn[txn_idx].accounts[account_idx] == expected_account) 189 | 190 | 191 | # INNER TXN HELPERS 192 | 193 | 194 | @Subroutine(TealType.none) 195 | def send_asa(asset_id: Expr, amount: Expr, receiver: Expr) -> Expr: 196 | """Send an ASA.""" 197 | return Seq( 198 | [ 199 | InnerTxnBuilder.Begin(), 200 | InnerTxnBuilder.SetField( 201 | TxnField.type_enum, TxnType.AssetTransfer 202 | ), 203 | InnerTxnBuilder.SetField(TxnField.xfer_asset, asset_id), 204 | InnerTxnBuilder.SetField(TxnField.asset_amount, amount), 205 | InnerTxnBuilder.SetField(TxnField.asset_receiver, receiver), 206 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 207 | InnerTxnBuilder.Submit(), 208 | ] 209 | ) 210 | 211 | 212 | @Subroutine(TealType.none) 213 | def send_asa_from_address( 214 | sender: Expr, asset_id: Expr, amount: Expr, receiver: Expr 215 | ) -> Expr: 216 | """Send an ASA from a specified address.""" 217 | return Seq( 218 | [ 219 | InnerTxnBuilder.Begin(), 220 | InnerTxnBuilder.SetField(TxnField.sender, sender), 221 | InnerTxnBuilder.SetField( 222 | TxnField.type_enum, TxnType.AssetTransfer 223 | ), 224 | InnerTxnBuilder.SetField(TxnField.xfer_asset, asset_id), 225 | InnerTxnBuilder.SetField(TxnField.asset_amount, amount), 226 | InnerTxnBuilder.SetField(TxnField.asset_receiver, receiver), 227 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 228 | InnerTxnBuilder.Submit(), 229 | ] 230 | ) 231 | 232 | 233 | @Subroutine(TealType.none) 234 | def send_algo(amount: Expr, receiver: Expr) -> Expr: 235 | """Send Algo.""" 236 | return Seq( 237 | [ 238 | InnerTxnBuilder.Begin(), 239 | InnerTxnBuilder.SetField(TxnField.type_enum, TxnType.Payment), 240 | InnerTxnBuilder.SetField(TxnField.amount, amount), 241 | InnerTxnBuilder.SetField(TxnField.receiver, receiver), 242 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 243 | InnerTxnBuilder.Submit(), 244 | ] 245 | ) 246 | 247 | 248 | @Subroutine(TealType.none) 249 | def send_algo_from_address(sender: Expr, amount: Expr, receiver: Expr) -> Expr: 250 | """Send Algo from a specified address.""" 251 | return Seq( 252 | [ 253 | InnerTxnBuilder.Begin(), 254 | InnerTxnBuilder.SetField(TxnField.sender, sender), 255 | InnerTxnBuilder.SetField(TxnField.type_enum, TxnType.Payment), 256 | InnerTxnBuilder.SetField(TxnField.amount, amount), 257 | InnerTxnBuilder.SetField(TxnField.receiver, receiver), 258 | InnerTxnBuilder.SetField(TxnField.fee, Int(0)), 259 | InnerTxnBuilder.Submit(), 260 | ] 261 | ) 262 | 263 | 264 | def send_asa_set_fields(asa_id: Expr, receiver: Expr, amount: Expr): 265 | """Send an ASA.""" 266 | return InnerTxnBuilder.SetFields( 267 | { 268 | TxnField.type_enum: TxnType.AssetTransfer, 269 | TxnField.xfer_asset: asa_id, 270 | TxnField.asset_receiver: receiver, 271 | TxnField.asset_amount: amount, 272 | TxnField.fee: Int(0), 273 | } 274 | ) 275 | 276 | 277 | # TODO can we change this from "into" to "into" globally 278 | @Subroutine(TealType.none) 279 | def opt_into_asa(id: Expr) -> Expr: 280 | """Opts into an ASA.""" 281 | return send_asa(id, Int(0), Global.current_application_address()) 282 | -------------------------------------------------------------------------------- /contracts/governance/proposal_factory.py: -------------------------------------------------------------------------------- 1 | """Contains the ProposalFactory class, which is the contract that users interact with to create proposals.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.governance.constants import * 6 | from contracts.governance.contract_strings import ( 7 | ProposalFactoryStrings, 8 | ProposalStrings, 9 | VotingEscrowStrings, 10 | ) 11 | from contracts.governance.subroutines import * 12 | from contracts.utils.wrapped_var import * 13 | 14 | 15 | # Subroutines 16 | @Subroutine(TealType.none) 17 | def create_proposal_from_template_and_optin( 18 | approval_program_proposal, 19 | clear_state_program_proposal, 20 | admin_app_id, 21 | title, 22 | link, 23 | proposer, 24 | proposer_admin_storage_account, 25 | ): 26 | """Creates a proposal from the proposal template and opts it into the admin contract.""" 27 | proposal_app_id_scratch = ScratchVar(TealType.uint64) 28 | proposal_app_id = Gitxn[0].created_application_id() 29 | proposal_app_address = AppParam.address(proposal_app_id) 30 | 31 | return Seq( 32 | # creating the proposal 33 | InnerTxnBuilder.Begin(), 34 | InnerTxnBuilder.SetFields( 35 | { 36 | TxnField.type_enum: TxnType.ApplicationCall, 37 | TxnField.approval_program: approval_program_proposal, 38 | TxnField.clear_state_program: clear_state_program_proposal, 39 | TxnField.global_num_byte_slices: GLOBAL_BYTES_PROPOSAL_CONTRACT, 40 | TxnField.global_num_uints: GLOBAL_INTS_PROPOSAL_CONTRACT, 41 | TxnField.local_num_byte_slices: LOCAL_BYTES_PROPOSAL_CONTRACT, 42 | TxnField.local_num_uints: LOCAL_INTS_PROPOSAL_CONTRACT, 43 | TxnField.application_args: [title, link], 44 | TxnField.fee: Int(0), 45 | } 46 | ), 47 | InnerTxnBuilder.Submit(), 48 | # make sure the proposal was created correctly 49 | MagicAssert(proposal_app_id > Int(0)), 50 | proposal_app_id_scratch.store(proposal_app_id), 51 | # getting the address so that we can determine minimum balances 52 | proposal_app_address, 53 | MagicAssert(proposal_app_address.hasValue()), 54 | InnerTxnBuilder.Begin(), 55 | InnerTxnBuilder.SetFields( 56 | { 57 | TxnField.type_enum: TxnType.Payment, 58 | TxnField.amount: MIN_BALANCE_PROPOSAL, 59 | TxnField.receiver: proposal_app_address.value(), 60 | TxnField.fee: Int(0), 61 | } 62 | ), 63 | InnerTxnBuilder.Next(), 64 | # opt the proposal contract into the admin 65 | InnerTxnBuilder.SetFields( 66 | { 67 | TxnField.type_enum: TxnType.ApplicationCall, 68 | TxnField.application_id: proposal_app_id_scratch.load(), 69 | TxnField.application_args: [ 70 | Bytes(ProposalStrings.opt_into_admin) 71 | ], 72 | TxnField.applications: [admin_app_id], 73 | TxnField.accounts: [proposer, proposer_admin_storage_account], 74 | TxnField.fee: Int(0), 75 | } 76 | ), 77 | InnerTxnBuilder.Submit(), 78 | ) 79 | 80 | 81 | class User: 82 | """Defines a user of the proposal factory.""" 83 | 84 | def __init__(self, user_account, voting_escrow_app_id): 85 | self.account = user_account 86 | 87 | # USER STATE 88 | self.current_ve_bank = WrappedVar( 89 | VotingEscrowStrings.user_amount_vebank, 90 | LOCAL_EX_VAR, 91 | user_account, 92 | voting_escrow_app_id, 93 | ).get() 94 | 95 | def load_ve_bank(self): 96 | """Loads the user's ve bank.""" 97 | return Seq( 98 | [ 99 | self.current_ve_bank, 100 | MagicAssert(self.current_ve_bank.hasValue()), 101 | ] 102 | ) 103 | 104 | 105 | class ProposalFactory: 106 | """Defines the proposal factory contract.""" 107 | 108 | def __init__(self): 109 | # SCRATCH VARS 110 | self.min_balance_store = ScratchVar( 111 | TealType.uint64, ProposalFactoryScratchSlots.min_balance 112 | ) 113 | 114 | # GLOBAL BYTES 115 | self.dao_address = WrappedVar( 116 | ProposalFactoryStrings.dao_address, GLOBAL_VAR 117 | ) 118 | self.emergency_dao_address = WrappedVar( 119 | ProposalFactoryStrings.emergency_dao_address, GLOBAL_VAR 120 | ) 121 | 122 | # GLOBAL INTS 123 | self.gov_token = WrappedVar( 124 | ProposalFactoryStrings.gov_token, GLOBAL_VAR 125 | ) 126 | self.voting_escrow_app_id = WrappedVar( 127 | ProposalFactoryStrings.voting_escrow_app_id, GLOBAL_VAR 128 | ) 129 | self.proposal_template = WrappedVar( 130 | ProposalFactoryStrings.proposal_template, GLOBAL_VAR 131 | ) 132 | self.minimum_ve_bank_to_propose = WrappedVar( 133 | ProposalFactoryStrings.minimum_ve_bank_to_propose, GLOBAL_VAR 134 | ) 135 | self.admin_app_id = WrappedVar( 136 | ProposalFactoryStrings.admin_app_id, GLOBAL_VAR 137 | ) 138 | 139 | # DERIVED VALUES 140 | self.proposal_approval_program = AppParam.approvalProgram( 141 | self.proposal_template.get() 142 | ) 143 | self.proposal_clear_state_program = AppParam.clearStateProgram( 144 | self.proposal_template.get() 145 | ) 146 | 147 | # HELPER CLASSES 148 | self.user = User( 149 | Txn.accounts[1], 150 | voting_escrow_app_id=self.voting_escrow_app_id.get(), 151 | ) 152 | 153 | # HELPER FUNCTIONS 154 | 155 | def load_proposal_template(self): 156 | """Loads the proposal template.""" 157 | return Seq( 158 | [ 159 | self.proposal_approval_program, 160 | self.proposal_clear_state_program, 161 | MagicAssert(self.proposal_approval_program.hasValue()), 162 | MagicAssert(self.proposal_clear_state_program.hasValue()), 163 | ] 164 | ) 165 | 166 | # CREATION 167 | 168 | def on_creation(self): 169 | """Called when the contract is created.""" 170 | minimum_ve_bank_to_propose = Btoi(Txn.application_args[0]) 171 | dao_address = Txn.accounts[1] 172 | emergency_dao_address = Txn.accounts[2] 173 | voting_escrow_app_id = Txn.applications[1] 174 | proposal_template = Txn.applications[2] 175 | admin_app_id = Txn.applications[3] 176 | 177 | return Seq( 178 | [ 179 | # setting dao address 180 | self.dao_address.put(dao_address), 181 | # setting emergency dao address 182 | self.emergency_dao_address.put(emergency_dao_address), 183 | # setting minimum ve bank to propose 184 | self.minimum_ve_bank_to_propose.put( 185 | minimum_ve_bank_to_propose 186 | ), 187 | # setting voting escrow app id 188 | self.voting_escrow_app_id.put(voting_escrow_app_id), 189 | # setting proposal template 190 | self.proposal_template.put(proposal_template), 191 | # setting admin app id 192 | self.admin_app_id.put(admin_app_id), 193 | Approve(), 194 | ] 195 | ) 196 | 197 | # ADMIN 198 | 199 | def on_set_voting_escrow_app_id(self): 200 | """Sets the voting escrow app id.""" 201 | voting_escrow_app_id = Txn.applications[1] 202 | 203 | return Seq( 204 | self.voting_escrow_app_id.put(voting_escrow_app_id), Approve() 205 | ) 206 | 207 | def on_set_admin_app_id(self): 208 | """Sets the admin app id.""" 209 | admin_app_id = Txn.applications[1] 210 | 211 | return Seq(self.admin_app_id.put(admin_app_id), Approve()) 212 | 213 | def on_set_proposal_template(self): 214 | """Sets the proposal template.""" 215 | proposal_template = Txn.applications[1] 216 | 217 | return Seq(self.proposal_template.put(proposal_template), Approve()) 218 | 219 | def on_set_minimum_ve_bank_to_propose(self): 220 | """Sets the minimum ve bank to propose.""" 221 | new_minimum_ve_bank_to_propose = Btoi(Txn.application_args[1]) 222 | 223 | return Seq( 224 | self.minimum_ve_bank_to_propose.put( 225 | new_minimum_ve_bank_to_propose 226 | ), 227 | Approve(), 228 | ) 229 | 230 | # USER FUNCTIONS 231 | 232 | def on_create_proposal(self): 233 | """Creates a proposal.""" 234 | # application args 235 | title = Txn.application_args[1] 236 | link = Txn.application_args[2] 237 | 238 | # user admin storage account 239 | user_admin_storage_account = Txn.accounts[2] 240 | 241 | # min balance state 242 | min_balance = MinBalance(Global.current_application_address()) 243 | min_balance_delta = min_balance - self.min_balance_store.load() 244 | 245 | return Seq( 246 | [ 247 | # check previous transaction was to this app with user for ledger compatibility 248 | verify_txn_is_named_no_op_application_call( 249 | PREVIOUS_TRANSACTION, 250 | ProposalFactoryStrings.validate_user_account, 251 | ), 252 | # verify sender of previous txn is the foreign account 253 | verify_txn_account(PREVIOUS_TRANSACTION, 0, self.user.account), 254 | # sending the update ve bank transaction 255 | send_update_vebank_txn( 256 | self.user.account, self.voting_escrow_app_id.get() 257 | ), 258 | # load user ve bank 259 | self.user.load_ve_bank(), 260 | # load proposal template 261 | self.load_proposal_template(), 262 | # verify user has sufficient ve bank 263 | MagicAssert( 264 | self.user.current_ve_bank.value() 265 | > self.minimum_ve_bank_to_propose.get() 266 | ), 267 | # cache min balance 268 | self.min_balance_store.store(min_balance), 269 | # creating the proposal 270 | create_proposal_from_template_and_optin( 271 | self.proposal_approval_program.value(), 272 | self.proposal_clear_state_program.value(), 273 | self.admin_app_id.get(), 274 | title, 275 | link, 276 | self.user.account, 277 | user_admin_storage_account, 278 | ), 279 | # verify min balance was funded 280 | verify_txn_is_payment_and_amount( 281 | TWO_PREVIOUS_TRANSACTION, 282 | Global.current_application_address(), 283 | min_balance_delta + MIN_BALANCE_PROPOSAL, 284 | ), 285 | Approve(), 286 | ] 287 | ) 288 | 289 | # APPROVAL 290 | 291 | def approval_program(self): 292 | """The proposal factory approval program.""" 293 | 294 | # sender checks 295 | sender_is_dao = Or( 296 | Txn.sender() == self.dao_address.get(), 297 | Txn.sender() == self.emergency_dao_address.get(), 298 | ) 299 | # check on complete 300 | is_delete_application = ( 301 | Txn.on_completion() == OnComplete.DeleteApplication 302 | ) 303 | is_no_op = Txn.on_completion() == OnComplete.NoOp 304 | is_opt_in = Txn.on_completion() == OnComplete.OptIn 305 | is_close_out = Txn.on_completion() == OnComplete.CloseOut 306 | # type of call 307 | type_of_call = Txn.application_args[0] 308 | 309 | program = Cond( 310 | [Txn.application_id() == Int(0), self.on_creation()], 311 | [is_delete_application, Reject()], 312 | [is_opt_in, Reject()], 313 | [is_close_out, Reject()], 314 | # dao functions 315 | [ 316 | sender_is_dao, 317 | Cond( 318 | [ 319 | is_no_op, 320 | Cond( 321 | [ 322 | type_of_call 323 | == Bytes( 324 | ProposalFactoryStrings.set_proposal_template 325 | ), 326 | self.on_set_proposal_template(), 327 | ], 328 | [ 329 | type_of_call 330 | == Bytes( 331 | ProposalFactoryStrings.set_voting_escrow_app_id 332 | ), 333 | self.on_set_voting_escrow_app_id(), 334 | ], 335 | [ 336 | type_of_call 337 | == Bytes( 338 | ProposalFactoryStrings.set_admin_app_id 339 | ), 340 | self.on_set_admin_app_id(), 341 | ], 342 | [ 343 | type_of_call 344 | == Bytes( 345 | ProposalFactoryStrings.set_minimum_ve_bank_to_propose 346 | ), 347 | self.on_set_minimum_ve_bank_to_propose(), 348 | ], 349 | ), 350 | ] 351 | ), 352 | ], 353 | # user functions 354 | [ 355 | is_no_op, 356 | Cond( 357 | [ 358 | type_of_call 359 | == Bytes( 360 | ProposalFactoryStrings.validate_user_account 361 | ), 362 | Approve(), 363 | ], 364 | [ 365 | type_of_call 366 | == Bytes(ProposalFactoryStrings.create_proposal), 367 | self.on_create_proposal(), 368 | ], 369 | ), 370 | ], 371 | ) 372 | 373 | return program 374 | 375 | def clear_state_program(self): 376 | return Approve() 377 | -------------------------------------------------------------------------------- /contracts/amm/manager.py: -------------------------------------------------------------------------------- 1 | """Manager contract for the AMM.""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.amm.constants import ( 6 | DEFAULT_RESERVE_FACTOR, 7 | FIXED_6_SCALE_FACTOR, 8 | INIT_FLASH_LOAN_FEE, 9 | INIT_MAX_FLASH_LOAN_RATIO, 10 | MAX_VALIDATOR_COUNT, 11 | N_FUND_LOGIC_SIG_TXN, 12 | N_FUND_MANAGER_TXN, 13 | N_INITIALIZE_POOL_TXN, 14 | N_OPT_IN_LOGIC_SIG_TXN, 15 | ) 16 | from contracts.amm.contract_strings import * 17 | from contracts.amm.subroutines import send_algo_to_receiver 18 | from contracts.utils.wrapped_var import * 19 | 20 | 21 | class AMMPoolManagerRegistrant: 22 | """A helper class to represent the global state of a pool manager registrant.""" 23 | 24 | def __init__(self): 25 | self.registered_pool_id = WrappedVar( 26 | AMMManagerStrings.registered_pool_id, LOCAL_VAR, Int(0) 27 | ) 28 | self.registered_asset_1_id = WrappedVar( 29 | AMMManagerStrings.registered_asset_1_id, LOCAL_VAR, Int(0) 30 | ) 31 | self.registered_asset_2_id = WrappedVar( 32 | AMMManagerStrings.registered_asset_2_id, LOCAL_VAR, Int(0) 33 | ) 34 | self.validator_index = WrappedVar( 35 | AMMManagerStrings.validator_index, LOCAL_VAR, Int(0) 36 | ) 37 | 38 | 39 | class AMMPoolManagerPool: 40 | """A helper class to access the represent the global state of a pool manager.""" 41 | 42 | def __init__(self, pool_application_id): 43 | self.admin = WrappedVar( 44 | AMMPoolStrings.admin, 45 | GLOBAL_EX_VAR, 46 | pool_application_id.load(), 47 | ).get() 48 | self.asset_1_id = WrappedVar( 49 | AMMPoolStrings.asset1_id, 50 | GLOBAL_EX_VAR, 51 | pool_application_id.load(), 52 | ).get() 53 | self.asset_2_id = WrappedVar( 54 | AMMPoolStrings.asset2_id, 55 | GLOBAL_EX_VAR, 56 | pool_application_id.load(), 57 | ).get() 58 | self.validator_index = WrappedVar( 59 | AMMPoolStrings.validator_index, 60 | GLOBAL_EX_VAR, 61 | pool_application_id.load(), 62 | ).get() 63 | 64 | 65 | class AMMPoolManagerPoolValidator: 66 | """A helper class to access the represent the global state of a pool validator.""" 67 | 68 | def __init__(self, validator_index): 69 | self.pool_hash = WrappedVar( 70 | Concat( 71 | Bytes(AMMManagerStrings.pool_hash_prefix), 72 | Itob(validator_index.load()), 73 | ), 74 | GLOBAL_VAR, 75 | name_to_bytes=False, 76 | ) 77 | 78 | 79 | class AMMPoolManager: 80 | """A class to represent the AMM Manager contract.""" 81 | 82 | def __init__(self): 83 | # SCRATCH VARS 84 | self.pool_validator_index_store = ScratchVar(TealType.uint64, 0) 85 | self.pool_application_id_store = ScratchVar(TealType.uint64, 1) 86 | 87 | # STATE VARS 88 | self.admin = WrappedVar(AMMManagerStrings.admin, GLOBAL_VAR) 89 | self.reserve_factor = WrappedVar( 90 | AMMManagerStrings.reserve_factor, GLOBAL_VAR 91 | ) 92 | self.flash_loan_fee = WrappedVar( 93 | AMMManagerStrings.flash_loan_fee, GLOBAL_VAR 94 | ) 95 | self.max_flash_loan_ratio = WrappedVar( 96 | AMMManagerStrings.max_flash_loan_ratio, GLOBAL_VAR 97 | ) 98 | 99 | # HELPER CLASSES 100 | self.registrant = AMMPoolManagerRegistrant() 101 | self.pool = AMMPoolManagerPool(self.pool_application_id_store) 102 | self.validator = AMMPoolManagerPoolValidator( 103 | self.pool_validator_index_store 104 | ) 105 | 106 | def on_creation(self): 107 | """A method called at smart contract creation.""" 108 | return Seq( 109 | [ 110 | self.admin.put(Global.creator_address()), 111 | self.reserve_factor.put(DEFAULT_RESERVE_FACTOR), 112 | self.flash_loan_fee.put(INIT_FLASH_LOAN_FEE), 113 | self.max_flash_loan_ratio.put(INIT_MAX_FLASH_LOAN_RATIO), 114 | Int(1), 115 | ] 116 | ) 117 | 118 | # ADMIN FUNCTIONS 119 | 120 | def on_set_reserve_factor(self): 121 | """A method called by the admin to set the reserve factor.""" 122 | 123 | new_reserve_factor = Btoi(Txn.application_args[1]) 124 | sender_is_admin = Txn.sender() == self.admin.get() 125 | 126 | return Seq( 127 | [ 128 | Assert(sender_is_admin), 129 | # check that we are increasing the min_scheduled_param_update_delay 130 | Assert(new_reserve_factor <= FIXED_6_SCALE_FACTOR), 131 | # update min_scheduled_param_update_delay 132 | self.reserve_factor.put(new_reserve_factor), 133 | Int(1), 134 | ] 135 | ) 136 | 137 | def on_set_flash_loan_fee(self): 138 | """A method called by the admin to set the flash loan fee.""" 139 | 140 | flash_loan_fee = Btoi(Txn.application_args[1]) 141 | sender_is_admin = Txn.sender() == self.admin.get() 142 | 143 | return Seq( 144 | [ 145 | Assert(sender_is_admin), 146 | # check that we are increasing the min_scheduled_param_update_delay 147 | Assert(flash_loan_fee <= FIXED_6_SCALE_FACTOR), 148 | # update min_scheduled_param_update_delay 149 | self.flash_loan_fee.put(flash_loan_fee), 150 | Int(1), 151 | ] 152 | ) 153 | 154 | def on_set_max_flash_loan_ratio(self): 155 | """A method called by the admin to set the max flash loan ratio.""" 156 | 157 | max_flash_loan_ratio = Btoi(Txn.application_args[1]) 158 | sender_is_admin = Txn.sender() == self.admin.get() 159 | 160 | return Seq( 161 | [ 162 | Assert(sender_is_admin), 163 | # check that we are increasing the min_scheduled_param_update_delay 164 | Assert(max_flash_loan_ratio <= FIXED_6_SCALE_FACTOR), 165 | # update min_scheduled_param_update_delay 166 | self.max_flash_loan_ratio.put(max_flash_loan_ratio), 167 | Int(1), 168 | ] 169 | ) 170 | 171 | def on_set_validator(self): 172 | """A method called by the admin to set the validator for a pool.""" 173 | 174 | validator_index = Btoi(Txn.application_args[1]) 175 | approval_program_hash = Txn.application_args[2] 176 | sender_is_admin = Txn.sender() == self.admin.get() 177 | 178 | return Seq( 179 | [ 180 | Assert(sender_is_admin), 181 | Assert(validator_index < MAX_VALIDATOR_COUNT), 182 | self.pool_validator_index_store.store(validator_index), 183 | self.validator.pool_hash.put(approval_program_hash), 184 | Int(1), 185 | ] 186 | ) 187 | 188 | # LOGIC SIG OPTIN 189 | 190 | def on_user_opt_in(self): 191 | """ 192 | 193 | A method called during the user opt in process. 194 | 195 | This method is responsible for validating the group transaction structure 196 | and the transaction parameters. 197 | """ 198 | 199 | asset_1_id = Btoi(Txn.application_args[0]) 200 | asset_2_id = Btoi(Txn.application_args[1]) 201 | validator_index = Btoi(Txn.application_args[2]) 202 | 203 | pool_application_id = Gtxn[N_INITIALIZE_POOL_TXN].application_id() 204 | pool_approval_program = AppParam.approvalProgram(pool_application_id) 205 | pool_approval_program_hash = Sha256(pool_approval_program.value()) 206 | pool_clear_state_program = AppParam.clearStateProgram( 207 | pool_application_id 208 | ) 209 | 210 | manager_clear_state_program = AppParam.clearStateProgram( 211 | Global.current_application_id() 212 | ) 213 | 214 | def validate_group_structure(): 215 | """A method to verify the group transaction structure.""" 216 | return Seq( 217 | [ 218 | Assert(Global.group_size() == Int(4)), 219 | Assert(Txn.group_index() == Int(N_OPT_IN_LOGIC_SIG_TXN)), 220 | ] 221 | ) 222 | 223 | def validate_fund_manager_txn(): 224 | """A method to verify the funding transaction.""" 225 | return Seq( 226 | [ 227 | Assert( 228 | Gtxn[N_FUND_MANAGER_TXN].receiver() 229 | == Global.current_application_address() 230 | ), 231 | Assert( 232 | Gtxn[N_FUND_MANAGER_TXN].type_enum() == TxnType.Payment 233 | ), 234 | Assert(Gtxn[N_FUND_MANAGER_TXN].amount() == Int(400000)), 235 | ] 236 | ) 237 | 238 | def validate_fund_logic_sig_txn(): 239 | """A method to verify the logic signature transaction.""" 240 | return Seq( 241 | [ 242 | Assert( 243 | Gtxn[N_FUND_LOGIC_SIG_TXN].receiver() == Txn.sender() 244 | ), 245 | Assert( 246 | Gtxn[N_FUND_LOGIC_SIG_TXN].type_enum() 247 | == TxnType.Payment 248 | ), 249 | Assert(Gtxn[N_FUND_LOGIC_SIG_TXN].amount() == Int(450000)), 250 | ] 251 | ) 252 | 253 | def validate_pool_initialization_txn(): 254 | """A method to verify the pool initialization transaction.""" 255 | return Seq( 256 | [ 257 | Assert( 258 | Gtxn[N_INITIALIZE_POOL_TXN].type_enum() 259 | == TxnType.ApplicationCall 260 | ), 261 | Assert( 262 | Gtxn[N_INITIALIZE_POOL_TXN].on_completion() 263 | == OnComplete.NoOp 264 | ), 265 | Assert( 266 | Gtxn[N_INITIALIZE_POOL_TXN].application_args[0] 267 | == Bytes(AMMPoolStrings.initialize_pool) 268 | ), 269 | ] 270 | ) 271 | 272 | def validate_pool_state(): 273 | """A method to verify the pool state.""" 274 | return Seq( 275 | [ 276 | Assert(asset_1_id < asset_2_id), 277 | self.pool_application_id_store.store(pool_application_id), 278 | self.pool.admin, 279 | Assert(self.pool.admin.hasValue()), 280 | self.pool.asset_1_id, 281 | Assert(self.pool.asset_1_id.hasValue()), 282 | self.pool.asset_2_id, 283 | Assert(self.pool.asset_2_id.hasValue()), 284 | self.pool.validator_index, 285 | Assert(self.pool.validator_index.hasValue()), 286 | Assert(self.pool.admin.value() == self.admin.get()), 287 | Assert(self.pool.asset_1_id.value() == asset_1_id), 288 | Assert(self.pool.asset_2_id.value() == asset_2_id), 289 | Assert( 290 | self.pool.validator_index.value() == validator_index 291 | ), 292 | ] 293 | ) 294 | 295 | def validate_pool_program(): 296 | """A method to verify the pool program.""" 297 | return Seq( 298 | [ 299 | self.pool_validator_index_store.store(validator_index), 300 | pool_approval_program, 301 | Assert(pool_approval_program.hasValue()), 302 | Assert( 303 | self.validator.pool_hash.get() 304 | == pool_approval_program_hash 305 | ), 306 | pool_clear_state_program, 307 | Assert(pool_clear_state_program.hasValue()), 308 | manager_clear_state_program, 309 | Assert(manager_clear_state_program.hasValue()), 310 | Assert( 311 | pool_clear_state_program.value() 312 | == manager_clear_state_program.value() 313 | ), 314 | ] 315 | ) 316 | 317 | def fund_pool(): 318 | """A method to fund the pool with initial algos.""" 319 | return Seq( 320 | [ 321 | # TODO will need to find a better way to do this in AVM 1.1 but this works for now 322 | send_algo_to_receiver(Int(400000), Txn.accounts[1]) 323 | ] 324 | ) 325 | 326 | def set_registrant_local_state(): 327 | """A method to set the registrant's local state.""" 328 | return Seq( 329 | [ 330 | self.registrant.registered_pool_id.put( 331 | pool_application_id 332 | ), 333 | self.registrant.registered_asset_1_id.put(asset_1_id), 334 | self.registrant.registered_asset_2_id.put(asset_2_id), 335 | self.registrant.validator_index.put(validator_index), 336 | ] 337 | ) 338 | 339 | return Seq( 340 | [ 341 | # validate group transaction composition 342 | validate_group_structure(), 343 | validate_fund_manager_txn(), 344 | validate_fund_logic_sig_txn(), 345 | validate_pool_initialization_txn(), 346 | # validate target pool approval program and state 347 | validate_pool_program(), 348 | validate_pool_state(), 349 | # fund target pool algos so it can create its LP token on initialization 350 | fund_pool(), 351 | # register pool info in this logic sig's local state 352 | set_registrant_local_state(), 353 | Int(1), 354 | ] 355 | ) 356 | 357 | def approval_program(self): 358 | """ 359 | The approval program logic for the AMM Manager contract. 360 | 361 | A conditional over the transaction type and parameters is used 362 | to route the transaction to the appropriate method. 363 | """ 364 | 365 | sender_is_admin = Txn.sender() == self.admin.get() 366 | is_no_op_appl_call = And( 367 | Txn.on_completion() == OnComplete.NoOp, 368 | Txn.type_enum() == TxnType.ApplicationCall, 369 | ) 370 | 371 | return Cond( 372 | [Txn.application_id() == Int(0), self.on_creation()], 373 | [Txn.on_completion() == OnComplete.DeleteApplication, Int(0)], 374 | [ 375 | Txn.on_completion() == OnComplete.OptIn, 376 | self.on_user_opt_in(), 377 | ], # opt in pool 378 | [Txn.on_completion() == OnComplete.CloseOut, Int(0)], 379 | # admin calls 380 | [ 381 | sender_is_admin, 382 | Cond( 383 | [ 384 | is_no_op_appl_call, 385 | Cond( 386 | [ 387 | Txn.application_args[0] 388 | == Bytes( 389 | AMMManagerStrings.set_validator 390 | ), 391 | self.on_set_validator(), 392 | ], 393 | [ 394 | Txn.application_args[0] 395 | == Bytes( 396 | AMMManagerStrings.set_reserve_factor 397 | ), 398 | self.on_set_reserve_factor(), 399 | ], 400 | [ 401 | Txn.application_args[0] 402 | == Bytes( 403 | AMMManagerStrings.set_flash_loan_fee 404 | ), 405 | self.on_set_flash_loan_fee(), 406 | ], 407 | [ 408 | Txn.application_args[0] 409 | == Bytes( 410 | AMMManagerStrings.set_max_flash_loan_ratio 411 | ), 412 | self.on_set_max_flash_loan_ratio(), 413 | ], 414 | ), 415 | ], 416 | ), 417 | ], 418 | [ 419 | And( 420 | Txn.on_completion() == OnComplete.NoOp, 421 | Txn.application_args[0] 422 | == Bytes(AMMManagerStrings.farm_ops), 423 | ), 424 | Int(1), 425 | ], 426 | ) 427 | -------------------------------------------------------------------------------- /contracts/governance/voting_escrow.py: -------------------------------------------------------------------------------- 1 | """Vote Escrow Contract""" 2 | 3 | from pyteal import * 4 | 5 | from contracts.governance.constants import * 6 | from contracts.governance.contract_strings import VotingEscrowStrings 7 | from contracts.governance.subroutines import ( 8 | MagicAssert, 9 | decrement, 10 | increment, 11 | opt_into_asa, 12 | send_asa, 13 | verify_txn_is_sending_asa_to_contract, 14 | ) 15 | from contracts.utils.wrapped_var import * 16 | 17 | 18 | class VotingEscrowUser: 19 | """Data structure for user state in the voting escrow contract""" 20 | 21 | def __init__(self, user_index): 22 | # LOCAL STATE 23 | self.amount_locked = WrappedVar( 24 | VotingEscrowStrings.user_amount_locked, LOCAL_VAR, user_index 25 | ) 26 | self.lock_start_time = WrappedVar( 27 | VotingEscrowStrings.user_lock_start_time, 28 | LOCAL_VAR, 29 | user_index, 30 | ) 31 | self.lock_duration = WrappedVar( 32 | VotingEscrowStrings.user_lock_duration, LOCAL_VAR, user_index 33 | ) 34 | self.amount_vebank = WrappedVar( 35 | VotingEscrowStrings.user_amount_vebank, LOCAL_VAR, user_index 36 | ) 37 | self.boost_multiplier = WrappedVar( 38 | VotingEscrowStrings.user_boost_multiplier, 39 | LOCAL_VAR, 40 | user_index, 41 | ) 42 | self.update_time = WrappedVar( 43 | VotingEscrowStrings.user_last_update_time, 44 | LOCAL_VAR, 45 | user_index, 46 | ) 47 | 48 | def get_lock_end_time(self): 49 | """Get the time at which the lock expires""" 50 | return self.lock_start_time.get() + self.lock_duration.get() 51 | 52 | 53 | class VotingEscrow: 54 | """Vote Escrow Contract""" 55 | 56 | def __init__(self): 57 | # GLOBAL STATE 58 | self.dao_address = WrappedVar( 59 | VotingEscrowStrings.dao_address, GLOBAL_VAR 60 | ) 61 | self.emergency_dao_address = WrappedVar( 62 | VotingEscrowStrings.emergency_dao_address, GLOBAL_VAR 63 | ) 64 | self.asset_id = WrappedVar( 65 | VotingEscrowStrings.asset_id, GLOBAL_VAR 66 | ) 67 | self.total_locked = WrappedVar( 68 | VotingEscrowStrings.total_locked, GLOBAL_VAR 69 | ) 70 | self.total_vebank = WrappedVar( 71 | VotingEscrowStrings.total_vebank, GLOBAL_VAR 72 | ) 73 | self.admin_contract_app_id = WrappedVar( 74 | VotingEscrowStrings.admin_contract_app_id, GLOBAL_VAR 75 | ) 76 | 77 | # HELPER CLASSES 78 | self.sending_user = VotingEscrowUser(Int(0)) 79 | self.target_user = VotingEscrowUser(Int(1)) 80 | 81 | # CREATION 82 | 83 | def on_creation(self): 84 | """Creates the voting escrow contract""" 85 | dao_address = Txn.accounts[1] 86 | emergency_dao_address = Txn.accounts[2] 87 | 88 | return Seq( 89 | # set dao address 90 | self.dao_address.put(dao_address), 91 | # set emergency dao address 92 | self.emergency_dao_address.put(emergency_dao_address), 93 | self.total_vebank.put(ZERO_AMOUNT), 94 | self.total_locked.put(ZERO_AMOUNT), 95 | Approve(), 96 | ) 97 | 98 | # ADMIN 99 | 100 | def on_set_admin_contract_app_id(self): 101 | """Sets the admin contract app id""" 102 | admin_contract_app_id = Txn.applications[1] 103 | 104 | return Seq( 105 | # set new rewards manager app id 106 | self.admin_contract_app_id.put(admin_contract_app_id), 107 | Approve(), 108 | ) 109 | 110 | def on_set_gov_token_id(self): 111 | """Sets the gov token id""" 112 | return Seq( 113 | # set gov token id 114 | self.asset_id.put(Txn.assets[0]), 115 | # opt into gov asset 116 | opt_into_asa(self.asset_id.get()), 117 | Approve(), 118 | ) 119 | 120 | # OPT IN / CLOSE OUT 121 | 122 | def on_opt_in(self): 123 | """Called on opt in""" 124 | return Seq( 125 | MagicAssert(Gtxn[PREVIOUS_TRANSACTION].sender() == Txn.sender()), 126 | MagicAssert( 127 | Gtxn[PREVIOUS_TRANSACTION].application_id() 128 | == self.admin_contract_app_id.get() 129 | ), 130 | MagicAssert( 131 | Gtxn[PREVIOUS_TRANSACTION].on_completion() == OnComplete.OptIn 132 | ), 133 | Approve(), 134 | ) 135 | 136 | def on_close_out(self): 137 | """Called on close out""" 138 | return Seq( 139 | # assert user has no locked bank 140 | MagicAssert(self.sending_user.amount_locked.get() == ZERO_AMOUNT), 141 | Approve(), 142 | ) 143 | 144 | # HELPER FUNCTIONS 145 | 146 | def calculate_vebank_amount(self, amount_locked, time_remaining): 147 | """Calculates the amount of veBANK a user has""" 148 | return WideRatio([amount_locked, time_remaining], [SECONDS_PER_YEAR]) 149 | 150 | def update_boost(self, user: VotingEscrowUser): 151 | """Updates the user's boost""" 152 | return Seq( 153 | [ 154 | If(self.total_vebank.get() > ZERO_AMOUNT) 155 | .Then( 156 | user.boost_multiplier.put( 157 | WideRatio( 158 | [user.amount_vebank.get(), FIXED_12_SCALE_FACTOR], 159 | [self.total_vebank.get()], 160 | ) 161 | ) 162 | ) 163 | .Else(user.boost_multiplier.put(ZERO_AMOUNT)) 164 | ] 165 | ) 166 | 167 | def update_vebank_data(self, user: VotingEscrowUser): 168 | """Updates a user's veBANK data""" 169 | current_time = Global.latest_timestamp() 170 | time_delta = current_time - user.update_time.get() 171 | lock_end_time = user.get_lock_end_time() 172 | lock_time_remaining = lock_end_time - current_time 173 | 174 | on_update = Seq( 175 | # update user state if time_delta is non zero 176 | If(time_delta > ZERO_AMOUNT).Then( 177 | Seq( 178 | # decrement user vebank from total 179 | decrement(self.total_vebank, user.amount_vebank.get()), 180 | # recalculate user vebank amount 181 | If(current_time > lock_end_time) 182 | .Then( 183 | user.amount_vebank.put(ZERO_AMOUNT), 184 | ) 185 | .Else( 186 | Seq( 187 | user.amount_vebank.put( 188 | self.calculate_vebank_amount( 189 | user.amount_locked.get(), 190 | lock_time_remaining, 191 | ) 192 | ), 193 | # increment new user vebank to total 194 | increment( 195 | self.total_vebank, user.amount_vebank.get() 196 | ), 197 | ), 198 | ), 199 | # recalculate user boost 200 | self.update_boost(user), 201 | # update user latest update time 202 | user.update_time.put(current_time), 203 | ), 204 | ), 205 | ) 206 | 207 | return on_update 208 | 209 | # USER FUNCTIONS 210 | 211 | def on_lock(self): 212 | """ 213 | Locks user's BANK and grants veBANK (stored in local state) 214 | veBANK = BANK * (lock_duration / 4 years) 215 | Locking for 4 years grants maximum weight. Min lock duration is 7 days 216 | """ 217 | gov_token_txn_index = PREVIOUS_TRANSACTION 218 | current_timestamp = Global.latest_timestamp() 219 | 220 | lock_duration = Btoi(Txn.application_args[1]) 221 | lock_amount = Gtxn[gov_token_txn_index].asset_amount() 222 | vebank_amount = self.calculate_vebank_amount( 223 | lock_amount, lock_duration 224 | ) 225 | 226 | return Seq( 227 | # verify asset being sent to voting escrow contract 228 | verify_txn_is_sending_asa_to_contract( 229 | gov_token_txn_index, self.asset_id.get() 230 | ), 231 | # verify user has zero existing locked amount 232 | MagicAssert(self.sending_user.amount_locked.get() == ZERO_AMOUNT), 233 | # verify lock duration 234 | MagicAssert(lock_duration >= MIN_LOCK_TIME_SECONDS), 235 | MagicAssert(lock_duration <= MAX_LOCK_TIME_SECONDS), 236 | # verify non zero ve bank amount 237 | MagicAssert(vebank_amount > ZERO_AMOUNT), 238 | # set amount locked 239 | self.sending_user.amount_locked.put(lock_amount), 240 | # set lock start time 241 | self.sending_user.lock_start_time.put(current_timestamp), 242 | # set lock duration 243 | self.sending_user.lock_duration.put(lock_duration), 244 | # set vebank amount 245 | self.sending_user.amount_vebank.put(vebank_amount), 246 | # set update time 247 | self.sending_user.update_time.put(current_timestamp), 248 | # update global totals 249 | increment(self.total_locked, lock_amount), 250 | increment(self.total_vebank, vebank_amount), 251 | # recalculate user boost 252 | self.update_boost(self.sending_user), 253 | Approve(), 254 | ) 255 | 256 | def on_update_vebank_data(self): 257 | """ 258 | Update a user's and global veBANK and lock state 259 | Anyone can call this for any user 260 | """ 261 | 262 | return Seq( 263 | [ 264 | # update target user vebank data 265 | self.update_vebank_data(self.target_user), 266 | Approve(), 267 | ] 268 | ) 269 | 270 | def on_claim(self): 271 | """Sends back user's locked BANK after the lock expires""" 272 | lock_end_time = self.sending_user.get_lock_end_time() 273 | current_time = Global.latest_timestamp() 274 | 275 | return Seq( 276 | # verify amount locked is non zero 277 | MagicAssert(self.sending_user.amount_locked.get() > ZERO_AMOUNT), 278 | # verify lock has expired 279 | MagicAssert(current_time > lock_end_time), 280 | # return asset to user 281 | send_asa( 282 | self.asset_id.get(), 283 | self.sending_user.amount_locked.get(), 284 | Txn.sender(), 285 | ), 286 | # decrement user amount from total 287 | decrement( 288 | self.total_locked, self.sending_user.amount_locked.get() 289 | ), 290 | # set user amount locked to zero 291 | self.sending_user.amount_locked.put(ZERO_AMOUNT), 292 | # reset user lock start time to 293 | self.sending_user.lock_start_time.put(UNSET), 294 | # reset user lock duration 295 | self.sending_user.lock_duration.put(UNSET), 296 | # reset user update time 297 | self.sending_user.update_time.put(UNSET), 298 | Approve(), 299 | ) 300 | 301 | def on_extend_lock(self): 302 | """Adds time to existing user lock.""" 303 | extend_duration_seconds = Btoi(Txn.application_args[1]) 304 | current_time = Global.latest_timestamp() 305 | lock_end_time = self.sending_user.get_lock_end_time() 306 | duration_remaining = ( 307 | If(current_time < lock_end_time) 308 | .Then(lock_end_time - current_time) 309 | .Else(Int(0)) 310 | ) 311 | total_new_duration = duration_remaining + extend_duration_seconds 312 | current_vebank_balance = self.sending_user.amount_vebank.get() 313 | locked_amount = self.sending_user.amount_locked.get() 314 | 315 | new_vebank_balance = self.calculate_vebank_amount( 316 | locked_amount, total_new_duration 317 | ) 318 | 319 | return Seq( 320 | # verify user has non zero locked amount 321 | MagicAssert(locked_amount > ZERO_AMOUNT), 322 | # verify extend duration is non zero 323 | MagicAssert(extend_duration_seconds > ZERO_AMOUNT), 324 | # validate new total duration 325 | MagicAssert(total_new_duration >= MIN_LOCK_TIME_SECONDS), 326 | MagicAssert(total_new_duration <= MAX_LOCK_TIME_SECONDS), 327 | # update global total vebank 328 | decrement(self.total_vebank, current_vebank_balance), 329 | increment(self.total_vebank, new_vebank_balance), 330 | # set new user vebank amount 331 | self.sending_user.amount_vebank.put(new_vebank_balance), 332 | # set new user lock duration 333 | self.sending_user.lock_duration.put(total_new_duration), 334 | # set new user lock start time 335 | self.sending_user.lock_start_time.put(current_time), 336 | # recalculate user boost 337 | self.update_boost(self.sending_user), 338 | Approve(), 339 | ) 340 | 341 | def on_increase_lock_amount(self): 342 | """Increases the amount of BANK locked, without changing lock duration""" 343 | gov_token_txn_index = PREVIOUS_TRANSACTION 344 | current_time = Global.latest_timestamp() 345 | lock_end_time = self.sending_user.get_lock_end_time() 346 | lock_duration = lock_end_time - current_time 347 | additional_amount_to_lock = Gtxn[gov_token_txn_index].asset_amount() 348 | existing_amount_locked = self.sending_user.amount_locked.get() 349 | new_vebank = self.calculate_vebank_amount( 350 | existing_amount_locked + additional_amount_to_lock, lock_duration 351 | ) 352 | 353 | return Seq( 354 | # verify previous transaction is payment to this contract 355 | verify_txn_is_sending_asa_to_contract( 356 | gov_token_txn_index, self.asset_id.get() 357 | ), 358 | # verify the users current amount locked is non zero 359 | MagicAssert(self.sending_user.amount_locked.get() > ZERO_AMOUNT), 360 | # verify remaining lock duration is greater than minimum 361 | MagicAssert(lock_duration >= MIN_LOCK_TIME_SECONDS), 362 | # verify additional amount to lock is non zero 363 | MagicAssert(additional_amount_to_lock > ZERO_AMOUNT), 364 | # verify additional vebank amount is non zero 365 | MagicAssert(new_vebank > self.sending_user.amount_vebank.get()), 366 | # increment total locked 367 | increment(self.total_locked, additional_amount_to_lock), 368 | # increment user locked 369 | increment( 370 | self.sending_user.amount_locked, additional_amount_to_lock 371 | ), 372 | decrement( 373 | self.total_vebank, self.sending_user.amount_vebank.get() 374 | ), 375 | # increment total vebank 376 | increment(self.total_vebank, new_vebank), 377 | # increment user vebank 378 | self.sending_user.amount_vebank.put(new_vebank), 379 | # recalculate user boost 380 | self.update_boost(self.sending_user), 381 | Approve(), 382 | ) 383 | 384 | def approval_program(self): 385 | """Voting escrow approval program.""" 386 | # sender checks 387 | sender_is_dao = Or( 388 | Txn.sender() == self.dao_address.get(), 389 | Txn.sender() == self.emergency_dao_address.get(), 390 | ) 391 | # check on complete 392 | is_no_op = Txn.on_completion() == OnComplete.NoOp 393 | is_opt_in = Txn.on_completion() == OnComplete.OptIn 394 | is_close_out = Txn.on_completion() == OnComplete.CloseOut 395 | # on call method 396 | on_call_method = Txn.application_args[0] 397 | 398 | return Cond( 399 | [Txn.application_id() == Int(0), self.on_creation()], 400 | [Txn.on_completion() == OnComplete.DeleteApplication, Reject()], 401 | [is_opt_in, self.on_opt_in()], 402 | [is_close_out, self.on_close_out()], 403 | # admin functions 404 | [ 405 | sender_is_dao, 406 | Cond( 407 | [ 408 | is_no_op, 409 | Cond( 410 | [ 411 | on_call_method 412 | == Bytes( 413 | VotingEscrowStrings.set_gov_token_id 414 | ), 415 | self.on_set_gov_token_id(), 416 | ], 417 | [ 418 | on_call_method 419 | == Bytes( 420 | VotingEscrowStrings.set_admin_contract_app_id 421 | ), 422 | self.on_set_admin_contract_app_id(), 423 | ], 424 | ), 425 | ] 426 | ), 427 | ], 428 | # user functions 429 | [ 430 | is_no_op, 431 | Cond( 432 | # target user 433 | [ 434 | on_call_method 435 | == Bytes(VotingEscrowStrings.update_vebank_data), 436 | self.on_update_vebank_data(), 437 | ], 438 | # lock (does not require vebank update) 439 | [ 440 | on_call_method 441 | == Bytes(VotingEscrowStrings.lock), 442 | self.on_lock(), 443 | ], 444 | # user 445 | [ 446 | TRUE, 447 | Seq( 448 | self.update_vebank_data(self.sending_user), 449 | Cond( 450 | [ 451 | on_call_method 452 | == Bytes( 453 | VotingEscrowStrings.extend_lock 454 | ), 455 | self.on_extend_lock(), 456 | ], 457 | [ 458 | on_call_method 459 | == Bytes( 460 | VotingEscrowStrings.increase_lock_amount 461 | ), 462 | self.on_increase_lock_amount(), 463 | ], 464 | [ 465 | on_call_method 466 | == Bytes(VotingEscrowStrings.claim), 467 | self.on_claim(), 468 | ], 469 | ), 470 | ), 471 | ], 472 | ), 473 | ], 474 | ) 475 | 476 | def clear_state_program(self): 477 | """Clear state program for the voting escrow contract.""" 478 | return Seq( 479 | # decrement user vebank amount from total 480 | decrement( 481 | self.total_vebank, self.sending_user.amount_vebank.get() 482 | ), 483 | # decrement user locked amount from total 484 | decrement( 485 | self.total_locked, self.sending_user.amount_locked.get() 486 | ), 487 | Approve(), 488 | ) 489 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /contracts/v2_staking/staking_contract.py: -------------------------------------------------------------------------------- 1 | """A module containing the staking contract.""" 2 | from pyteal import * 3 | 4 | from contracts.governance.contract_strings import VotingEscrowStrings 5 | from contracts.utils.wrapped_var import * 6 | from contracts.v2_staking.constants import * 7 | from contracts.v2_staking.constants import StakingScratchSlots 8 | from contracts.v2_staking.contract_strings import ( 9 | StakingStrings as StakingStrings, 10 | ) 11 | from contracts.v2_staking.subroutines import * 12 | 13 | 14 | class StakingUser: 15 | """A user of the staking contract.""" 16 | 17 | def __init__(self, account, rewards_program_index, voting_escrow_app_id): 18 | self.account = account 19 | self.voting_escrow_app_id = voting_escrow_app_id 20 | 21 | # CURVE REWARDS CONSTANTS 22 | self.STAKE_PCT = Int(400) 23 | self.BOOST_PCT = Int(600) 24 | 25 | # USER STATE 26 | 27 | # staking state 28 | self.total_staked = WrappedVar( 29 | StakingStrings.user_total_staked, LOCAL_VAR, self.account 30 | ) 31 | self.scaled_total_staked = WrappedVar( 32 | StakingStrings.user_scaled_total_staked, LOCAL_VAR, self.account 33 | ) 34 | 35 | # locking multiplier state 36 | self.boost_multiplier = WrappedVar( 37 | StakingStrings.boost_multiplier, LOCAL_VAR, self.account 38 | ) 39 | 40 | # rewards state 41 | self.rewards_program_counter = WrappedVar( 42 | Concat( 43 | Bytes(StakingStrings.user_rewards_program_counter_prefix), 44 | Itob(rewards_program_index.load()), 45 | ), 46 | LOCAL_VAR, 47 | name_to_bytes=False, 48 | index=self.account, 49 | ) 50 | self.rewards_coefficient = WrappedVar( 51 | Concat( 52 | Bytes(StakingStrings.user_rewards_coefficient_prefix), 53 | Itob(rewards_program_index.load()), 54 | ), 55 | LOCAL_VAR, 56 | name_to_bytes=False, 57 | index=self.account, 58 | ) 59 | self.unclaimed_rewards = WrappedVar( 60 | Concat( 61 | Bytes(StakingStrings.user_unclaimed_rewards_prefix), 62 | Itob(rewards_program_index.load()), 63 | ), 64 | LOCAL_VAR, 65 | name_to_bytes=False, 66 | index=self.account, 67 | ) 68 | 69 | # external state 70 | self.opted_into_voting_escrow = App.optedIn( 71 | self.account, self.voting_escrow_app_id 72 | ) 73 | self.external_boost_multiplier = WrappedVar( 74 | VotingEscrowStrings.user_boost_multiplier, 75 | LOCAL_EX_VAR, 76 | index=self.account, 77 | app_id=self.voting_escrow_app_id, 78 | ).get() 79 | 80 | def update_boost_multiplier(self): 81 | """Update the boost multiplier.""" 82 | return Seq( 83 | [ 84 | If( 85 | And( 86 | self.voting_escrow_app_id != UNSET, 87 | self.opted_into_voting_escrow, 88 | ) 89 | ) 90 | .Then( 91 | Seq( 92 | [ 93 | # update vebank data 94 | InnerTxnBuilder.Begin(), 95 | InnerTxnBuilder.SetFields( 96 | { 97 | TxnField.type_enum: TxnType.ApplicationCall, 98 | TxnField.application_id: self.voting_escrow_app_id, 99 | TxnField.application_args: [ 100 | Bytes( 101 | VotingEscrowStrings.update_vebank_data 102 | ) 103 | ], 104 | TxnField.accounts: [self.account], 105 | TxnField.fee: ZERO_FEE, 106 | } 107 | ), 108 | InnerTxnBuilder.Submit(), 109 | # get updated boost multiplier 110 | self.external_boost_multiplier, 111 | self.boost_multiplier.put( 112 | self.external_boost_multiplier.value() 113 | ), 114 | ] 115 | ) 116 | ) 117 | .Else(self.boost_multiplier.put(ZERO_AMOUNT)) 118 | ] 119 | ) 120 | 121 | def update_scaled_total_staked(self, global_total_staked): 122 | """ 123 | Curve Rewards Formula 124 | 125 | stake_component = user_total_staked * 40% 126 | boost_component = boost_multiplier * global_total_staked * 60% 127 | MIN( 128 | stake_component + boost_component, 129 | user_total_staked 130 | ) 131 | If boost_multiplier == 0 --> 40% * user_total_staked 132 | If boost_multiplier == 1 --> user_total_staked 133 | 134 | As such, the best multiplier a user can get is user_total_staked / 40% * user_total_staked = 2.5x 135 | """ 136 | stake_component = WideRatio( 137 | [self.total_staked.get(), self.STAKE_PCT], [FIXED_3_SCALE_FACTOR] 138 | ) 139 | boost_component = WideRatio( 140 | [self.boost_multiplier.get(), global_total_staked, self.BOOST_PCT], 141 | [FIXED_15_SCALE_FACTOR], 142 | ) 143 | scaled_total_staked = stake_component + boost_component 144 | 145 | return Seq( 146 | [ 147 | # return max of total staked and scaled total staked 148 | self.scaled_total_staked.put( 149 | minimum(self.total_staked.get(), scaled_total_staked) 150 | ) 151 | ] 152 | ) 153 | 154 | 155 | class StakingRewardsProgram: 156 | """A class for managing staking rewards programs.""" 157 | 158 | def __init__( 159 | self, 160 | rewards_escrow_account, 161 | rewards_program_index, 162 | staking_asset_id, 163 | scaled_total_staked, 164 | ): 165 | # STAKING STATE 166 | self.rewards_escrow_account = rewards_escrow_account 167 | self.staking_asset_id = staking_asset_id 168 | self.scaled_total_staked = scaled_total_staked 169 | 170 | # SCRATCH VARS 171 | self.rewards_to_issue = ScratchVar( 172 | TealType.uint64, StakingScratchSlots.rewards_to_issue 173 | ) 174 | self.rewards_available = ScratchVar( 175 | TealType.uint64, StakingScratchSlots.rewards_available 176 | ) 177 | 178 | # REWARDS PROGRAM STATE 179 | self.program_counter = WrappedVar( 180 | Concat( 181 | Bytes(StakingStrings.rewards_program_counter_prefix), 182 | Itob(rewards_program_index), 183 | ), 184 | GLOBAL_VAR, 185 | name_to_bytes=False, 186 | ) 187 | self.asset_id = WrappedVar( 188 | Concat( 189 | Bytes(StakingStrings.rewards_asset_id_prefix), 190 | Itob(rewards_program_index), 191 | ), 192 | GLOBAL_VAR, 193 | name_to_bytes=False, 194 | ) 195 | self.rewards_per_second = WrappedVar( 196 | Concat( 197 | Bytes(StakingStrings.rewards_per_second_prefix), 198 | Itob(rewards_program_index), 199 | ), 200 | GLOBAL_VAR, 201 | name_to_bytes=False, 202 | ) 203 | self.coefficient = WrappedVar( 204 | Concat( 205 | Bytes(StakingStrings.rewards_coefficient_prefix), 206 | Itob(rewards_program_index), 207 | ), 208 | GLOBAL_VAR, 209 | name_to_bytes=False, 210 | ) 211 | self.rewards_issued = WrappedVar( 212 | Concat( 213 | Bytes(StakingStrings.rewards_issued_prefix), 214 | Itob(rewards_program_index), 215 | ), 216 | GLOBAL_VAR, 217 | name_to_bytes=False, 218 | ) 219 | self.rewards_paid = WrappedVar( 220 | Concat( 221 | Bytes(StakingStrings.rewards_paid_prefix), 222 | Itob(rewards_program_index), 223 | ), 224 | GLOBAL_VAR, 225 | name_to_bytes=False, 226 | ) 227 | 228 | def initialize_program(self, asset_id, rewards_per_second): 229 | """Initialize a rewards program.""" 230 | 231 | return Seq( 232 | [ 233 | # increment program counter 234 | increment(self.program_counter, Int(1)), 235 | # init asset_id 236 | self.asset_id.put(asset_id), 237 | # init rps 238 | self.rewards_per_second.put(rewards_per_second), 239 | # set coefficient to 0 240 | self.coefficient.put(BytesZero(Int(64))), 241 | # set rewards issued and payed to 0 242 | self.rewards_issued.put(ZERO_AMOUNT), 243 | self.rewards_paid.put(ZERO_AMOUNT), 244 | ] 245 | ) 246 | 247 | def update_rewards_per_second(self, new_rewards_per_second): 248 | """Update the rewards per second.""" 249 | 250 | return Seq([self.rewards_per_second.put(new_rewards_per_second)]) 251 | 252 | def update_coefficient(self, time_delta): 253 | """Update the coefficient.""" 254 | 255 | rewards_to_issue = time_delta * self.rewards_per_second.get() 256 | latest_coefficient_term = BytesDiv( 257 | BytesMul( 258 | Itob(FIXED_18_SCALE_FACTOR), Itob(self.rewards_to_issue.load()) 259 | ), 260 | Itob(self.scaled_total_staked), 261 | ) 262 | 263 | return Seq( 264 | [ 265 | If(self.scaled_total_staked > Int(0)).Then( 266 | Seq( 267 | [ 268 | # calculate rewards to issue 269 | self.rewards_to_issue.store(rewards_to_issue), 270 | # increment coefficient 271 | self.coefficient.put( 272 | BytesAdd( 273 | self.coefficient.get(), 274 | latest_coefficient_term, 275 | ) 276 | ), 277 | # increment rewards issued 278 | increment( 279 | self.rewards_issued, 280 | self.rewards_to_issue.load(), 281 | ), 282 | ] 283 | ) 284 | ) 285 | ] 286 | ) 287 | 288 | def update_user_rewards(self, staking_user): 289 | """Update a user's rewards.""" 290 | 291 | latest_user_rewards = Btoi( 292 | BytesDiv( 293 | BytesMul( 294 | BytesMinus( 295 | self.coefficient.get(), 296 | staking_user.rewards_coefficient.get(), 297 | ), 298 | Itob(staking_user.scaled_total_staked.get()), 299 | ), 300 | Itob(FIXED_18_SCALE_FACTOR), 301 | ) 302 | ) 303 | 304 | return Seq( 305 | [ 306 | # reset user rewards program variables if necessary 307 | If( 308 | staking_user.rewards_program_counter.get() 309 | != self.program_counter.get() 310 | ).Then( 311 | Seq( 312 | [ 313 | # reset user claimable rewards 314 | staking_user.unclaimed_rewards.put(ZERO_AMOUNT), 315 | # set user rewards index to 0 316 | staking_user.rewards_coefficient.put(BYTES_ZERO), 317 | # set user program counter to current program 318 | staking_user.rewards_program_counter.put( 319 | self.program_counter.get() 320 | ), 321 | ] 322 | ) 323 | ), 324 | # add latest user rewards to unclaimed rewards 325 | increment(staking_user.unclaimed_rewards, latest_user_rewards), 326 | # set user rewards coefficient to latest coefficient 327 | staking_user.rewards_coefficient.put(self.coefficient.get()), 328 | ] 329 | ) 330 | 331 | def claim_rewards(self, staking_user): 332 | """Claims a users' rewards.""" 333 | return Seq( 334 | [ 335 | # send rewards 336 | If(self.asset_id.get() == ALGO_ASSET_ID) 337 | .Then( 338 | send_algo_from_address( 339 | self.rewards_escrow_account, 340 | staking_user.unclaimed_rewards.get(), 341 | staking_user.account, 342 | ) 343 | ) 344 | .Else( 345 | send_asa_from_address( 346 | self.rewards_escrow_account, 347 | self.asset_id.get(), 348 | staking_user.unclaimed_rewards.get(), 349 | staking_user.account, 350 | ) 351 | ), 352 | increment( 353 | self.rewards_paid, staking_user.unclaimed_rewards.get() 354 | ), 355 | # zero users unclaimed rewards 356 | staking_user.unclaimed_rewards.put(ZERO_AMOUNT), 357 | ] 358 | ) 359 | 360 | 361 | class StakingContract: 362 | """Contract for staking assets.""" 363 | 364 | def __init__(self, rewards_program_count, staked_asset_is_algo=False): 365 | self.raw_rewards_program_count = rewards_program_count 366 | self.staked_asset_is_algo = staked_asset_is_algo 367 | 368 | # SCRATCH VARS 369 | self.rewards_program_index = ScratchVar( 370 | TealType.uint64, StakingScratchSlots.rewards_program_index 371 | ) 372 | self.amount_staked = ScratchVar( 373 | TealType.uint64, StakingScratchSlots.amount_staked 374 | ) 375 | 376 | # ADMIN STATE 377 | self.dao_address = WrappedVar(StakingStrings.dao_address, GLOBAL_VAR) 378 | self.emergency_dao_address = WrappedVar( 379 | StakingStrings.emergency_dao_address, GLOBAL_VAR 380 | ) 381 | self.rewards_escrow_account = WrappedVar( 382 | StakingStrings.rewards_escrow_account, GLOBAL_VAR 383 | ) 384 | self.rewards_program_count = WrappedVar( 385 | StakingStrings.rewards_program_count, GLOBAL_VAR 386 | ) 387 | self.voting_escrow_app_id = WrappedVar( 388 | StakingStrings.voting_escrow_app_id, GLOBAL_VAR 389 | ) 390 | 391 | # IMMUTABLE GLOBAL STATE 392 | self.asset_id = WrappedVar(StakingStrings.asset_id, GLOBAL_VAR) 393 | 394 | # STAKING STATE 395 | self.total_staked = WrappedVar(StakingStrings.total_staked, GLOBAL_VAR) 396 | self.scaled_total_staked = WrappedVar( 397 | StakingStrings.scaled_total_staked, GLOBAL_VAR 398 | ) 399 | 400 | # REWARDS PROGRAM STATE 401 | self.latest_time = WrappedVar(StakingStrings.latest_time, GLOBAL_VAR) 402 | self.rewards_program = StakingRewardsProgram( 403 | self.rewards_escrow_account.get(), 404 | self.rewards_program_index.load(), 405 | self.asset_id.get(), 406 | self.scaled_total_staked.get(), 407 | ) 408 | 409 | # USER STATE 410 | self.calling_user = StakingUser( 411 | Txn.accounts[0], 412 | self.rewards_program_index, 413 | self.voting_escrow_app_id.get(), 414 | ) 415 | self.target_user = StakingUser( 416 | Txn.accounts[1], 417 | self.rewards_program_index, 418 | self.voting_escrow_app_id.get(), 419 | ) 420 | 421 | # HELPERS 422 | 423 | def verify_staked_asset_payment_txn_to_market(self, idx): 424 | """Verify that the transaction is a payment to the market.""" 425 | if self.staked_asset_is_algo: 426 | return verify_txn_is_payment( 427 | idx, Global.current_application_address() 428 | ) 429 | else: 430 | return verify_txn_is_asset_transfer( 431 | idx, Global.current_application_address(), self.asset_id.get() 432 | ) 433 | 434 | def get_staked_asset_received(self, idx): 435 | """Get the amount of staked asset received in the transaction.""" 436 | if self.staked_asset_is_algo: 437 | return Gtxn[idx].amount() 438 | else: 439 | return Gtxn[idx].asset_amount() 440 | 441 | def send_staked_asset(self, amount): 442 | """Send the staked asset to the caller.""" 443 | if self.staked_asset_is_algo: 444 | return send_algo(amount, Txn.sender()) 445 | else: 446 | return send_asa(self.asset_id.get(), amount, Txn.sender()) 447 | 448 | def for_each_rewards_program(self, do): 449 | """For each rewards program, do something.""" 450 | return For( 451 | self.rewards_program_index.store(Int(0)), 452 | self.rewards_program_index.load() 453 | < self.rewards_program_count.get(), 454 | self.rewards_program_index.store( 455 | self.rewards_program_index.load() + Int(1) 456 | ), 457 | ).Do(do) 458 | 459 | # CREATION 460 | 461 | def on_creation(self): 462 | """Initialize the staking contract.""" 463 | asset_id = Txn.assets[0] 464 | voting_escrow_app_id = Txn.applications[1] 465 | 466 | dao_address = Txn.accounts[1] 467 | emergency_dao_address = Txn.accounts[2] 468 | 469 | return Seq( 470 | # check that this staking contract was initialized with the correct boolean 471 | ( 472 | [MagicAssert(asset_id == ALGO_ASSET_ID)] 473 | if (self.staked_asset_is_algo) 474 | else [] 475 | ) 476 | + [ 477 | # SET ADMIN VARIABLES 478 | self.dao_address.put(dao_address), 479 | self.emergency_dao_address.put(emergency_dao_address), 480 | self.rewards_escrow_account.put(Global.zero_address()), 481 | self.voting_escrow_app_id.put(voting_escrow_app_id), 482 | self.total_staked.put(ZERO_AMOUNT), 483 | self.scaled_total_staked.put(ZERO_AMOUNT), 484 | # SET STAKING PARAMETERS 485 | self.asset_id.put(asset_id), 486 | # INITIALIZE REWARDS PROGRAMS 487 | self.rewards_program_count.put( 488 | Int(self.raw_rewards_program_count) 489 | ), 490 | self.for_each_rewards_program( 491 | self.rewards_program.initialize_program( 492 | ALGO_ASSET_ID, ZERO_AMOUNT 493 | ) 494 | ), 495 | self.latest_time.put(Global.latest_timestamp()), 496 | Approve(), 497 | ] 498 | ) 499 | 500 | # ADMIN FUNCTIONS 501 | 502 | def on_initialize_rewards_escrow_account(self): 503 | """Initialize the rewards escrow account.""" 504 | rewards_escrow_account = Txn.accounts[1] 505 | 506 | return Seq( 507 | [ 508 | # verify rewards escrow is not already set 509 | MagicAssert( 510 | self.rewards_escrow_account.get() == Global.zero_address() 511 | ), 512 | # verify account is being rekeyed in the previous transaction 513 | MagicAssert( 514 | Gtxn[PREVIOUS_TRANSACTION].sender() 515 | == rewards_escrow_account 516 | ), 517 | MagicAssert( 518 | Gtxn[PREVIOUS_TRANSACTION].close_remainder_to() 519 | == Global.zero_address() 520 | ), 521 | MagicAssert( 522 | Gtxn[PREVIOUS_TRANSACTION].rekey_to() 523 | == Global.current_application_address() 524 | ), 525 | # set rewards escrow account 526 | self.rewards_escrow_account.put(rewards_escrow_account), 527 | Approve(), 528 | ] 529 | ) 530 | 531 | def on_set_voting_escrow_app_id(self): 532 | """Set the voting escrow app id.""" 533 | 534 | new_voting_escrow_app_id = Txn.applications[1] 535 | 536 | return Seq( 537 | [ 538 | # set rps pusher 539 | self.voting_escrow_app_id.put(new_voting_escrow_app_id), 540 | Approve(), 541 | ] 542 | ) 543 | 544 | def on_set_rewards_program(self): 545 | """Set the rewards program.""" 546 | 547 | index = Btoi(Txn.application_args[1]) 548 | asset_id = Txn.assets[0] 549 | rewards_per_second = Btoi(Txn.application_args[2]) 550 | 551 | return Seq( 552 | [ 553 | # verify index is valid 554 | MagicAssert(index < self.rewards_program_count.get()), 555 | # set the rewards program index to update 556 | self.rewards_program_index.store(index), 557 | # set the rewards program 558 | self.rewards_program.initialize_program( 559 | asset_id, rewards_per_second 560 | ), 561 | # opt rewards escrow account into asset 562 | If(asset_id != ALGO_ASSET_ID).Then( 563 | send_asa_from_address( 564 | self.rewards_escrow_account.get(), 565 | asset_id, 566 | ZERO_AMOUNT, 567 | self.rewards_escrow_account.get(), 568 | ) 569 | ), 570 | Approve(), 571 | ] 572 | ) 573 | 574 | def on_update_rewards_per_second(self): 575 | """Update the rewards per second.""" 576 | 577 | index = Btoi(Txn.application_args[1]) 578 | rewards_per_second = Btoi(Txn.application_args[2]) 579 | 580 | return Seq( 581 | [ 582 | # verify index is valid 583 | MagicAssert(index < self.rewards_program_count.get()), 584 | # set the rewards program index to update 585 | self.rewards_program_index.store(index), 586 | # set the rewards program 587 | self.rewards_program.update_rewards_per_second( 588 | rewards_per_second 589 | ), 590 | Approve(), 591 | ] 592 | ) 593 | 594 | def on_opt_into_asset(self): 595 | """Opt into an asset.""" 596 | 597 | asset_id = Txn.assets[0] 598 | 599 | return Seq( 600 | [ 601 | # opt into asa 602 | send_asa( 603 | asset_id, ZERO_AMOUNT, Global.current_application_address() 604 | ), 605 | Approve(), 606 | ] 607 | ) 608 | 609 | def on_reclaim_rewards_assets(self): 610 | """Reclaim rewards assets.""" 611 | 612 | reclaim_asset_id = Btoi(Txn.application_args[1]) 613 | reclaim_amount = Btoi(Txn.application_args[2]) 614 | 615 | return Seq( 616 | [ 617 | If(reclaim_asset_id == ALGO_ASSET_ID) 618 | .Then( 619 | send_algo_from_address( 620 | self.rewards_escrow_account.get(), 621 | reclaim_amount, 622 | Txn.sender(), 623 | ) 624 | ) 625 | .Else( 626 | send_asa_from_address( 627 | self.rewards_escrow_account.get(), 628 | reclaim_asset_id, 629 | reclaim_amount, 630 | Txn.sender(), 631 | ) 632 | ), 633 | Approve(), 634 | ] 635 | ) 636 | 637 | # OPT IN / CLOSE OUT 638 | 639 | def on_user_opt_in(self): 640 | """Opt a user into the staking contract.""" 641 | 642 | return Seq( 643 | [ 644 | # initialize user state 645 | self.calling_user.total_staked.put(ZERO_AMOUNT), 646 | self.calling_user.scaled_total_staked.put(ZERO_AMOUNT), 647 | # initialize rewards program states 648 | self.for_each_rewards_program( 649 | Seq( 650 | [ 651 | self.rewards_program.update_user_rewards( 652 | self.calling_user 653 | ), 654 | ] 655 | ) 656 | ), 657 | # set initial boost multiplier to zero 658 | self.calling_user.boost_multiplier.put(ZERO_AMOUNT), 659 | Approve(), 660 | ] 661 | ) 662 | 663 | def on_user_close_out(self): 664 | """Close out a user from the staking contract.""" 665 | 666 | ignore_unclaimed_rewards = Btoi(Txn.application_args[1]) 667 | 668 | return Seq( 669 | [ 670 | # check that user has no stake 671 | MagicAssert( 672 | self.calling_user.total_staked.get() == ZERO_AMOUNT 673 | ), 674 | # check that user has no unclaimed rewards 675 | If(ignore_unclaimed_rewards == FALSE).Then( 676 | self.for_each_rewards_program( 677 | MagicAssert( 678 | self.calling_user.unclaimed_rewards.get() 679 | == ZERO_AMOUNT 680 | ) 681 | ), 682 | ), 683 | Approve(), 684 | ] 685 | ) 686 | 687 | # USER FUNCTIONS 688 | 689 | def update_user(self, staking_user): 690 | """Update a user state.""" 691 | 692 | time_delta = Global.latest_timestamp() - self.latest_time.get() 693 | 694 | return Seq( 695 | [ 696 | # update rewards program states 697 | self.for_each_rewards_program( 698 | Seq( 699 | [ 700 | self.rewards_program.update_coefficient( 701 | time_delta 702 | ), 703 | self.rewards_program.update_user_rewards( 704 | staking_user 705 | ), 706 | ] 707 | ) 708 | ), 709 | self.latest_time.put(Global.latest_timestamp()), 710 | # update user scaled stake 711 | # decrement global scaled total staked 712 | decrement( 713 | self.scaled_total_staked, 714 | staking_user.scaled_total_staked.get(), 715 | ), 716 | # update boost multiplier 717 | staking_user.update_boost_multiplier(), 718 | # update user scaled total staked 719 | staking_user.update_scaled_total_staked( 720 | self.total_staked.get() 721 | ), 722 | # increment global scaled total staked 723 | increment( 724 | self.scaled_total_staked, 725 | staking_user.scaled_total_staked.get(), 726 | ), 727 | ] 728 | ) 729 | 730 | def on_stake(self): 731 | return Seq( 732 | [ 733 | # verify payment 734 | self.verify_staked_asset_payment_txn_to_market( 735 | PREVIOUS_TRANSACTION 736 | ), 737 | # cache amount staked 738 | self.amount_staked.store( 739 | self.get_staked_asset_received(PREVIOUS_TRANSACTION) 740 | ), 741 | # decrement user from scaled total staked 742 | decrement( 743 | self.scaled_total_staked, 744 | self.calling_user.scaled_total_staked.get(), 745 | ), 746 | # increment user total staked 747 | increment( 748 | self.calling_user.total_staked, self.amount_staked.load() 749 | ), 750 | # increment global total staked 751 | increment(self.total_staked, self.amount_staked.load()), 752 | # update user scaled total staked 753 | self.calling_user.update_scaled_total_staked( 754 | self.total_staked.get() 755 | ), 756 | # increment global scaled total staked 757 | increment( 758 | self.scaled_total_staked, 759 | self.calling_user.scaled_total_staked.get(), 760 | ), 761 | Approve(), 762 | ] 763 | ) 764 | 765 | def on_unstake(self): 766 | """Unstake an amount of staked asset.""" 767 | amount = Btoi(Txn.application_args[1]) 768 | 769 | return Seq( 770 | [ 771 | # verify the user has enough staked to unstake this amount 772 | MagicAssert(self.calling_user.total_staked.get() >= amount), 773 | # send asset 774 | self.send_staked_asset(amount), 775 | # decrement user from scaled total staked 776 | decrement( 777 | self.scaled_total_staked, 778 | self.calling_user.scaled_total_staked.get(), 779 | ), 780 | # decrement user total staked 781 | decrement(self.calling_user.total_staked, amount), 782 | # decrement global total staked 783 | decrement(self.total_staked, amount), 784 | # update user scaled total staked 785 | self.calling_user.update_scaled_total_staked( 786 | self.total_staked.get() 787 | ), 788 | # increment global scaled total staked 789 | increment( 790 | self.scaled_total_staked, 791 | self.calling_user.scaled_total_staked.get(), 792 | ), 793 | Approve(), 794 | ] 795 | ) 796 | 797 | def on_claim_rewards(self): 798 | """Claim the user rewards.""" 799 | rewards_program_index = Btoi(Txn.application_args[1]) 800 | 801 | return Seq( 802 | [ 803 | # verify index is valid 804 | MagicAssert( 805 | rewards_program_index < self.rewards_program_count.get() 806 | ), 807 | # cache target rewards program index 808 | self.rewards_program_index.store(rewards_program_index), 809 | # claim rewards 810 | self.rewards_program.claim_rewards(self.calling_user), 811 | Approve(), 812 | ] 813 | ) 814 | 815 | def on_update_target_user(self): 816 | """Update the target user.""" 817 | 818 | return Seq( 819 | [ 820 | # update rewards 821 | self.update_user(self.target_user), 822 | Approve(), 823 | ] 824 | ) 825 | 826 | def approval_program(self): 827 | """Staking contract approval program.""" 828 | sender_is_dao = Or( 829 | Txn.sender() == self.dao_address.get(), 830 | Txn.sender() == self.emergency_dao_address.get(), 831 | ) 832 | is_no_op = And(Txn.on_completion() == OnComplete.NoOp) 833 | 834 | return Cond( 835 | [Txn.application_id() == Int(0), self.on_creation()], 836 | [Txn.on_completion() == OnComplete.OptIn, self.on_user_opt_in()], 837 | # admin calls 838 | [ 839 | sender_is_dao, 840 | Cond( 841 | [ 842 | is_no_op, 843 | Cond( 844 | [ 845 | Txn.application_args[0] 846 | == Bytes( 847 | StakingStrings.initialize_rewards_escrow_account 848 | ), 849 | self.on_initialize_rewards_escrow_account(), 850 | ], 851 | [ 852 | Txn.application_args[0] 853 | == Bytes( 854 | StakingStrings.set_voting_escrow_app_id 855 | ), 856 | self.on_set_voting_escrow_app_id(), 857 | ], 858 | [ 859 | Txn.application_args[0] 860 | == Bytes(StakingStrings.set_rewards_program), 861 | self.on_set_rewards_program(), 862 | ], 863 | [ 864 | Txn.application_args[0] 865 | == Bytes( 866 | StakingStrings.update_rewards_per_second 867 | ), 868 | self.on_update_rewards_per_second(), 869 | ], 870 | [ 871 | Txn.application_args[0] 872 | == Bytes(StakingStrings.opt_into_asset), 873 | self.on_opt_into_asset(), 874 | ], 875 | [ 876 | Txn.application_args[0] 877 | == Bytes( 878 | StakingStrings.reclaim_rewards_assets 879 | ), 880 | self.on_reclaim_rewards_assets(), 881 | ], 882 | ), 883 | ] 884 | ), 885 | ], 886 | # all other application calls 887 | [ 888 | is_no_op, 889 | Cond( 890 | # unprotected 891 | [ 892 | Txn.application_args[0] 893 | == Bytes(StakingStrings.farm_ops), 894 | Approve(), 895 | ], 896 | [ 897 | Txn.application_args[0] 898 | == Bytes(StakingStrings.update_target_user), 899 | self.on_update_target_user(), 900 | ], 901 | [ 902 | TRUE, 903 | Seq( 904 | [ 905 | self.update_user(self.calling_user), 906 | Cond( 907 | [ 908 | Txn.application_args[0] 909 | == Bytes(StakingStrings.stake), 910 | self.on_stake(), 911 | ], 912 | [ 913 | Txn.application_args[0] 914 | == Bytes(StakingStrings.unstake), 915 | self.on_unstake(), 916 | ], 917 | [ 918 | Txn.application_args[0] 919 | == Bytes(StakingStrings.claim_rewards), 920 | self.on_claim_rewards(), 921 | ], 922 | ), 923 | ] 924 | ), 925 | ], 926 | ), 927 | ], 928 | # opt in / out 929 | [ 930 | Txn.on_completion() == OnComplete.CloseOut, 931 | self.on_user_close_out(), 932 | ], 933 | # disallowed 934 | [Txn.on_completion() == OnComplete.DeleteApplication, Reject()], 935 | ) 936 | 937 | def clear_state_program(self): 938 | return Seq( 939 | [ 940 | # decrement global total_staked by user's total_staked to reduce rewards dilution 941 | decrement( 942 | self.total_staked, self.calling_user.total_staked.get() 943 | ), 944 | # decrement global scaled_total_staked by user's scaled_total_staked to reduce rewards dilution 945 | decrement( 946 | self.scaled_total_staked, 947 | self.calling_user.scaled_total_staked.get(), 948 | ), 949 | Approve(), 950 | ] 951 | ) 952 | --------------------------------------------------------------------------------