diff --git a/README.md b/README.md index c83057cbf..6fab1dad7 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,68 @@ - [brownie](https://github.com/eth-brownie/brownie/) v1.12.4 or greater - [solc-select](https://github.com/crytic/solc-select) only if you are having multiple solc installed locally and globally. +## Documentation Generation + +The project uses Foundry's built-in documentation generator to create comprehensive documentation from NatSpec comments in the smart contracts. + +### Prerequisites + +1. Install Rust and Cargo (required for mdBook): +```bash +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh +``` + +2. Install mdBook using Cargo: +```bash +cargo install mdbook +``` + +### Available Documentation Scripts + +The following npm scripts are available for documentation: + +1. Generate documentation: +```bash +yarn doc:forge +``` + +2. View documentation in browser: +```bash +yarn doc:serve +``` + +3. Generate and view documentation in one command: +```bash +yarn doc:forge-all +``` + +### Documentation Structure + +- Documentation is generated from NatSpec comments in the contracts +- Output is stored in `foundry/docs/` +- Documentation is served at `http://localhost:3000` by default +- The documentation includes: + - Contract interfaces and inheritance + - Function documentation + - Events documentation + - State variables + - Custom errors + +### Updating Documentation + +1. Add or update NatSpec comments in your Solidity files +2. Run `yarn doc:forge` to regenerate the documentation +3. View changes using `yarn doc:serve` + +### Configuration + +Documentation generation settings can be found in `foundry.toml`: +```toml +[doc] +out = 'foundry/docs' +ignore = ['contracts/mockup/**/*.sol','contracts/testhelpers/**/*.sol'] +``` + ## Setup and Testing First install all the npm packages: diff --git a/foundry/docs/.gitignore b/foundry/docs/.gitignore new file mode 100644 index 000000000..4e42a1bcd --- /dev/null +++ b/foundry/docs/.gitignore @@ -0,0 +1 @@ +book/ \ No newline at end of file diff --git a/foundry/docs/book.css b/foundry/docs/book.css new file mode 100644 index 000000000..b5ce903f9 --- /dev/null +++ b/foundry/docs/book.css @@ -0,0 +1,13 @@ +table { + margin: 0 auto; + border-collapse: collapse; + width: 100%; +} + +table td:first-child { + width: 15%; +} + +table td:nth-child(2) { + width: 25%; +} \ No newline at end of file diff --git a/foundry/docs/book.toml b/foundry/docs/book.toml new file mode 100644 index 000000000..ad4a3c976 --- /dev/null +++ b/foundry/docs/book.toml @@ -0,0 +1,12 @@ +[book] +src = "src" +title = "" + +[output.html] +no-section-label = true +additional-js = ["solidity.min.js"] +additional-css = ["book.css"] +git-repository-url = "https://github.com/DistributedCollective/Sovryn-smart-contracts" + +[output.html.fold] +enable = true diff --git a/foundry/docs/solidity.min.js b/foundry/docs/solidity.min.js new file mode 100644 index 000000000..192493291 --- /dev/null +++ b/foundry/docs/solidity.min.js @@ -0,0 +1,74 @@ +hljs.registerLanguage("solidity",(()=>{"use strict";function e(){try{return!0 +}catch(e){return!1}} +var a=/-?(\b0[xX]([a-fA-F0-9]_?)*[a-fA-F0-9]|(\b[1-9](_?\d)*(\.((\d_?)*\d)?)?|\.\d(_?\d)*)([eE][-+]?\d(_?\d)*)?|\b0)(?!\w|\$)/ +;e()&&(a=a.source.replace(/\\b/g,"(?{ +var a=r(e),o=l(e),c=/[A-Za-z_$][A-Za-z_$0-9.]*/,d=e.inherit(e.TITLE_MODE,{ +begin:/[A-Za-z$_][0-9A-Za-z$_]*/,lexemes:c,keywords:n}),u={className:"params", +begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,lexemes:c,keywords:n, +contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,a,o,s]},_={ +className:"operator",begin:/:=|->/};return{keywords:n,lexemes:c, +contains:[a,o,i,t,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,s,_,{ +className:"function",lexemes:c,beginKeywords:"function",end:"{",excludeEnd:!0, +contains:[d,u,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,_]}]}}, +solAposStringMode:r,solQuoteStringMode:l,HEX_APOS_STRING_MODE:i, +HEX_QUOTE_STRING_MODE:t,SOL_NUMBER:s,isNegativeLookbehindAvailable:e} +;const{baseAssembly:c,solAposStringMode:d,solQuoteStringMode:u,HEX_APOS_STRING_MODE:_,HEX_QUOTE_STRING_MODE:m,SOL_NUMBER:b,isNegativeLookbehindAvailable:E}=o +;return e=>{for(var a=d(e),s=u(e),n=[],i=0;i<32;i++)n[i]=i+1 +;var t=n.map((e=>8*e)),r=[];for(i=0;i<=80;i++)r[i]=i +;var l=n.map((e=>"bytes"+e)).join(" ")+" ",o=t.map((e=>"uint"+e)).join(" ")+" ",g=t.map((e=>"int"+e)).join(" ")+" ",M=[].concat.apply([],t.map((e=>r.map((a=>e+"x"+a))))),p={ +keyword:"var bool string int uint "+g+o+"byte bytes "+l+"fixed ufixed "+M.map((e=>"fixed"+e)).join(" ")+" "+M.map((e=>"ufixed"+e)).join(" ")+" enum struct mapping address new delete if else for while continue break return throw emit try catch revert unchecked _ function modifier event constructor fallback receive error virtual override constant immutable anonymous indexed storage memory calldata external public internal payable pure view private returns import from as using pragma contract interface library is abstract type assembly", +literal:"true false wei gwei szabo finney ether seconds minutes hours days weeks years", +built_in:"self this super selfdestruct suicide now msg block tx abi blockhash gasleft assert require Error Panic sha3 sha256 keccak256 ripemd160 ecrecover addmod mulmod log0 log1 log2 log3 log4" +},O={className:"operator",begin:/[+\-!~*\/%<>&^|=]/ +},C=/[A-Za-z_$][A-Za-z_$0-9]*/,N={className:"params",begin:/\(/,end:/\)/, +excludeBegin:!0,excludeEnd:!0,lexemes:C,keywords:p, +contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,a,s,b,"self"]},f={ +begin:/\.\s*/,end:/[^A-Za-z0-9$_\.]/,excludeBegin:!0,excludeEnd:!0,keywords:{ +built_in:"gas value selector address length push pop send transfer call callcode delegatecall staticcall balance code codehash wrap unwrap name creationCode runtimeCode interfaceId min max" +},relevance:2},y=e.inherit(e.TITLE_MODE,{begin:/[A-Za-z$_][0-9A-Za-z$_]*/, +lexemes:C,keywords:p}),w={className:"built_in", +begin:(E()?"(?= collateral`, the complete position will be closed. Else if `returnTokenIsCollateral == True` `(swapAmount/collateral) * principal` will be swapped (partial closure). Else the closure amount will be the principal's covered amount + +`returnTokenIsCollateral` pass `true` if you want to withdraw remaining collateral + profit in collateral tokens (e.g. rBTC on a iSUSD contract), `false` if you want to withdraw it in loan tokens (e.g. sUSD on a iSUSD contract). + +`loanDataBytes` is not used at this point. Pass empty bytes. + +### 4. Borrowing + +##### 4.1 Borrow - take a loan + +Borrowing works similar to margin trading, just that the borrowed amount is withdrawn by the user instead of being held by the protocol. Just like with margin trading, the collateral is held in a differnet currency than the loan token. In our rBTC/sUSD example, sUSD is being used as collateral for rBTC and vice versa. In contrast to the margin trade call, it's not possible to send loan tokens, but collateral tokens must be sent: 150% of the withdrawn amount converted to collateral tokens. + +`borrow` expects following parameter: + +``` +bytes32 loanId, +uint256 withdrawAmount, +uint256 initialLoanDuration, +uint256 collateralTokenSent, +address collateralTokenAddress, +address borrower, +address receiver, +bytes memory loanDataBytes +``` + +`loanId` is the ID of the loan, 0 for a new loan + +`withdrawAmount` is the amount to be withdrawn (actually borrowed) + +`initialLoanDuration` is the duration of the loan in seconds. if the loan is not paid back until then, it'll need to be rolled over + +`collateralTokenSent` is the amount of collateral token sent (150% of the withdrawn amount worth in collateral tokens). If the collateral is rBTC, +`collateralTokenSent` needs to be added as value to the transaction as well. + +`collateralTokenAddress` is the address of the token to be used as collateral. cannot be the loan token address + +`borrower` is the address of the user paying for the collateral + +`receiver` is the address to receive the withdrawn amount + +##### 4.2 Close the loan + +Loans can either be closed with a swap like explained in 3.2, or with a deposit. Closing with deposit might be considered the standard behaviour. With `closeWithDeposit` the user pays back the loan fully or partially by sending loan tokens to the protocol contract. But users should always have the choice if they prefer to pay back the loan in loan tokens or pay it from their collateral. + +`closeWithDeposit` expects the following parameter: + +``` +bytes32 loanId, +address receiver, +uint256 depositAmount +``` + +`loanId`is the id of the loan + +`receiver` is the receiver of the collateral + +`depositAmount` defines how much of the position should be paid back. It is denominated in loan tokens. + +### 5. Loan Maintainanance + +##### 5.1 Add margin + +In order to add margin to a open position, call `depositCollateral` on the protocol contract. + +`depositCollateral` expects following parameter: + +``` +bytes32 loanId, +uint256 depositAmount +``` + +`loanId` is the ID of the loan + +`depositAmount` is the amount of collateral tokens to deposit. + +##### 5.2 Rollover + +When the maximum loan duration has been exceeded, the position will need to be rolled over. The function `rollover` on the protocol contract extends the loan duration by the maximum term (28 days for margin trades at the moment of writing), pays the interest to the lender and refunds the caller for the gas cost by sending 2 \* the gas cost using the fast gas price as base for the calculation. + +`rollover` expects following parameter: + +``` +bytes32 loanId, +bytes calldata loanDataBytes +``` + +`loanId` is the ID of the loan. + +`loanDataBytes` is a placeholder for future use. Send an empty bytes array. + +### 6. Liquidation Handling + +##### 6.1 Liquidate a position + +In order to liquidate an open position, call `liquidate` on the protocol contract. Requirements: + +- current margin < maintenance margin +- liquidator approved the protocol to spend sufficient tokens + +`liquidate` will compute the maximum seizable amount and buy it using the caller's tokens. Therefore, the caller needs to possess enough funds to purchase the tokens. The liquidator gets an discount on the collateral token price. The discount is set on State.sol and is called `liquidationIncentivePercent`. Currently, it is hardcoded to 5%. + +`liquidate` expects following parameter: + +``` +bytes32 loanId, +address receiver, +uint256 closeAmount +``` + +`loanId` is the ID of the loan + +`receiver` is the address receiving the seized funds + +`closeAmount` is the amount to liquidate. If closeAmount > maxLiquidatable, the maximum amount will be liquidated. + +### 7. Reading data from the contracts + +##### 7.1 Loans + +You can read all active loans from the smart contract calling `getActiveLoans`. All active loans for a specific user can be retrieved with ` getUserLoans`. Both function will return a array of `LoanReturnData` objects. +To query a single loan, use `getLoan`. + +`LoanReturnData` objects contain following data: + +``` +bytes32 loanId; +address loanToken; +address collateralToken; +uint256 principal; +uint256 collateral; +uint256 interestOwedPerDay; +uint256 interestDepositRemaining; +uint256 startRate; +uint256 startMargin; +uint256 maintenanceMargin; +uint256 currentMargin; +uint256 maxLoanTerm; +uint256 endTimestamp; +uint256 maxLiquidatable; +uint256 maxSeizable; +``` + +` loanId` is the ID of the loan + +`loanToken` is the address of the loan token + +`collateralToken` is the address of the collateral token + +`principal` is the complete borrowed amount (in loan tokens) + +`collateral` is the complete position size (loan + margin) (in collateral tokens) + +`interestOwedPerDay` is the interest per day + +`startRate` is the exchange rate at the beginning (collateral token to loan token) + +`startMargin` is the margin at the beginning (in percent, 18 decimals) + +`maintenanceMargin` is the minimum margin. If the current margin drops below, the position will be partially liquidated + +`currentMargin` is the current margin + +`maxLoanTerm` is the max duration of the loan + +`endTimestamp` afterwards the loan needs to be rolled over + +`maxLiquidatable` is the amount which can be liquidated (in loan tokens) + +`maxSeizable ` is the amount which can be retrieved through liquidation (in collateral tokens) + +##### 7.2 Supply and Demand + +`totalAssetSupply()` returns the total amount of funds supplied to the iToken contract by the liquidity providers (lenders). + +`totalAssetBorrow()` returns the total amount of funds which is currently borrowed from the smart contract. + +##### 7.3 Interest Rates + +To read the current interest rate for liquidity providers (lenders), call `supplyInterestRate()` . If you would like to obtain the potential interest rate after x assets are being lent to the contract, use `nextSupplyInterestRate(x)` + +To read the current interest rate for borrowers and/or traders, call `borrowInterestRate()`. If you would like to determine the interest rate to be paid considering the loan size x `nextBorrowInterestRate(x)`. + +`avgBorrowInterestRate()` returns the average interest rate paid by borrowers at the moment. Since the interest rate depends on the ratio demand/supply, some borrower are paying more than others. + +##### 7.4 iToken Price + +`tokenPrice()` returns the current iToken price denominated in underlying tokens. In case of iSUSD, the price would be given in SUSD. + +##### 7.5 Lender Balances + +Each lender has 2 balances on the iToken contract. The balance of iTokens (e.g. iSUSD) and the balance of underlying tokens (e.g. SUSD). + +`balanceOf(address)` returns the iToken balance of the given address. + +`assetBalanceOf(address)` returns the underlying token balance of the given address. + +### 8. Remarks + +The loan token (iToken) contract as well as the protocol contract act as proxies, delegating all calls to underlying contracts. Therefore, if you want to interact with them using web3, you need to use the ABIs from the contracts containing the actual logic or the interface contract. + +ABI for `LoanToken` contracts: `LoanTokenLogicLM` (if the underlying asset is any but RBTC) and `LoanTokenLogicWrbtc` (if the underlying asset is RBTC) + +ABI for `Protocol` contract: `ISovryn` + +### 9. SOV Reward Payments + +#### 9.1 Setup + +When deploying the protocol you need to: + +1. Configure the protocol address. It is an ERC20 token. +2. Configure price rates between loan and protocol tokens. Using PriceFeeds +3. Mint or approve tokens to protocol. +4. Deposit protocol token. `sovryn.depositProtocolToken(amount)` + +#### 9.2 Payment + +When a user calls one of the below functions the protocol pays SOV rewards. + +- closeWithSwap +- closeWithDeposit +- extendLoanDuration +- reduceLoanDuration +- borrow +- marginTrade +- rollover +- liquidate + +The function which pays the reward is `PayFeeReward` from `FeesHelper.sol`. + +#### 9.3 Withdraw + +The protocol can withdraw SOV tokens using `sovryn.withdrawProtocolToken()` from `ProtocolSettings.sol`. This function is executable only by the owner. + +## UML + +![UML Diagram](UML.svg) + +## Hardhat mainnet forking + +Out of the box, Hardhat's [mainnet forking mode](https://hardhat.org/hardhat-network/guides/mainnet-forking) does +not work with RSK. This package uses `patch-package` to patch the installed version of Hardhat to enable support for +forking from RSK. For more details, see [HARDHAT_FORKING.md](HARDHAT_FORKING.md). + +## Slither (pre-requisite) +Slither is enabled as the static analyzer. Currently we introduce the static anlysis to the staking modules `npm run analyze:staking-modules`.
+Before run this command, make sure that we have: + +- [Slither](https://github.com/crytic/slither) installed +- The solc version 0.5.17 installed. +We can use [`solc-select`](https://github.com/crytic/solc-select) for managing the solc version. + +[comment]: #solidoc (Start) +## Contracts + +* [Address](docs/Address.md) +* [Administered](docs/Administered.md) +* [AdminRole](docs/AdminRole.md) +* [AdvancedToken](docs/AdvancedToken.md) +* [AdvancedTokenStorage](docs/AdvancedTokenStorage.md) +* [Affiliates](docs/Affiliates.md) +* [AffiliatesEvents](docs/AffiliatesEvents.md) +* [ApprovalReceiver](docs/ApprovalReceiver.md) +* [BProPriceFeed](docs/BProPriceFeed.md) +* [CheckpointsShared](docs/CheckpointsShared.md) +* [Constants](docs/Constants.md) +* [Context](docs/Context.md) +* [DevelopmentFund](docs/DevelopmentFund.md) +* [DummyContract](docs/DummyContract.md) +* [EnumerableAddressSet](docs/EnumerableAddressSet.md) +* [EnumerableBytes32Set](docs/EnumerableBytes32Set.md) +* [EnumerableBytes4Set](docs/EnumerableBytes4Set.md) +* [ERC20](docs/ERC20.md) +* [ERC20Detailed](docs/ERC20Detailed.md) +* [ErrorDecoder](docs/ErrorDecoder.md) +* [Escrow](docs/Escrow.md) +* [EscrowReward](docs/EscrowReward.md) +* [FeedsLike](docs/FeedsLike.md) +* [FeesEvents](docs/FeesEvents.md) +* [FeeSharingCollector](docs/FeeSharingCollector.md) +* [FeeSharingCollectorProxy](docs/FeeSharingCollectorProxy.md) +* [FeeSharingCollectorStorage](docs/FeeSharingCollectorStorage.md) +* [FeesHelper](docs/FeesHelper.md) +* [FourYearVesting](docs/FourYearVesting.md) +* [FourYearVestingFactory](docs/FourYearVestingFactory.md) +* [FourYearVestingLogic](docs/FourYearVestingLogic.md) +* [FourYearVestingStorage](docs/FourYearVestingStorage.md) +* [GenericTokenSender](docs/GenericTokenSender.md) +* [GovernorAlpha](docs/GovernorAlpha.md) +* [GovernorVault](docs/GovernorVault.md) +* [IApproveAndCall](docs/IApproveAndCall.md) +* [IChai](docs/IChai.md) +* [IContractRegistry](docs/IContractRegistry.md) +* [IConverterAMM](docs/IConverterAMM.md) +* [IERC1820Registry](docs/IERC1820Registry.md) +* [IERC20_](docs/IERC20_.md) +* [IERC20](docs/IERC20.md) +* [IERC777](docs/IERC777.md) +* [IERC777Recipient](docs/IERC777Recipient.md) +* [IERC777Sender](docs/IERC777Sender.md) +* [IFeeSharingCollector](docs/IFeeSharingCollector.md) +* [IFourYearVesting](docs/IFourYearVesting.md) +* [IFourYearVestingFactory](docs/IFourYearVestingFactory.md) +* [IFunctionsList](docs/IFunctionsList.md) +* [ILiquidityMining](docs/ILiquidityMining.md) +* [ILiquidityPoolV1Converter](docs/ILiquidityPoolV1Converter.md) +* [ILoanPool](docs/ILoanPool.md) +* [ILoanToken](docs/ILoanToken.md) +* [ILoanTokenLogicBeacon](docs/ILoanTokenLogicBeacon.md) +* [ILoanTokenLogicModules](docs/ILoanTokenLogicModules.md) +* [ILoanTokenLogicProxy](docs/ILoanTokenLogicProxy.md) +* [ILoanTokenModules](docs/ILoanTokenModules.md) +* [ILoanTokenWRBTC](docs/ILoanTokenWRBTC.md) +* [ILockedSOV](docs/ILockedSOV.md) +* [IMoCState](docs/IMoCState.md) +* [IModulesProxyRegistry](docs/IModulesProxyRegistry.md) +* [Initializable](docs/Initializable.md) +* [InterestUser](docs/InterestUser.md) +* [IPot](docs/IPot.md) +* [IPriceFeeds](docs/IPriceFeeds.md) +* [IPriceFeedsExt](docs/IPriceFeedsExt.md) +* [IProtocol](docs/IProtocol.md) +* [IRSKOracle](docs/IRSKOracle.md) +* [ISovryn](docs/ISovryn.md) +* [ISovrynSwapNetwork](docs/ISovrynSwapNetwork.md) +* [IStaking](docs/IStaking.md) +* [ISwapsImpl](docs/ISwapsImpl.md) +* [ITeamVesting](docs/ITeamVesting.md) +* [ITimelock](docs/ITimelock.md) +* [IV1PoolOracle](docs/IV1PoolOracle.md) +* [IVesting](docs/IVesting.md) +* [IVestingFactory](docs/IVestingFactory.md) +* [IVestingRegistry](docs/IVestingRegistry.md) +* [IWrbtc](docs/IWrbtc.md) +* [IWrbtcERC20](docs/IWrbtcERC20.md) +* [LenderInterestStruct](docs/LenderInterestStruct.md) +* [LiquidationHelper](docs/LiquidationHelper.md) +* [LiquidityMining](docs/LiquidityMining.md) +* [LiquidityMiningConfigToken](docs/LiquidityMiningConfigToken.md) +* [LiquidityMiningProxy](docs/LiquidityMiningProxy.md) +* [LiquidityMiningStorage](docs/LiquidityMiningStorage.md) +* [LoanClosingsEvents](docs/LoanClosingsEvents.md) +* [LoanClosingsLiquidation](docs/LoanClosingsLiquidation.md) +* [LoanClosingsRollover](docs/LoanClosingsRollover.md) +* [LoanClosingsShared](docs/LoanClosingsShared.md) +* [LoanClosingsWith](docs/LoanClosingsWith.md) +* [LoanClosingsWithoutInvariantCheck](docs/LoanClosingsWithoutInvariantCheck.md) +* [LoanInterestStruct](docs/LoanInterestStruct.md) +* [LoanMaintenance](docs/LoanMaintenance.md) +* [LoanMaintenanceEvents](docs/LoanMaintenanceEvents.md) +* [LoanOpenings](docs/LoanOpenings.md) +* [LoanOpeningsEvents](docs/LoanOpeningsEvents.md) +* [LoanParamsStruct](docs/LoanParamsStruct.md) +* [LoanSettings](docs/LoanSettings.md) +* [LoanSettingsEvents](docs/LoanSettingsEvents.md) +* [LoanStruct](docs/LoanStruct.md) +* [LoanToken](docs/LoanToken.md) +* [LoanTokenBase](docs/LoanTokenBase.md) +* [LoanTokenLogicBeacon](docs/LoanTokenLogicBeacon.md) +* [LoanTokenLogicLM](docs/LoanTokenLogicLM.md) +* [LoanTokenLogicProxy](docs/LoanTokenLogicProxy.md) +* [LoanTokenLogicStandard](docs/LoanTokenLogicStandard.md) +* [LoanTokenLogicStorage](docs/LoanTokenLogicStorage.md) +* [LoanTokenLogicWrbtc](docs/LoanTokenLogicWrbtc.md) +* [LoanTokenSettingsLowerAdmin](docs/LoanTokenSettingsLowerAdmin.md) +* [LockedSOV](docs/LockedSOV.md) +* [MarginTradeStructHelpers](docs/MarginTradeStructHelpers.md) +* [Medianizer](docs/Medianizer.md) +* [ModuleCommonFunctionalities](docs/ModuleCommonFunctionalities.md) +* [ModulesCommonEvents](docs/ModulesCommonEvents.md) +* [ModulesProxy](docs/ModulesProxy.md) +* [ModulesProxyRegistry](docs/ModulesProxyRegistry.md) +* [MultiSigKeyHolders](docs/MultiSigKeyHolders.md) +* [MultiSigWallet](docs/MultiSigWallet.md) +* [Mutex](docs/Mutex.md) +* [Objects](docs/Objects.md) +* [OrderStruct](docs/OrderStruct.md) +* [OrigingVestingCreator](docs/OrigingVestingCreator.md) +* [OriginInvestorsClaim](docs/OriginInvestorsClaim.md) +* [Ownable](docs/Ownable.md) +* [Pausable](docs/Pausable.md) +* [PausableOz](docs/PausableOz.md) +* [PreviousLoanToken](docs/PreviousLoanToken.md) +* [PreviousLoanTokenSettingsLowerAdmin](docs/PreviousLoanTokenSettingsLowerAdmin.md) +* [PriceFeedRSKOracle](docs/PriceFeedRSKOracle.md) +* [PriceFeeds](docs/PriceFeeds.md) +* [PriceFeedsLocal](docs/PriceFeedsLocal.md) +* [PriceFeedsMoC](docs/PriceFeedsMoC.md) +* [PriceFeedV1PoolOracle](docs/PriceFeedV1PoolOracle.md) +* [ProtocolAffiliatesInterface](docs/ProtocolAffiliatesInterface.md) +* [ProtocolLike](docs/ProtocolLike.md) +* [ProtocolSettings](docs/ProtocolSettings.md) +* [ProtocolSettingsEvents](docs/ProtocolSettingsEvents.md) +* [ProtocolSettingsLike](docs/ProtocolSettingsLike.md) +* [ProtocolSwapExternalInterface](docs/ProtocolSwapExternalInterface.md) +* [ProtocolTokenUser](docs/ProtocolTokenUser.md) +* [Proxy](docs/Proxy.md) +* [ProxyOwnable](docs/ProxyOwnable.md) +* [ReentrancyGuard](docs/ReentrancyGuard.md) +* [RewardHelper](docs/RewardHelper.md) +* [RSKAddrValidator](docs/RSKAddrValidator.md) +* [SafeERC20](docs/SafeERC20.md) +* [SafeMath](docs/SafeMath.md) +* [SafeMath96](docs/SafeMath96.md) +* [setGet](docs/setGet.md) +* [SharedReentrancyGuard](docs/SharedReentrancyGuard.md) +* [SignedSafeMath](docs/SignedSafeMath.md) +* [SOV](docs/SOV.md) +* [sovrynProtocol](docs/sovrynProtocol.md) +* [StakingAdminModule](docs/StakingAdminModule.md) +* [StakingGovernanceModule](docs/StakingGovernanceModule.md) +* [StakingInterface](docs/StakingInterface.md) +* [StakingProxy](docs/StakingProxy.md) +* [StakingRewards](docs/StakingRewards.md) +* [StakingRewardsProxy](docs/StakingRewardsProxy.md) +* [StakingRewardsStorage](docs/StakingRewardsStorage.md) +* [StakingShared](docs/StakingShared.md) +* [StakingStakeModule](docs/StakingStakeModule.md) +* [StakingStorageModule](docs/StakingStorageModule.md) +* [StakingStorageShared](docs/StakingStorageShared.md) +* [StakingVestingModule](docs/StakingVestingModule.md) +* [StakingWithdrawModule](docs/StakingWithdrawModule.md) +* [State](docs/State.md) +* [SwapsEvents](docs/SwapsEvents.md) +* [SwapsExternal](docs/SwapsExternal.md) +* [SwapsImplLocal](docs/SwapsImplLocal.md) +* [SwapsImplSovrynSwap](docs/SwapsImplSovrynSwap.md) +* [SwapsUser](docs/SwapsUser.md) +* [TeamVesting](docs/TeamVesting.md) +* [Timelock](docs/Timelock.md) +* [TimelockHarness](docs/TimelockHarness.md) +* [TimelockInterface](docs/TimelockInterface.md) +* [TokenSender](docs/TokenSender.md) +* [UpgradableProxy](docs/UpgradableProxy.md) +* [USDTPriceFeed](docs/USDTPriceFeed.md) +* [Utils](docs/Utils.md) +* [VaultController](docs/VaultController.md) +* [Vesting](docs/Vesting.md) +* [VestingCreator](docs/VestingCreator.md) +* [VestingFactory](docs/VestingFactory.md) +* [VestingLogic](docs/VestingLogic.md) +* [VestingRegistry](docs/VestingRegistry.md) +* [VestingRegistry2](docs/VestingRegistry2.md) +* [VestingRegistry3](docs/VestingRegistry3.md) +* [VestingRegistryLogic](docs/VestingRegistryLogic.md) +* [VestingRegistryProxy](docs/VestingRegistryProxy.md) +* [VestingRegistryStorage](docs/VestingRegistryStorage.md) +* [VestingStorage](docs/VestingStorage.md) +* [WeightedStakingModule](docs/WeightedStakingModule.md) +* [WRBTC](docs/WRBTC.md) + +[comment]: #solidoc (End) + + +## Contributing + + + + + +## License + +This project is licensed under the [Apache License, Version 2.0](LICENSE). diff --git a/foundry/docs/src/SUMMARY.md b/foundry/docs/src/SUMMARY.md new file mode 100644 index 000000000..70d4d92e9 --- /dev/null +++ b/foundry/docs/src/SUMMARY.md @@ -0,0 +1,248 @@ +# Summary +- [Home](README.md) +# contracts + - [❱ connectors](contracts/connectors/README.md) + - [❱ loantoken](contracts/connectors/loantoken/README.md) + - [❱ interfaces](contracts/connectors/loantoken/interfaces/README.md) + - [FeedsLike](contracts/connectors/loantoken/interfaces/FeedsLike.sol/interface.FeedsLike.md) + - [ProtocolLike](contracts/connectors/loantoken/interfaces/ProtocolLike.sol/interface.ProtocolLike.md) + - [ProtocolSettingsLike](contracts/connectors/loantoken/interfaces/ProtocolSettingsLike.sol/interface.ProtocolSettingsLike.md) + - [❱ lib](contracts/connectors/loantoken/lib/README.md) + - [MarginTradeStructHelpers](contracts/connectors/loantoken/lib/MarginTradeStructHelpers.sol/library.MarginTradeStructHelpers.md) + - [❱ modules](contracts/connectors/loantoken/modules/README.md) + - [❱ beaconLogicLM](contracts/connectors/loantoken/modules/beaconLogicLM/README.md) + - [LoanTokenLogic](contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogic.sol/contract.LoanTokenLogic.md) + - [LoanTokenLogicLM](contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogicLM.sol/contract.LoanTokenLogicLM.md) + - [❱ beaconLogicWRBTC](contracts/connectors/loantoken/modules/beaconLogicWRBTC/README.md) + - [LoanTokenLogicWrbtc](contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtc.sol/contract.LoanTokenLogicWrbtc.md) + - [LoanTokenLogicWrbtcLM](contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtcLM.sol/contract.LoanTokenLogicWrbtcLM.md) + - [❱ shared](contracts/connectors/loantoken/modules/shared/README.md) + - [LoanTokenSettingsLowerAdmin](contracts/connectors/loantoken/modules/shared/LoanTokenSettingsLowerAdmin.sol/contract.LoanTokenSettingsLowerAdmin.md) + - [AdvancedToken](contracts/connectors/loantoken/AdvancedToken.sol/contract.AdvancedToken.md) + - [AdvancedTokenStorage](contracts/connectors/loantoken/AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md) + - [LoanToken](contracts/connectors/loantoken/LoanToken.sol/contract.LoanToken.md) + - [LoanTokenBase](contracts/connectors/loantoken/LoanTokenBase.sol/contract.LoanTokenBase.md) + - [LoanTokenLogicBeacon](contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/contract.LoanTokenLogicBeacon.md) + - [ILoanTokenLogicModules](contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/interface.ILoanTokenLogicModules.md) + - [LoanTokenLogicProxy](contracts/connectors/loantoken/LoanTokenLogicProxy.sol/contract.LoanTokenLogicProxy.md) + - [ILoanTokenLogicBeacon](contracts/connectors/loantoken/LoanTokenLogicProxy.sol/interface.ILoanTokenLogicBeacon.md) + - [LoanTokenLogicShared](contracts/connectors/loantoken/LoanTokenLogicShared.sol/contract.LoanTokenLogicShared.md) + - [LoanTokenLogicSplit](contracts/connectors/loantoken/LoanTokenLogicSplit.sol/contract.LoanTokenLogicSplit.md) + - [LoanTokenLogicStandard](contracts/connectors/loantoken/LoanTokenLogicStandard.sol/contract.LoanTokenLogicStandard.md) + - [LoanTokenLogicStorage](contracts/connectors/loantoken/LoanTokenLogicStorage.sol/contract.LoanTokenLogicStorage.md) + - [Pausable](contracts/connectors/loantoken/Pausable.sol/contract.Pausable.md) + - [❱ core](contracts/core/README.md) + - [❱ objects](contracts/core/objects/README.md) + - [LenderInterestStruct](contracts/core/objects/LenderInterestStruct.sol/contract.LenderInterestStruct.md) + - [LoanInterestStruct](contracts/core/objects/LoanInterestStruct.sol/contract.LoanInterestStruct.md) + - [LoanParamsStruct](contracts/core/objects/LoanParamsStruct.sol/contract.LoanParamsStruct.md) + - [LoanStruct](contracts/core/objects/LoanStruct.sol/contract.LoanStruct.md) + - [OrderStruct](contracts/core/objects/OrderStruct.sol/contract.OrderStruct.md) + - [Objects](contracts/core/Objects.sol/contract.Objects.md) + - [sovrynProtocol](contracts/core/Protocol.sol/contract.sovrynProtocol.md) + - [State](contracts/core/State.sol/contract.State.md) + - [❱ escrow](contracts/escrow/README.md) + - [Escrow](contracts/escrow/Escrow.sol/contract.Escrow.md) + - [EscrowReward](contracts/escrow/EscrowReward.sol/contract.EscrowReward.md) + - [❱ events](contracts/events/README.md) + - [AffiliatesEvents](contracts/events/AffiliatesEvents.sol/contract.AffiliatesEvents.md) + - [FeesEvents](contracts/events/FeesEvents.sol/contract.FeesEvents.md) + - [LoanClosingsEvents](contracts/events/LoanClosingsEvents.sol/contract.LoanClosingsEvents.md) + - [LoanMaintenanceEvents](contracts/events/LoanMaintenanceEvents.sol/contract.LoanMaintenanceEvents.md) + - [LoanOpeningsEvents](contracts/events/LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md) + - [LoanSettingsEvents](contracts/events/LoanSettingsEvents.sol/contract.LoanSettingsEvents.md) + - [ModulesCommonEvents](contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + - [ProtocolSettingsEvents](contracts/events/ProtocolSettingsEvents.sol/contract.ProtocolSettingsEvents.md) + - [SwapsEvents](contracts/events/SwapsEvents.sol/contract.SwapsEvents.md) + - [❱ farm](contracts/farm/README.md) + - [ILiquidityMining](contracts/farm/ILiquidityMining.sol/interface.ILiquidityMining.md) + - [LiquidityMining](contracts/farm/LiquidityMining.sol/contract.LiquidityMining.md) + - [LiquidityMiningConfigToken](contracts/farm/LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md) + - [LiquidityMiningProxy](contracts/farm/LiquidityMiningProxy.sol/contract.LiquidityMiningProxy.md) + - [LiquidityMiningStorage](contracts/farm/LiquidityMiningStorage.sol/contract.LiquidityMiningStorage.md) + - [❱ feeds](contracts/feeds/README.md) + - [❱ testnet](contracts/feeds/testnet/README.md) + - [MockMoCMedianizer](contracts/feeds/testnet/MockMoCMedianizer.sol/contract.MockMoCMedianizer.md) + - [PriceFeedsLocal](contracts/feeds/testnet/PriceFeedsLocal.sol/contract.PriceFeedsLocal.md) + - [BProPriceFeed](contracts/feeds/BProPriceFeed.sol/contract.BProPriceFeed.md) + - [IExternalPriceFeed](contracts/feeds/DummyFallbackOracle.sol/interface.IExternalPriceFeed.md) + - [DummyFallbackOracle](contracts/feeds/DummyFallbackOracle.sol/contract.DummyFallbackOracle.md) + - [IMoCState](contracts/feeds/IMoCState.sol/interface.IMoCState.md) + - [IPriceFeeds](contracts/feeds/IPriceFeeds.sol/interface.IPriceFeeds.md) + - [IRSKOracle](contracts/feeds/IRSKOracle.sol/interface.IRSKOracle.md) + - [IV1PoolOracle](contracts/feeds/IV1PoolOracle.sol/interface.IV1PoolOracle.md) + - [ILiquidityPoolV1Converter](contracts/feeds/IV1PoolOracle.sol/interface.ILiquidityPoolV1Converter.md) + - [PriceFeedRSKOracle](contracts/feeds/PriceFeedRSKOracle.sol/contract.PriceFeedRSKOracle.md) + - [PriceFeedV1PoolOracle](contracts/feeds/PriceFeedV1PoolOracle.sol/contract.PriceFeedV1PoolOracle.md) + - [IPriceFeedsExt](contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md) + - [PriceFeeds](contracts/feeds/PriceFeeds.sol/contract.PriceFeeds.md) + - [Constants](contracts/feeds/PriceFeedsConstants.sol/contract.Constants.md) + - [Medianizer](contracts/feeds/PriceFeedsMoC.sol/interface.Medianizer.md) + - [IPriceFeedLatestAnswer](contracts/feeds/PriceFeedsMoC.sol/interface.IPriceFeedLatestAnswer.md) + - [PriceFeedsMoC](contracts/feeds/PriceFeedsMoC.sol/contract.PriceFeedsMoC.md) + - [USDTPriceFeed](contracts/feeds/USDTPriceFeed.sol/contract.USDTPriceFeed.md) + - [❱ governance](contracts/governance/README.md) + - [❱ FeeSharingCollector](contracts/governance/FeeSharingCollector/README.md) + - [FeeSharingCollector](contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/contract.FeeSharingCollector.md) + - [ILoanToken](contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanToken.md) + - [ILoanTokenWRBTC](contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanTokenWRBTC.md) + - [FeeSharingCollectorProxy](contracts/governance/FeeSharingCollector/FeeSharingCollectorProxy.sol/contract.FeeSharingCollectorProxy.md) + - [FeeSharingCollectorStorage](contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/contract.FeeSharingCollectorStorage.md) + - [IProtocol](contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/interface.IProtocol.md) + - [❱ Staking](contracts/governance/Staking/README.md) + - [❱ interfaces](contracts/governance/Staking/interfaces/README.md) + - [IStaking](contracts/governance/Staking/interfaces/IStaking.sol/interface.IStaking.md) + - [❱ modules](contracts/governance/Staking/modules/README.md) + - [❱ shared](contracts/governance/Staking/modules/shared/README.md) + - [CheckpointsShared](contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md) + - [StakingShared](contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md) + - [StakingStorageShared](contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md) + - [StakingAdminModule](contracts/governance/Staking/modules/StakingAdminModule.sol/contract.StakingAdminModule.md) + - [StakingGovernanceModule](contracts/governance/Staking/modules/StakingGovernanceModule.sol/contract.StakingGovernanceModule.md) + - [StakingStakeModule](contracts/governance/Staking/modules/StakingStakeModule.sol/contract.StakingStakeModule.md) + - [StakingStorageModule](contracts/governance/Staking/modules/StakingStorageModule.sol/contract.StakingStorageModule.md) + - [StakingVestingModule](contracts/governance/Staking/modules/StakingVestingModule.sol/contract.StakingVestingModule.md) + - [StakingWithdrawModule](contracts/governance/Staking/modules/StakingWithdrawModule.sol/contract.StakingWithdrawModule.md) + - [WeightedStakingModule](contracts/governance/Staking/modules/WeightedStakingModule.sol/contract.WeightedStakingModule.md) + - [SafeMath96](contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md) + - [StakingProxy](contracts/governance/Staking/StakingProxy.sol/contract.StakingProxy.md) + - [❱ StakingRewards](contracts/governance/StakingRewards/README.md) + - [StakingRewards](contracts/governance/StakingRewards/StakingRewards.sol/contract.StakingRewards.md) + - [StakingRewardsOs](contracts/governance/StakingRewards/StakingRewardsOs.sol/contract.StakingRewardsOs.md) + - [StakingRewardsOsProxy](contracts/governance/StakingRewards/StakingRewardsOsProxy.sol/contract.StakingRewardsOsProxy.md) + - [StakingRewardsOsStorage](contracts/governance/StakingRewards/StakingRewardsOsStorage.sol/contract.StakingRewardsOsStorage.md) + - [StakingRewardsProxy](contracts/governance/StakingRewards/StakingRewardsProxy.sol/contract.StakingRewardsProxy.md) + - [StakingRewardsStorage](contracts/governance/StakingRewards/StakingRewardsStorage.sol/contract.StakingRewardsStorage.md) + - [❱ Vesting](contracts/governance/Vesting/README.md) + - [❱ fouryear](contracts/governance/Vesting/fouryear/README.md) + - [FourYearVesting](contracts/governance/Vesting/fouryear/FourYearVesting.sol/contract.FourYearVesting.md) + - [FourYearVestingFactory](contracts/governance/Vesting/fouryear/FourYearVestingFactory.sol/contract.FourYearVestingFactory.md) + - [FourYearVestingLogic](contracts/governance/Vesting/fouryear/FourYearVestingLogic.sol/contract.FourYearVestingLogic.md) + - [FourYearVestingStorage](contracts/governance/Vesting/fouryear/FourYearVestingStorage.sol/contract.FourYearVestingStorage.md) + - [IFourYearVesting](contracts/governance/Vesting/fouryear/IFourYearVesting.sol/interface.IFourYearVesting.md) + - [IFourYearVestingFactory](contracts/governance/Vesting/fouryear/IFourYearVestingFactory.sol/interface.IFourYearVestingFactory.md) + - [DevelopmentFund](contracts/governance/Vesting/DevelopmentFund.sol/contract.DevelopmentFund.md) + - [GenericTokenSender](contracts/governance/Vesting/GenericTokenSender.sol/contract.GenericTokenSender.md) + - [ITeamVesting](contracts/governance/Vesting/ITeamVesting.sol/interface.ITeamVesting.md) + - [IVesting](contracts/governance/Vesting/IVesting.sol/interface.IVesting.md) + - [IVestingFactory](contracts/governance/Vesting/IVestingFactory.sol/interface.IVestingFactory.md) + - [IVestingRegistry](contracts/governance/Vesting/IVestingRegistry.sol/interface.IVestingRegistry.md) + - [OriginInvestorsClaim](contracts/governance/Vesting/OriginInvestorsClaim.sol/contract.OriginInvestorsClaim.md) + - [OrigingVestingCreator](contracts/governance/Vesting/OrigingVestingCreator.sol/contract.OrigingVestingCreator.md) + - [TeamVesting](contracts/governance/Vesting/TeamVesting.sol/contract.TeamVesting.md) + - [TokenSender](contracts/governance/Vesting/TokenSender.sol/contract.TokenSender.md) + - [Vesting](contracts/governance/Vesting/Vesting.sol/contract.Vesting.md) + - [VestingCreator](contracts/governance/Vesting/VestingCreator.sol/contract.VestingCreator.md) + - [VestingFactory](contracts/governance/Vesting/VestingFactory.sol/contract.VestingFactory.md) + - [VestingLogic](contracts/governance/Vesting/VestingLogic.sol/contract.VestingLogic.md) + - [VestingRegistry](contracts/governance/Vesting/VestingRegistry.sol/contract.VestingRegistry.md) + - [VestingRegistry2](contracts/governance/Vesting/VestingRegistry2.sol/contract.VestingRegistry2.md) + - [VestingRegistry3](contracts/governance/Vesting/VestingRegistry3.sol/contract.VestingRegistry3.md) + - [VestingRegistryLogic](contracts/governance/Vesting/VestingRegistryLogic.sol/contract.VestingRegistryLogic.md) + - [VestingRegistryProxy](contracts/governance/Vesting/VestingRegistryProxy.sol/contract.VestingRegistryProxy.md) + - [VestingRegistryStorage](contracts/governance/Vesting/VestingRegistryStorage.sol/contract.VestingRegistryStorage.md) + - [VestingStorage](contracts/governance/Vesting/VestingStorage.sol/contract.VestingStorage.md) + - [ApprovalReceiver](contracts/governance/ApprovalReceiver.sol/contract.ApprovalReceiver.md) + - [ErrorDecoder](contracts/governance/ErrorDecoder.sol/contract.ErrorDecoder.md) + - [GovernorAlpha](contracts/governance/GovernorAlpha.sol/contract.GovernorAlpha.md) + - [TimelockInterface](contracts/governance/GovernorAlpha.sol/interface.TimelockInterface.md) + - [StakingInterface](contracts/governance/GovernorAlpha.sol/interface.StakingInterface.md) + - [GovernorVault](contracts/governance/GovernorVault.sol/contract.GovernorVault.md) + - [IFeeSharingCollector](contracts/governance/IFeeSharingCollector.sol/interface.IFeeSharingCollector.md) + - [ITimelock](contracts/governance/Timelock.sol/interface.ITimelock.md) + - [Timelock](contracts/governance/Timelock.sol/contract.Timelock.md) + - [❱ interfaces](contracts/interfaces/README.md) + - [IPot](contracts/interfaces/IChai.sol/interface.IPot.md) + - [IChai](contracts/interfaces/IChai.sol/contract.IChai.md) + - [IConverterAMM](contracts/interfaces/IConverterAMM.sol/interface.IConverterAMM.md) + - [IERC20](contracts/interfaces/IERC20.sol/contract.IERC20.md) + - [IERC20Mintable](contracts/interfaces/IERC20Mintable.sol/contract.IERC20Mintable.md) + - [IERC777](contracts/interfaces/IERC777.sol/interface.IERC777.md) + - [IERC777Recipient](contracts/interfaces/IERC777Recipient.sol/interface.IERC777Recipient.md) + - [IERC777Sender](contracts/interfaces/IERC777Sender.sol/interface.IERC777Sender.md) + - [ILoanPool](contracts/interfaces/ILoanPool.sol/interface.ILoanPool.md) + - [ILoanTokenLogicProxy](contracts/interfaces/ILoanTokenLogicProxy.sol/interface.ILoanTokenLogicProxy.md) + - [ILoanTokenModules](contracts/interfaces/ILoanTokenModules.sol/interface.ILoanTokenModules.md) + - [ISovryn](contracts/interfaces/ISovryn.sol/contract.ISovryn.md) + - [IWrbtc](contracts/interfaces/IWrbtc.sol/interface.IWrbtc.md) + - [IWrbtcERC20](contracts/interfaces/IWrbtcERC20.sol/contract.IWrbtcERC20.md) + - [❱ locked](contracts/locked/README.md) + - [ILockedSOV](contracts/locked/ILockedSOV.sol/interface.ILockedSOV.md) + - [LockedSOV](contracts/locked/LockedSOV.sol/contract.LockedSOV.md) + - [❱ mixins](contracts/mixins/README.md) + - [EnumerableAddressSet](contracts/mixins/EnumerableAddressSet.sol/library.EnumerableAddressSet.md) + - [EnumerableBytes32Set](contracts/mixins/EnumerableBytes32Set.sol/library.EnumerableBytes32Set.md) + - [EnumerableBytes4Set](contracts/mixins/EnumerableBytes4Set.sol/library.EnumerableBytes4Set.md) + - [FeesHelper](contracts/mixins/FeesHelper.sol/contract.FeesHelper.md) + - [InterestUser](contracts/mixins/InterestUser.sol/contract.InterestUser.md) + - [LiquidationHelper](contracts/mixins/LiquidationHelper.sol/contract.LiquidationHelper.md) + - [ModuleCommonFunctionalities](contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + - [ProtocolTokenUser](contracts/mixins/ProtocolTokenUser.sol/contract.ProtocolTokenUser.md) + - [RewardHelper](contracts/mixins/RewardHelper.sol/contract.RewardHelper.md) + - [VaultController](contracts/mixins/VaultController.sol/contract.VaultController.md) + - [❱ modules](contracts/modules/README.md) + - [❱ interfaces](contracts/modules/interfaces/README.md) + - [ProtocolAffiliatesInterface](contracts/modules/interfaces/ProtocolAffiliatesInterface.sol/interface.ProtocolAffiliatesInterface.md) + - [ProtocolSwapExternalInterface](contracts/modules/interfaces/ProtocolSwapExternalInterface.sol/interface.ProtocolSwapExternalInterface.md) + - [Affiliates](contracts/modules/Affiliates.sol/contract.Affiliates.md) + - [LoanClosingsLiquidation](contracts/modules/LoanClosingsLiquidation.sol/contract.LoanClosingsLiquidation.md) + - [LoanClosingsRollover](contracts/modules/LoanClosingsRollover.sol/contract.LoanClosingsRollover.md) + - [LoanClosingsShared](contracts/modules/LoanClosingsShared.sol/contract.LoanClosingsShared.md) + - [LoanClosingsWith](contracts/modules/LoanClosingsWith.sol/contract.LoanClosingsWith.md) + - [LoanMaintenance](contracts/modules/LoanMaintenance.sol/contract.LoanMaintenance.md) + - [LoanOpenings](contracts/modules/LoanOpenings.sol/contract.LoanOpenings.md) + - [LoanSettings](contracts/modules/LoanSettings.sol/contract.LoanSettings.md) + - [ProtocolSettings](contracts/modules/ProtocolSettings.sol/contract.ProtocolSettings.md) + - [SwapsExternal](contracts/modules/SwapsExternal.sol/contract.SwapsExternal.md) + - [SwapsImplSovrynSwapModule](contracts/modules/SwapsImplSovrynSwapModule.sol/contract.SwapsImplSovrynSwapModule.md) + - [❱ multisig](contracts/multisig/README.md) + - [MultiSigKeyHolders](contracts/multisig/MultiSigKeyHolders.sol/contract.MultiSigKeyHolders.md) + - [MultiSigWallet](contracts/multisig/MultiSigWallet.sol/contract.MultiSigWallet.md) + - [❱ openzeppelin](contracts/openzeppelin/README.md) + - [Address](contracts/openzeppelin/Address.sol/library.Address.md) + - [Context](contracts/openzeppelin/Context.sol/contract.Context.md) + - [ERC20](contracts/openzeppelin/ERC20.sol/contract.ERC20.md) + - [ERC20Detailed](contracts/openzeppelin/ERC20Detailed.sol/contract.ERC20Detailed.md) + - [IERC20_](contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md) + - [Initializable](contracts/openzeppelin/Initializable.sol/contract.Initializable.md) + - [Ownable](contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + - [PausableOz](contracts/openzeppelin/PausableOz.sol/contract.PausableOz.md) + - [ReentrancyGuard](contracts/openzeppelin/ReentrancyGuard.sol/contract.ReentrancyGuard.md) + - [SafeERC20](contracts/openzeppelin/SafeERC20.sol/library.SafeERC20.md) + - [SafeMath](contracts/openzeppelin/SafeMath.sol/library.SafeMath.md) + - [SignedSafeMath](contracts/openzeppelin/SignedSafeMath.sol/library.SignedSafeMath.md) + - [❱ proxy](contracts/proxy/README.md) + - [❱ TransparentUpgradableProxy](contracts/proxy/TransparentUpgradableProxy/README.md) + - [TransparentUpgradableProxyAdmin](contracts/proxy/TransparentUpgradableProxy/TransparentUpgradableProxyAdmin.sol/contract.TransparentUpgradableProxyAdmin.md) + - [❱ modules](contracts/proxy/modules/README.md) + - [❱ interfaces](contracts/proxy/modules/interfaces/README.md) + - [IFunctionsList](contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md) + - [IModulesProxyRegistry](contracts/proxy/modules/interfaces/IModulesProxyRegistry.sol/contract.IModulesProxyRegistry.md) + - [ModulesProxy](contracts/proxy/modules/ModulesProxy.sol/contract.ModulesProxy.md) + - [ModulesProxyRegistry](contracts/proxy/modules/ModulesProxyRegistry.sol/contract.ModulesProxyRegistry.md) + - [Proxy](contracts/proxy/Proxy.sol/contract.Proxy.md) + - [UpgradableProxy](contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + - [❱ reentrancy](contracts/reentrancy/README.md) + - [Mutex](contracts/reentrancy/Mutex.sol/contract.Mutex.md) + - [SharedReentrancyGuard](contracts/reentrancy/SharedReentrancyGuard.sol/contract.SharedReentrancyGuard.md) + - [❱ rsk](contracts/rsk/README.md) + - [RSKAddrValidator](contracts/rsk/RSKAddrValidator.sol/library.RSKAddrValidator.md) + - [❱ swaps](contracts/swaps/README.md) + - [❱ connectors](contracts/swaps/connectors/README.md) + - [❱ interfaces](contracts/swaps/connectors/interfaces/README.md) + - [IContractRegistry](contracts/swaps/connectors/interfaces/IContractRegistry.sol/contract.IContractRegistry.md) + - [ISovrynSwapNetwork](contracts/swaps/connectors/interfaces/ISovrynSwapNetwork.sol/contract.ISovrynSwapNetwork.md) + - [❱ testnet](contracts/swaps/connectors/testnet/README.md) + - [SwapsImplLocal](contracts/swaps/connectors/testnet/SwapsImplLocal.sol/contract.SwapsImplLocal.md) + - [SwapsImplSovrynSwap](contracts/swaps/connectors/SwapsImplSovrynSwap.sol/contract.SwapsImplSovrynSwap.md) + - [SwapsImplSovrynSwapLib](contracts/swaps/connectors/SwapsImplSovrynSwapLib.sol/library.SwapsImplSovrynSwapLib.md) + - [SwapsUser](contracts/swaps/SwapsUser.sol/contract.SwapsUser.md) + - [❱ token](contracts/token/README.md) + - [IApproveAndCall](contracts/token/IApproveAndCall.sol/interface.IApproveAndCall.md) + - [OsSOV](contracts/token/OsSOV.sol/contract.OsSOV.md) + - [SOV](contracts/token/SOV.sol/contract.SOV.md) + - [❱ utils](contracts/utils/README.md) + - [AdminRole](contracts/utils/AdminRole.sol/contract.AdminRole.md) + - [PausableRole](contracts/utils/PausableRole.sol/contract.PausableRole.md) + - [ProxyOwnable](contracts/utils/ProxyOwnable.sol/contract.ProxyOwnable.md) + - [Utils](contracts/utils/Utils.sol/library.Utils.md) diff --git a/foundry/docs/src/contracts/README.md b/foundry/docs/src/contracts/README.md new file mode 100644 index 000000000..6f911c19a --- /dev/null +++ b/foundry/docs/src/contracts/README.md @@ -0,0 +1,22 @@ + + +# Contents +- [connectors](/contracts/connectors) +- [core](/contracts/core) +- [escrow](/contracts/escrow) +- [events](/contracts/events) +- [farm](/contracts/farm) +- [feeds](/contracts/feeds) +- [governance](/contracts/governance) +- [interfaces](/contracts/interfaces) +- [locked](/contracts/locked) +- [mixins](/contracts/mixins) +- [modules](/contracts/modules) +- [multisig](/contracts/multisig) +- [openzeppelin](/contracts/openzeppelin) +- [proxy](/contracts/proxy) +- [reentrancy](/contracts/reentrancy) +- [rsk](/contracts/rsk) +- [swaps](/contracts/swaps) +- [token](/contracts/token) +- [utils](/contracts/utils) diff --git a/foundry/docs/src/contracts/connectors/README.md b/foundry/docs/src/contracts/connectors/README.md new file mode 100644 index 000000000..e82b0a1bf --- /dev/null +++ b/foundry/docs/src/contracts/connectors/README.md @@ -0,0 +1,4 @@ + + +# Contents +- [loantoken](/contracts/connectors/loantoken) diff --git a/foundry/docs/src/contracts/connectors/loantoken/AdvancedToken.sol/contract.AdvancedToken.md b/foundry/docs/src/contracts/connectors/loantoken/AdvancedToken.sol/contract.AdvancedToken.md new file mode 100644 index 000000000..e94c81329 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/AdvancedToken.sol/contract.AdvancedToken.md @@ -0,0 +1,94 @@ +# AdvancedToken +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/AdvancedToken.sol) + +**Inherits:** +[AdvancedTokenStorage](/contracts/connectors/loantoken/AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized margin +trading and lending https://bzx.network similar to the dYdX protocol. +AdvancedToken implements standard ERC-20 approval, mint and burn token functionality. +Logic (AdvancedToken) is kept aside from storage (AdvancedTokenStorage). +For example, LoanTokenLogicDai contract uses AdvancedToken::_mint() to mint +its Loan Dai iTokens. + + +## Functions +### approve + +Set an amount as the allowance of `spender` over the caller's tokens. +Returns a boolean value indicating whether the operation succeeded. +IMPORTANT: Beware that changing an allowance with this method brings the risk +that someone may use both the old and the new allowance by unfortunate +transaction ordering. One possible solution to mitigate this race +condition is to first reduce the spender's allowance to 0 and set the +desired value afterwards: +https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 +Emits an {Approval} event. + + +```solidity +function approve(address _spender, uint256 _value) public returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_spender`|`address`|The account address that will be able to spend the tokens.| +|`_value`|`uint256`|The amount of tokens allowed to spend.| + + +### _mint + +The iToken minting process. Meant to issue Loan iTokens. +Lenders are able to open an iToken position, by minting them. +This function is called by LoanTokenLogicStandard::_mintToken + + +```solidity +function _mint(address _to, uint256 _tokenAmount, uint256 _assetAmount, uint256 _price) internal returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_to`|`address`|The recipient of the minted tTokens.| +|`_tokenAmount`|`uint256`|The amount of iTokens to be minted.| +|`_assetAmount`|`uint256`|The amount of lended tokens (asset to lend).| +|`_price`|`uint256`|The price of the lended tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The updated balance of the recipient.| + + +### _burn + +The iToken burning process. Meant to destroy Loan iTokens. +Lenders are able to close an iToken position, by burning them. +This function is called by LoanTokenLogicStandard::_burnToken + + +```solidity +function _burn(address _who, uint256 _tokenAmount, uint256 _assetAmount, uint256 _price) internal returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_who`|`address`|The owner of the iTokens to burn.| +|`_tokenAmount`|`uint256`|The amount of iTokens to burn.| +|`_assetAmount`|`uint256`|The amount of lended tokens.| +|`_price`|`uint256`|The price of the lended tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The updated balance of the iTokens owner.| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md b/foundry/docs/src/contracts/connectors/loantoken/AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md new file mode 100644 index 000000000..3cbb552f0 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md @@ -0,0 +1,148 @@ +# AdvancedTokenStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/AdvancedTokenStorage.sol) + +**Inherits:** +[LoanTokenBase](/contracts/connectors/loantoken/LoanTokenBase.sol/contract.LoanTokenBase.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +AdvancedTokenStorage implements standard ERC-20 getters functionality: +totalSupply, balanceOf, allowance and some events. +iToken logic is divided into several contracts AdvancedToken, +AdvancedTokenStorage and LoanTokenBase. + + +## State Variables +### balances + +```solidity +mapping(address => uint256) internal balances; +``` + + +### allowed + +```solidity +mapping(address => mapping(address => uint256)) internal allowed; +``` + + +### totalSupply_ + +```solidity +uint256 internal totalSupply_; +``` + + +## Functions +### totalSupply + +Get the total supply of iTokens. + + +```solidity +function totalSupply() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The total number of iTokens in existence as of now.| + + +### balanceOf + +Get the amount of iTokens owned by an account. + + +```solidity +function balanceOf(address _owner) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|The account owner of the iTokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The number of iTokens an account owns.| + + +### allowance + +Get the amount of iTokens allowed to be spent by a +given account on behalf of the owner. + + +```solidity +function allowance(address _owner, address _spender) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|The account owner of the iTokens.| +|`_spender`|`address`|The account allowed to send the iTokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The number of iTokens an account is allowing the spender to send on its behalf.| + + +## Events +### Transfer +topic: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +### Approval +topic: 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 + + +```solidity +event Approval(address indexed owner, address indexed spender, uint256 value); +``` + +### AllowanceUpdate +topic: 0x628e75c63c1873bcd3885f7aee9f58ee36f60dc789b2a6b3a978c4189bc548ba + + +```solidity +event AllowanceUpdate(address indexed owner, address indexed spender, uint256 valueBefore, uint256 valueAfter); +``` + +### Mint +topic: 0xb4c03061fb5b7fed76389d5af8f2e0ddb09f8c70d1333abbb62582835e10accb + + +```solidity +event Mint(address indexed minter, uint256 tokenAmount, uint256 assetAmount, uint256 price); +``` + +### Burn +topic: 0x743033787f4738ff4d6a7225ce2bd0977ee5f86b91a902a58f5e4d0b297b4644 + + +```solidity +event Burn(address indexed burner, uint256 tokenAmount, uint256 assetAmount, uint256 price); +``` + +### FlashBorrow +topic: 0xc688ff9bd4a1c369dd44c5cf64efa9db6652fb6b280aa765cd43f17d256b816e + + +```solidity +event FlashBorrow(address borrower, address target, address loanToken, uint256 loanAmount); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanToken.sol/contract.LoanToken.md b/foundry/docs/src/contracts/connectors/loantoken/LoanToken.sol/contract.LoanToken.md new file mode 100644 index 000000000..4468a9408 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanToken.sol/contract.LoanToken.md @@ -0,0 +1,169 @@ +# LoanToken +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanToken.sol) + +**Inherits:** +[AdvancedTokenStorage](/contracts/connectors/loantoken/AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +A loan token (iToken) is created as a proxy to an upgradable token contract. +Examples of loan tokens on Sovryn are iRBTC, iDOC, iUSDT, iBPro, +iSOV (near future). +Lenders receive iTokens that collect interest from the lending pool +which they can redeem by withdrawing them. The i in iToken stands for interest. +Do not confuse iTokens with underlying tokens. iDOC is an iToken (loan token) +whilest DOC is the underlying token (currency). + +*TODO: can I change this proxy to EIP-1822 proxy standard, please. +https://eips.ethereum.org/EIPS/eip-1822. It's really hard to work with this.* + + +## State Variables +### sovrynContractAddress +*It is important to maintain the variables order so the delegate +calls can access sovrynContractAddress and wrbtcTokenAddress* + + +```solidity +address public sovrynContractAddress; +``` + + +### wrbtcTokenAddress + +```solidity +address public wrbtcTokenAddress; +``` + + +### target_ + +```solidity +address internal target_; +``` + + +### admin + +```solidity +address public admin; +``` + + +## Functions +### constructor + +Deploy loan token proxy. +Sets ERC20 parameters of the token. + + +```solidity +constructor(address _newOwner, address _newTarget, address _sovrynContractAddress, address _wrbtcTokenAddress) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newOwner`|`address`|The address of the new owner.| +|`_newTarget`|`address`|The address of the new target contract instance.| +|`_sovrynContractAddress`|`address`|The address of the new sovrynContract instance.| +|`_wrbtcTokenAddress`|`address`|The address of the new wrBTC instance.| + + +### function + +Fallback function performs a delegate call +to the actual implementation address is pointing this proxy. +Returns whatever the implementation call returns. + + +```solidity +function() external payable; +``` + +### setTarget + +Public owner setter for target address. + +*Calls internal setter.* + + +```solidity +function setTarget(address _newTarget) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newTarget`|`address`|The address of the new target contract instance.| + + +### _setTarget + +Internal setter for target address. + + +```solidity +function _setTarget(address _newTarget) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newTarget`|`address`|The address of the new target contract instance.| + + +### _setSovrynContractAddress + +Internal setter for sovrynContract address. + + +```solidity +function _setSovrynContractAddress(address _sovrynContractAddress) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sovrynContractAddress`|`address`|The address of the new sovrynContract instance.| + + +### _setWrbtcTokenAddress + +Internal setter for wrBTC address. + + +```solidity +function _setWrbtcTokenAddress(address _wrbtcTokenAddress) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_wrbtcTokenAddress`|`address`|The address of the new wrBTC instance.| + + +### initialize + +Public owner cloner for pointed loan token. +Sets ERC20 parameters of the token. + +*TODO: add check for double init. +idk but init usually can be called only once.* + + +```solidity +function initialize(address _loanTokenAddress, string memory _name, string memory _symbol) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_loanTokenAddress`|`address`|The address of the pointed loan token instance.| +|`_name`|`string`|The ERC20 token name.| +|`_symbol`|`string`|The ERC20 token symbol.| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenBase.sol/contract.LoanTokenBase.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenBase.sol/contract.LoanTokenBase.md new file mode 100644 index 000000000..6bcd1f4a7 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenBase.sol/contract.LoanTokenBase.md @@ -0,0 +1,185 @@ +# LoanTokenBase +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenBase.sol) + +**Inherits:** +[ReentrancyGuard](/contracts/openzeppelin/ReentrancyGuard.sol/contract.ReentrancyGuard.md), [SharedReentrancyGuard](/contracts/reentrancy/SharedReentrancyGuard.sol/contract.SharedReentrancyGuard.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md), [Pausable](/contracts/connectors/loantoken/Pausable.sol/contract.Pausable.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized margin +trading and lending https://bzx.network similar to the dYdX protocol. +Specific loan related storage for iTokens. +An loan token or iToken is a representation of a user funds in the pool and the +interest they've earned. The redemption value of iTokens continually increase +from the accretion of interest paid into the lending pool by borrowers. The user +can sell iTokens to exit its position. The user might potentially use them as +collateral wherever applicable. +There are three main tokens in the bZx system, iTokens, pTokens, and BZRX tokens. +The bZx system of lending and borrowing depends on iTokens and pTokens, and when +users lend or borrow money on bZx, their crypto assets go into or come out of +global liquidity pools, which are pools of funds shared between many different +exchanges. When lenders supply funds into the global liquidity pools, they +automatically receive iTokens; When users borrow money to open margin trading +positions, they automatically receive pTokens. The system is also designed to +use the BZRX tokens, which are only used to pay fees on the network currently. + + +## State Variables +### WEI_PRECISION + +```solidity +uint256 internal constant WEI_PRECISION = 10 ** 18; +``` + + +### WEI_PERCENT_PRECISION + +```solidity +uint256 internal constant WEI_PERCENT_PRECISION = 10 ** 20; +``` + + +### sWEI_PRECISION + +```solidity +int256 internal constant sWEI_PRECISION = 10 ** 18; +``` + + +### name +Standard ERC-20 properties + + +```solidity +string public name; +``` + + +### symbol + +```solidity +string public symbol; +``` + + +### decimals + +```solidity +uint8 public decimals; +``` + + +### loanTokenAddress +The address of the loan token (asset to lend) instance. + + +```solidity +address public loanTokenAddress; +``` + + +### baseRate + +```solidity +uint256 public baseRate; +``` + + +### rateMultiplier + +```solidity +uint256 public rateMultiplier; +``` + + +### lowUtilBaseRate + +```solidity +uint256 public lowUtilBaseRate; +``` + + +### lowUtilRateMultiplier + +```solidity +uint256 public lowUtilRateMultiplier; +``` + + +### targetLevel + +```solidity +uint256 public targetLevel; +``` + + +### kinkLevel + +```solidity +uint256 public kinkLevel; +``` + + +### maxScaleRate + +```solidity +uint256 public maxScaleRate; +``` + + +### _flTotalAssetSupply + +```solidity +uint256 internal _flTotalAssetSupply; +``` + + +### checkpointSupply + +```solidity +uint256 public checkpointSupply; +``` + + +### initialPrice + +```solidity +uint256 public initialPrice; +``` + + +### lastSettleTime_ +uint88 for tight packing -> 8 + 88 + 160 = 256 + + +```solidity +uint88 internal lastSettleTime_; +``` + + +### loanParamsIds +Mapping of keccak256(collateralToken, isTorqueLoan) to loanParamsId. + + +```solidity +mapping(uint256 => bytes32) public loanParamsIds; +``` + + +### checkpointPrices_ +Price of token at last user checkpoint. + + +```solidity +mapping(address => uint256) internal checkpointPrices_; +``` + + +### transactionLimit + +```solidity +mapping(address => uint256) public transactionLimit; +``` + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/contract.LoanTokenLogicBeacon.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/contract.LoanTokenLogicBeacon.md new file mode 100644 index 000000000..ff75fd76a --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/contract.LoanTokenLogicBeacon.md @@ -0,0 +1,190 @@ +# LoanTokenLogicBeacon +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol) + +**Inherits:** +[PausableRole](/contracts/utils/PausableRole.sol/contract.PausableRole.md) + +This contract stored the target logic implementation of LoanTokens which has the same logic implementation (LoanTokenLogicLM / LoanTokenLogicWrbtc) +Apart from storing the target logic implementation, this contract also has a pause functionality. +By implementing pause/unpause functionality in this beacon contract, we can pause the loan token that has the same Logic (LoanTokenLogicLM / LoanTokenLogicWrbtc) at one call. +Meanwhile the pause/unpause function in the LoanTokenLogicProxy is used to pause/unpause specific LoanToken + + +## State Variables +### logicTargets + +```solidity +mapping(bytes4 => address) private logicTargets; +``` + + +### moduleUpgradeLog + +```solidity +mapping(bytes32 => LoanTokenLogicModuleUpdate[]) public moduleUpgradeLog; +``` + + +### activeModuleIndex +the module name as the key + + +```solidity +mapping(bytes32 => uint256) public activeModuleIndex; +``` + + +### activeFuncSignatureList +To store the current active index log for module + + +```solidity +mapping(bytes32 => EnumerableBytes4Set.Bytes4Set) private activeFuncSignatureList; +``` + + +## Functions +### whenNotPaused + +Store the current active function signature + +*Modifier to make a function callable only when the contract is not paused. +This is the overriden function from the pausable contract, so that we can use custom error message.* + + +```solidity +modifier whenNotPaused(); +``` + +### registerLoanTokenModule + +Register the loanTokenModule (LoanTokenSettingsLowerAdmin, LoanTokenLogicLM / LoanTokenLogicWrbtc, etc) + +*This function will store the updated protocol module to the storage (For rollback purposes)* + + +```solidity +function registerLoanTokenModule(address loanTokenModuleAddress) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanTokenModuleAddress`|`address`|The module target address| + + +### _registerLoanTokenModule + +Register the loanTokenModule (LoanTokenSettingsLowerAdmin, LoanTokenLogicLM / LoanTokenLogicWrbtc, etc) + +*This registration will require target contract to have the exact function getListFunctionSignatures() which will return functionSignatureList and the moduleName in bytes32* + + +```solidity +function _registerLoanTokenModule(address loanTokenModuleAddress) private returns (bytes32); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanTokenModuleAddress`|`address`|the target logic of the loan token module| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes32`|the module name| + + +### getActiveFuncSignatureList + +register / update the module function signature address implementation +delete the "removed" module function signature in the current implementation + +*get all active function signature list based on the module name.* + + +```solidity +function getActiveFuncSignatureList(bytes32 moduleName) public view returns (bytes4[] memory signatureList); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`moduleName`|`bytes32`|in bytes32.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`signatureList`|`bytes4[]`|the array of function signature.| + + +### getModuleUpgradeLogLength + +*Get total length of the module upgrade log.* + + +```solidity +function getModuleUpgradeLogLength(bytes32 moduleName) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`moduleName`|`bytes32`|in bytes32.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|length of module upgrade log.| + + +### rollback + +This function will rollback particular module to the spesific index / version of deployment + + +```solidity +function rollback(bytes32 moduleName, uint256 index) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`moduleName`|`bytes32`|Name of module in bytes32 format| +|`index`|`uint256`|index / version of previous deployment| + + +### getTarget + +External getter for target addresses. + + +```solidity +function getTarget(bytes4 sig) external view whenNotPaused returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sig`|`bytes4`|The signature.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The address for a given signature.| + + +## Structs +### LoanTokenLogicModuleUpdate + +```solidity +struct LoanTokenLogicModuleUpdate { + address implementation; + uint256 updateTimestamp; +} +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/interface.ILoanTokenLogicModules.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/interface.ILoanTokenLogicModules.md new file mode 100644 index 000000000..d9b6a5d71 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol/interface.ILoanTokenLogicModules.md @@ -0,0 +1,12 @@ +# ILoanTokenLogicModules +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicBeacon.sol) + + +## Functions +### getListFunctionSignatures + + +```solidity +function getListFunctionSignatures() external pure returns (bytes4[] memory, bytes32 moduleName); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicProxy.sol/contract.LoanTokenLogicProxy.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicProxy.sol/contract.LoanTokenLogicProxy.md new file mode 100644 index 000000000..a1735bf12 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicProxy.sol/contract.LoanTokenLogicProxy.md @@ -0,0 +1,147 @@ +# LoanTokenLogicProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicProxy.sol) + +**Inherits:** +[AdvancedTokenStorage](/contracts/connectors/loantoken/AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md) + +This contract contains the proxy functionality and it will query the logic target from LoanTokenLogicBeacon +This contract will also has the pause/unpause functionality. The purpose of this pausability is so that we can pause/unpause from the loan token level. + + +## State Variables +### sovrynContractAddress +PLEASE DO NOT ADD ANY VARIABLES HERE UNLESS FOR SPESIFIC SLOT +------------- MUST BE THE SAME AS IN LoanToken CONTRACT ------------------- + + +```solidity +address public sovrynContractAddress; +``` + + +### wrbtcTokenAddress + +```solidity +address public wrbtcTokenAddress; +``` + + +### target_ + +```solidity +address public target_; +``` + + +### admin + +```solidity +address public admin; +``` + + +### LOAN_TOKEN_LOGIC_BEACON_ADDRESS_SLOT +------------- END MUST BE THE SAME AS IN LoanToken CONTRACT ------------------- + +PLEASE DO NOT ADD ANY VARIABLES HERE UNLESS FOR SPESIFIC SLOT (CONSTANT / IMMUTABLE) + + +```solidity +bytes32 internal constant LOAN_TOKEN_LOGIC_BEACON_ADDRESS_SLOT = keccak256("LOAN_TOKEN_LOGIC_BEACON_ADDRESS_SLOT"); +``` + + +## Functions +### onlyAdmin + + +```solidity +modifier onlyAdmin(); +``` + +### function + +Fallback function performs a logic implementation address query to LoanTokenLogicBeacon and then do delegate call to that query result address. +Returns whatever the implementation call returns. + + +```solidity +function() external payable; +``` + +### _beaconAddress + +*Returns the current Loan Token logic Beacon.* + + +```solidity +function _beaconAddress() internal view returns (address beaconAddress); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`beaconAddress`|`address`|Address of the current LoanTokenLogicBeacon.| + + +### beaconAddress + + +```solidity +function beaconAddress() external view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The address of the current LoanTokenLogicBeacon.| + + +### _setBeaconAddress + +*Set/update the new beacon address.* + + +```solidity +function _setBeaconAddress(address _newBeaconAddress) private; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newBeaconAddress`|`address`|Address of the new LoanTokenLogicBeacon.| + + +### setBeaconAddress + +*External function to set the new LoanTokenLogicBeacon Address* + + +```solidity +function setBeaconAddress(address _newBeaconAddress) external onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newBeaconAddress`|`address`|Address of the new LoanTokenLogicBeacon| + + +### getTarget + +*External function to return the LoanTokenLogicProxy of loan token (target of LoanToken contract). +Ideally this getter should be added in the LoanToken contract +but since LoanToken contract can't be changed, adding the getter in this contract will do +because it will use the context of LoanToken contract.* + + +```solidity +function getTarget() external view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|target address of LoanToken contract| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicProxy.sol/interface.ILoanTokenLogicBeacon.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicProxy.sol/interface.ILoanTokenLogicBeacon.md new file mode 100644 index 000000000..b164dd3b2 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicProxy.sol/interface.ILoanTokenLogicBeacon.md @@ -0,0 +1,12 @@ +# ILoanTokenLogicBeacon +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicProxy.sol) + + +## Functions +### getTarget + + +```solidity +function getTarget(bytes4 functionSignature) external view returns (address logicTargetAddress); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicShared.sol/contract.LoanTokenLogicShared.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicShared.sol/contract.LoanTokenLogicShared.md new file mode 100644 index 000000000..36afbe236 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicShared.sol/contract.LoanTokenLogicShared.md @@ -0,0 +1,328 @@ +# LoanTokenLogicShared +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicShared.sol) + +**Inherits:** +[LoanTokenLogicStorage](/contracts/connectors/loantoken/LoanTokenLogicStorage.sol/contract.LoanTokenLogicStorage.md) + +*This contract shares functions used by both LoanTokenLogicSplit and LoanTokenLogicStandard* + + +## Functions +### _updateCheckpoints + +DON'T ADD VARIABLES HERE, PLEASE + +Update the user's checkpoint price and profit so far. +In this loan token contract, whenever some tokens are minted or burned, +the _updateCheckpoints() function is invoked to update the stats to +reflect the balance changes. + + +```solidity +function _updateCheckpoints(address _user, uint256 _oldBalance, uint256 _newBalance, uint256 _currentPrice) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|The user address.| +|`_oldBalance`|`uint256`|The user's previous balance.| +|`_newBalance`|`uint256`|The user's updated balance.| +|`_currentPrice`|`uint256`|The current loan token price.| + + +### _internalTransferFrom + +Transfer tokens, low level. +Checks allowance, updates sender and recipient balances +and updates checkpoints too. + +*keccak256("iToken_ProfitSoFar") +INTERNAL FUNCTION* + + +```solidity +function _internalTransferFrom(address _from, address _to, uint256 _value, uint256 _allowanceAmount) + internal + returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_from`|`address`|The tokens' owner.| +|`_to`|`address`|The recipient of the tokens.| +|`_value`|`uint256`|The amount of tokens sent.| +|`_allowanceAmount`|`uint256`|The amount of tokens allowed to transfer.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Success true/false.| + + +### _profitOf + +Profit calculation based on checkpoints of price. + +*Allowance mapping update requires an event log* + +*Handle checkpoint update.* + + +```solidity +function _profitOf(bytes32 slot, uint256 _balance, uint256 _currentPrice, uint256 _checkpointPrice) + internal + view + returns (int256 profitSoFar); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`slot`|`bytes32`|The user slot.| +|`_balance`|`uint256`|The user balance.| +|`_currentPrice`|`uint256`|The current price of the loan token.| +|`_checkpointPrice`|`uint256`|The price of the loan token on checkpoint.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`profitSoFar`|`int256`|The profit of a user.| + + +### tokenPrice + +Loan token price calculation considering unpaid interests. + + +```solidity +function tokenPrice() public view returns (uint256 price); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`price`|`uint256`|The loan token price.| + + +### totalAssetBorrow + +Get the total amount of loan tokens on debt. +Calls protocol getTotalPrincipal function. +In the context of borrowing, principal is the initial size of a loan. +It can also be the amount still owed on a loan. If you take out a +$50,000 mortgage, for example, the principal is $50,000. If you pay off +$30,000, the principal balance now consists of the remaining $20,000. + + +```solidity +function totalAssetBorrow() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The total amount of loan tokens on debt.| + + +### _verifyTransfers + +INTERNAL FUNCTION + +. + + +```solidity +function _verifyTransfers( + address collateralTokenAddress, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + MarginTradeStructHelpers.SentAmounts memory sentAmounts, + uint256 withdrawalAmount +) internal returns (uint256 msgValue); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`collateralTokenAddress`|`address`|The address of the token to be used as collateral. Cannot be the loan token address.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The addresses to send tokens: lender, borrower, receiver and manager.| +|`sentAmounts`|`MarginTradeStructHelpers.SentAmounts`|The amounts to send to each address.| +|`withdrawalAmount`|`uint256`|The amount of tokens to withdraw.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`msgValue`|`uint256`|The amount of rBTC sent minus the collateral on tokens.| + + +### _settleInterest + +withdrawOnOpen == true +This is a critical piece of code! +rBTC are supposed to be held by the contract itself, while other tokens are being transfered from the sender directly. + +Withdraw loan token interests from protocol. +This function only operates once per block. +It asks protocol to withdraw accrued interests for the loan token. + +*Internal sync required on every loan trade before starting.* + + +```solidity +function _settleInterest() internal; +``` + +### _callOptionalReturn + +Imitate a Solidity high-level call (i.e. a regular function +call to a contract), relaxing the requirement on the return value: +the return value is optional (but if data is returned, it must not be +false). + + +```solidity +function _callOptionalReturn(address token, bytes memory data, string memory errorMsg) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The token targeted by the call.| +|`data`|`bytes`|The call data (encoded using abi.encode or one of its variants).| +|`errorMsg`|`string`|The error message on failure.| + + +### _safeTransfer + +Execute the ERC20 token's `transfer` function and reverts +upon failure the main purpose of this function is to prevent a non +standard ERC20 token from failing silently. + +*Wrappers around ERC20 operations that throw on failure (when the +token contract returns false). Tokens that return no value (and instead +revert or throw on failure) are also supported, non-reverting calls are +assumed to be successful.* + + +```solidity +function _safeTransfer(address token, address to, uint256 amount, string memory errorMsg) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The ERC20 token address.| +|`to`|`address`|The target address.| +|`amount`|`uint256`|The transfer amount.| +|`errorMsg`|`string`|The error message on failure.| + + +### _safeTransferFrom + +Execute the ERC20 token's `transferFrom` function and reverts +upon failure the main purpose of this function is to prevent a non +standard ERC20 token from failing silently. + +*Wrappers around ERC20 operations that throw on failure (when the +token contract returns false). Tokens that return no value (and instead +revert or throw on failure) are also supported, non-reverting calls are +assumed to be successful.* + + +```solidity +function _safeTransferFrom(address token, address from, address to, uint256 amount, string memory errorMsg) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The ERC20 token address.| +|`from`|`address`|The source address.| +|`to`|`address`|The target address.| +|`amount`|`uint256`|The transfer amount.| +|`errorMsg`|`string`|The error message on failure.| + + +### _tokenPrice + +Internal view function + +Compute the token price. + + +```solidity +function _tokenPrice(uint256 assetSupply) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`assetSupply`|`uint256`|The amount of loan tokens supplied.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The token price.| + + +### _getAllInterest + +Get two kind of interests: owed per day and yet to be paid. + + +```solidity +function _getAllInterest() internal view returns (uint256 interestOwedPerDay, uint256 interestUnPaid); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`interestOwedPerDay`|`uint256`|The interest per day.| +|`interestUnPaid`|`uint256`|The interest not yet paid.| + + +### _totalAssetSupply + +interestPaid, interestPaidDate, interestOwedPerDay, interestUnPaid, interestFeePercent, principalTotal + +Compute the total amount of loan tokens on supply. + + +```solidity +function _totalAssetSupply(uint256 interestUnPaid) internal view returns (uint256 assetSupply); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`interestUnPaid`|`uint256`|The interest not yet paid.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`assetSupply`|`uint256`|The total amount of loan tokens on supply.| + + +### _underlyingBalance + +Temporary locked totalAssetSupply during a flash loan transaction. + +Get the loan contract balance. + + +```solidity +function _underlyingBalance() internal view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The balance of the loan token for this contract.| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicSplit.sol/contract.LoanTokenLogicSplit.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicSplit.sol/contract.LoanTokenLogicSplit.md new file mode 100644 index 000000000..210fd55d2 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicSplit.sol/contract.LoanTokenLogicSplit.md @@ -0,0 +1,180 @@ +# LoanTokenLogicSplit +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicSplit.sol) + +**Inherits:** +[LoanTokenLogicShared](/contracts/connectors/loantoken/LoanTokenLogicShared.sol/contract.LoanTokenLogicShared.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized margin +trading and lending https://bzx.network similar to the dYdX protocol. +Logic around loan tokens (iTokens) required to operate borrowing, +and margin trading financial processes. +The user provides funds to the lending pool using the mint function and +withdraws funds from the lending pool using the burn function. Mint and +burn refer to minting and burning loan tokens. Loan tokens represent a +share of the pool and gather interest over time. +Interest rates are determined by supply and demand. When a lender deposits +funds, the interest rates go down. When a trader borrows funds, the +interest rates go up. Fulcrum uses a simple linear interest rate formula +of the form y = mx + b. The interest rate starts at 1% when loans aren't +being utilized and scales up to 40% when all the funds in the loan pool +are being borrowed. +The borrow rate is determined at the time of the loan and represents the +net contribution of each borrower. Each borrower's interest contribution +is determined by the utilization rate of the pool and is netted against +all prior borrows. This means that the total amount of interest flowing +into the lending pool is not directly changed by lenders entering or +exiting the pool. The entrance or exit of lenders only impacts how the +interest payments are split up. +For example, if there are 2 lenders with equal holdings each earning +5% APR, but one of the lenders leave, then the remaining lender will earn +10% APR since the interest payments don't have to be split between two +individuals. + + +## Functions +### mint + +DON'T ADD VARIABLES HERE, PLEASE + +Mint loan token wrapper. +Adds a check before calling low level _mintToken function. +The function retrieves the tokens from the message sender, so make sure +to first approve the loan token contract to access your funds. This is +done by calling approve(address spender, uint amount) on the ERC20 +token contract, where spender is the loan token contract address and +amount is the amount to be deposited. + + +```solidity +function mint(address receiver, uint256 depositAmount) + external + nonReentrant + globallyNonReentrant + returns (uint256 mintAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The account getting the minted tokens.| +|`depositAmount`|`uint256`|The amount of underlying tokens provided on the loan. (Not the number of loan tokens to mint).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`mintAmount`|`uint256`|The amount of loan tokens minted.| + + +### burn + +Burn loan token wrapper. +Adds a pay-out transfer after calling low level _burnToken function. +In order to withdraw funds to the pool, call burn on the respective +loan token contract. This will burn your loan tokens and send you the +underlying token in exchange. + + +```solidity +function burn(address receiver, uint256 burnAmount) + external + nonReentrant + globallyNonReentrant + returns (uint256 loanAmountPaid); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The account getting the minted tokens.| +|`burnAmount`|`uint256`|The amount of loan tokens to redeem.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanAmountPaid`|`uint256`|The amount of underlying tokens payed to lender.| + + +### _mintToken + +transfers the underlying asset from the msg.sender and mints tokens for the receiver + + +```solidity +function _mintToken(address receiver, uint256 depositAmount) internal returns (uint256 mintAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|the address of the iToken receiver| +|`depositAmount`|`uint256`|the amount of underlying assets to be deposited| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`mintAmount`|`uint256`|the amount of iTokens issued| + + +### _prepareMinting + +calculates the amount of tokens to mint and transfers the underlying asset to this contract + + +```solidity +function _prepareMinting(uint256 depositAmount) internal returns (uint256 mintAmount, uint256 currentPrice); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`depositAmount`|`uint256`|the amount of the underyling asset deposited| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`mintAmount`|`uint256`|the amount to be minted| +|`currentPrice`|`uint256`|| + + +### _burnToken + +A wrapper for AdvancedToken::_burn + + +```solidity +function _burnToken(uint256 burnAmount) internal returns (uint256 loanAmountPaid); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`burnAmount`|`uint256`|The amount of loan tokens to redeem.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanAmountPaid`|`uint256`|The amount of underlying tokens payed to lender.| + + +### _mintWithLM + + +```solidity +function _mintWithLM(address receiver, uint256 depositAmount) internal returns (uint256 minted); +``` + +### _burnFromLM + + +```solidity +function _burnFromLM(uint256 burnAmount) internal returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicStandard.sol/contract.LoanTokenLogicStandard.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicStandard.sol/contract.LoanTokenLogicStandard.md new file mode 100644 index 000000000..22835626d --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicStandard.sol/contract.LoanTokenLogicStandard.md @@ -0,0 +1,884 @@ +# LoanTokenLogicStandard +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicStandard.sol) + +**Inherits:** +[LoanTokenLogicShared](/contracts/connectors/loantoken/LoanTokenLogicShared.sol/contract.LoanTokenLogicShared.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### transfer + +Transfer tokens wrapper. +Sets token owner the msg.sender. +Sets maximun allowance uint256(-1) to ensure tokens are always transferred. +If the recipient (_to) is a vesting contract address, transfer the token to the tokenOwner of the vesting contract itself. + + +```solidity +function transfer(address _to, uint256 _value) external returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_to`|`address`|The recipient of the tokens.| +|`_value`|`uint256`|The amount of tokens sent.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Success true/false.| + + +### transferFrom + +need additional check address(0) here to support backward compatibility +in case we don't want to activate this check, just need to set the stakingContractAddress to 0 address + +Moves `_value` loan tokens from `_from` to `_to` using the +allowance mechanism. Calls internal _internalTransferFrom function. + + +```solidity +function transferFrom(address _from, address _to, uint256 _value) external returns (bool); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|A boolean value indicating whether the operation succeeded.| + + +### borrow + +Borrow funds from the pool. +The underlying loan token may not be used as collateral. + + +```solidity +function borrow( + bytes32 loanId, + uint256 withdrawAmount, + uint256 initialLoanDuration, + uint256 collateralTokenSent, + address collateralTokenAddress, + address borrower, + address receiver, + bytes memory +) public payable nonReentrant globallyNonReentrant returns (uint256, uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan, 0 for a new loan.| +|`withdrawAmount`|`uint256`|The amount to be withdrawn (actually borrowed).| +|`initialLoanDuration`|`uint256`|The duration of the loan in seconds. If the loan is not paid back until then, it'll need to be rolled over.| +|`collateralTokenSent`|`uint256`|The amount of collateral tokens provided by the user. (150% of the withdrawn amount worth in collateral tokens).| +|`collateralTokenAddress`|`address`|The address of the token to be used as collateral. Cannot be the loan token address.| +|`borrower`|`address`|The one paying for the collateral.| +|`receiver`|`address`|The one receiving the withdrawn amount.| +|``|`bytes`|| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|New principal and new collateral added to loan.| +|``|`uint256`|| + + +### marginTrade + +Temporary: limit transaction size. + +Borrow and immediately get into a position. +Trading on margin is used to increase an investor's buying power. +Margin is the amount of money required to open a position, while +leverage is the multiple of exposure to account equity. +Leverage allows you to trade positions LARGER than the amount +of money in your trading account. Leverage is expressed as a ratio. +When trading on margin, investors first deposit some token that then +serves as collateral for the loan, and then pay ongoing interest +payments on the money they borrow. +Margin trading = taking a loan and swapping it: +In order to open a margin trade position, +1.- The user calls marginTrade on the loan token contract. +2.- The loan token contract provides the loan and sends it for processing +to the protocol proxy contract. +3.- The protocol proxy contract uses the module LoanOpening to create a +position and swaps the loan tokens to collateral tokens. +4.- The Sovryn Swap network looks up the correct converter and swaps the +tokens. +If successful, the position is being held by the protocol proxy contract, +which is why positions need to be closed at the protocol proxy contract. + +*We have an issue regarding contract size code is too big. 1 of the solution is need to keep the error message 32 bytes length* + +*Ensure authorized use of existing loan.* + +*The condition is never met. +Address zero is not allowed by previous require validation. +This check is unneeded and was lowering the test coverage index. +The lender. +sentAddresses.manager = address(0); /// The manager. +interestRate, interestInitialAmount, borrowAmount (newBorrowAmount). +Interest is settled above. +sentAmounts.loanTokenSent = 0; /// loanTokenSent +loanDataBytes* + + +```solidity +function marginTrade( + bytes32 loanId, + uint256 leverageAmount, + uint256 loanTokenSent, + uint256 collateralTokenSent, + address collateralTokenAddress, + address trader, + uint256 minEntryPrice, + bytes memory loanDataBytes +) public payable nonReentrant globallyNonReentrant returns (uint256, uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan, 0 for a new loan.| +|`leverageAmount`|`uint256`|The multiple of exposure: 2x ... 5x. The leverage with 18 decimals.| +|`loanTokenSent`|`uint256`|The number of loan tokens provided by the user.| +|`collateralTokenSent`|`uint256`|The amount of collateral tokens provided by the user.| +|`collateralTokenAddress`|`address`|The token address of collateral.| +|`trader`|`address`|The account that performs this trade.| +|`minEntryPrice`|`uint256`|Value of loan token in collateral.| +|`loanDataBytes`|`bytes`|Additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|New principal and new collateral added to trade.| +|``|`uint256`|| + + +### marginTradeAffiliate + +Wrapper for marginTrade invoking setAffiliatesReferrer to track +referral trade by affiliates program. + +*Ensure authorized use of existing loan. +Temporary: limit transaction size.* + +*Compute the worth of the total deposit in loan tokens. +(loanTokenSent + convert(collateralTokenSent)) +No actual swap happening here. +sentAddresses.manager = address(0); /// The manager. +sentAmounts.interestRate = 0; /// interestRate (found later). +sentAmounts.interestInitialAmount = 0; /// interestInitialAmount (interest is calculated based on fixed-term loan). +borrowAmount, interestRate +depositAmount* + +*Converting to initialMargin +withdrawAmount* + + +```solidity +function marginTradeAffiliate( + bytes32 loanId, + uint256 leverageAmount, + uint256 loanTokenSent, + uint256 collateralTokenSent, + address collateralTokenAddress, + address trader, + uint256 minEntryPrice, + address affiliateReferrer, + bytes calldata loanDataBytes +) external payable returns (uint256, uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan, 0 for a new loan.| +|`leverageAmount`|`uint256`|The multiple of exposure: 2x ... 5x. The leverage with 18 decimals.| +|`loanTokenSent`|`uint256`|The number of loan tokens provided by the user.| +|`collateralTokenSent`|`uint256`|The amount of collateral tokens provided by the user.| +|`collateralTokenAddress`|`address`|The token address of collateral.| +|`trader`|`address`|The account that performs this trade.| +|`minEntryPrice`|`uint256`|Value of loan token in collateral.| +|`affiliateReferrer`|`address`|The address of the referrer from affiliates program.| +|`loanDataBytes`|`bytes`|Additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|New principal and new collateral added to trade.| +|``|`uint256`|| + + +### profitOf + +Wrapper for internal _profitOf low level function. + + +```solidity +function profitOf(address user) external view returns (int256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The user address.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`int256`|The profit of a user.| + + +### checkpointPrice + +Getter for the price checkpoint mapping. + +*keccak256("iToken_ProfitSoFar")* + + +```solidity +function checkpointPrice(address _user) public view returns (uint256 price); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|The user account as the mapping index.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`price`|`uint256`|The price on the checkpoint for this user.| + + +### marketLiquidity + +Get current liquidity. +A part of total funds supplied are borrowed. Liquidity = supply - borrow + + +```solidity +function marketLiquidity() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The market liquidity.| + + +### avgBorrowInterestRate + +Wrapper for average borrow interest. + + +```solidity +function avgBorrowInterestRate() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The average borrow interest.| + + +### borrowInterestRate + +Get borrow interest rate. +The minimum rate the next base protocol borrower will receive +for variable-rate loans. + + +```solidity +function borrowInterestRate() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The borrow interest rate.| + + +### nextBorrowInterestRate + +Public wrapper for internal call. + + +```solidity +function nextBorrowInterestRate(uint256 borrowAmount) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`borrowAmount`|`uint256`|The amount of tokens to borrow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The next borrow interest rate.| + + +### supplyInterestRate + +Get interest rate. + + +```solidity +function supplyInterestRate() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|Interest that lenders are currently receiving when supplying to the pool.| + + +### nextSupplyInterestRate + +Get interest rate w/ added supply. + + +```solidity +function nextSupplyInterestRate(uint256 supplyAmount) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`supplyAmount`|`uint256`|The amount of tokens supplied.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|Interest that lenders are currently receiving when supplying a given amount of tokens to the pool.| + + +### totalSupplyInterestRate + +Get interest rate w/ added supply assets. + + +```solidity +function totalSupplyInterestRate(uint256 assetSupply) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`assetSupply`|`uint256`|The amount of loan tokens supplied.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|Interest that lenders are currently receiving when supplying a given amount of loan tokens to the pool.| + + +### totalAssetSupply + +Get the total amount of loan tokens on supply. + +*Wrapper for internal _totalAssetSupply function.* + + +```solidity +function totalAssetSupply() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The total amount of loan tokens on supply.| + + +### getMaxEscrowAmount + +Compute the maximum deposit amount under current market conditions. + +*maxEscrowAmount = liquidity * (100 - interestForDuration) / 100* + + +```solidity +function getMaxEscrowAmount(uint256 leverageAmount) public view returns (uint256 maxEscrowAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`leverageAmount`|`uint256`|The chosen multiplier with 18 decimals.| + + +### assetBalanceOf + +Get loan token balance. + +*Mathematical imperfection: depending on liquidity we might be able +to borrow more if utilization is below the kink level.* + + +```solidity +function assetBalanceOf(address _owner) public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The user's balance of underlying token.| + + +### getEstimatedMarginDetails + +Get margin information on a trade. + + +```solidity +function getEstimatedMarginDetails( + uint256 leverageAmount, + uint256 loanTokenSent, + uint256 collateralTokenSent, + address collateralTokenAddress +) public view returns (uint256 principal, uint256 collateral, uint256 interestRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`leverageAmount`|`uint256`|The multiple of exposure: 2x ... 5x. The leverage with 18 decimals.| +|`loanTokenSent`|`uint256`|The number of loan tokens provided by the user.| +|`collateralTokenSent`|`uint256`|The amount of collateral tokens provided by the user.| +|`collateralTokenAddress`|`address`|The token address of collateral.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`principal`|`uint256`|The principal, the collateral and the interestRate.| +|`collateral`|`uint256`|| +|`interestRate`|`uint256`|| + + +### getDepositAmountForBorrow + +Calculate the deposit required to a given borrow. +The function for doing over-collateralized borrows against loan tokens +expects a minimum amount of collateral be sent to satisfy collateral +requirements of the loan, for borrow amount, interest rate, and +initial loan duration. To determine appropriate values to pass to this +function for a given loan, `getDepositAmountForBorrow` and +'getBorrowAmountForDeposit` are required. + + +```solidity +function getDepositAmountForBorrow(uint256 borrowAmount, uint256 initialLoanDuration, address collateralTokenAddress) + public + view + returns (uint256 depositAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`borrowAmount`|`uint256`|The amount of borrow.| +|`initialLoanDuration`|`uint256`|The duration of the loan.| +|`collateralTokenAddress`|`address`|The token address of collateral.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`depositAmount`|`uint256`|The amount of deposit required.| + + +### getBorrowAmountForDeposit + +initialMargin +isTorqueLoan +Some dust to compensate for rounding errors. + +Calculate the borrow allowed for a given deposit. +The function for doing over-collateralized borrows against loan tokens +expects a minimum amount of collateral be sent to satisfy collateral +requirements of the loan, for borrow amount, interest rate, and +initial loan duration. To determine appropriate values to pass to this +function for a given loan, `getDepositAmountForBorrow` and +'getBorrowAmountForDeposit` are required. + + +```solidity +function getBorrowAmountForDeposit(uint256 depositAmount, uint256 initialLoanDuration, address collateralTokenAddress) + public + view + returns (uint256 borrowAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`depositAmount`|`uint256`|The amount of deposit.| +|`initialLoanDuration`|`uint256`|The duration of the loan.| +|`collateralTokenAddress`|`address`|The token address of collateral.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`borrowAmount`|`uint256`|The amount of borrow allowed.| + + +### checkPriceDivergence + +initialMargin, +isTorqueLoan + +Check if entry price lies above a minimum + + +```solidity +function checkPriceDivergence(uint256 loanTokenSent, address collateralTokenAddress, uint256 minEntryPrice) + public + view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanTokenSent`|`uint256`|The amount of deposit.| +|`collateralTokenAddress`|`address`|The token address of collateral.| +|`minEntryPrice`|`uint256`|Value of loan token in collateral| + + +### calculateSupplyInterestRate + +Compute the next supply interest adjustment. + +*See how many collateralTokens we would get if exchanging this amount of loan tokens to collateral tokens.* + + +```solidity +function calculateSupplyInterestRate(uint256 assetBorrow, uint256 assetSupply) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`assetBorrow`|`uint256`|The amount of loan tokens on debt.| +|`assetSupply`|`uint256`|The amount of loan tokens supplied.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The next supply interest adjustment.| + + +### _totalDeposit + +Compute what the deposit is worth in loan tokens using the swap rate +used for loan size computation. + + +```solidity +function _totalDeposit(address collateralTokenAddress, uint256 collateralTokenSent, uint256 loanTokenSent) + internal + view + returns (uint256 totalDeposit); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`collateralTokenAddress`|`address`|The token address of the collateral.| +|`collateralTokenSent`|`uint256`|The amount of collateral tokens provided by the user.| +|`loanTokenSent`|`uint256`|The number of loan tokens provided by the user.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`totalDeposit`|`uint256`|The value of the deposit in loan tokens.| + + +### _getAmountInRbtc + +*Get the oracle rate from collateral -> loan* + +*Compute the loan token amount with the oracle rate.* + +*See how many collateralTokens we would get if exchanging this amount of loan tokens to collateral tokens.* + +*Probably not the same due to the price difference.* + +*returns amount of the asset converted to RBTC* + + +```solidity +function _getAmountInRbtc(address asset, uint256 amount) internal returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`asset`|`address`|the asset to be transferred| +|`amount`|`uint256`|the amount to be transferred| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|amount in RBTC| + + +### _getInterestRateAndBorrowAmount + + +```solidity +function _getInterestRateAndBorrowAmount(uint256 borrowAmount, uint256 assetSupply, uint256 initialLoanDuration) + internal + view + returns (uint256 interestRate, uint256 interestInitialAmount, uint256 newBorrowAmount); +``` + +### _borrowOrTrade + +newBorrowAmount = borrowAmount * 10^18 / (10^18 - interestRate * 7884000 * 10^18 / 31536000 / 10^20) +365 * 86400 * 10**20 + +Compute principal and collateral. + + +```solidity +function _borrowOrTrade( + bytes32 loanId, + uint256 withdrawAmount, + uint256 initialMargin, + address collateralTokenAddress, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + MarginTradeStructHelpers.SentAmounts memory sentAmounts, + bytes memory loanDataBytes +) internal returns (uint256, uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan, 0 for a new loan.| +|`withdrawAmount`|`uint256`|The amount to be withdrawn (actually borrowed).| +|`initialMargin`|`uint256`|The initial margin with 18 decimals| +|`collateralTokenAddress`|`address`| The address of the token to be used as collateral. Cannot be the loan token address.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The addresses to send tokens: lender, borrower, receiver and manager.| +|`sentAmounts`|`MarginTradeStructHelpers.SentAmounts`|The amounts to send to each address.| +|`loanDataBytes`|`bytes`|Additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The new principal and the new collateral. Principal is the complete borrowed amount (in loan tokens). Collateral is the complete position size (loan + margin) (in collateral tokens).| +|``|`uint256`|| + + +### _avgBorrowInterestRate + +newPrincipal (borrowed amount + fees) +The borrower. +The receiver = the borrower. + +Compute the average borrow interest rate. + +*Handle transfers prior to adding newPrincipal to loanTokenSent* + +*Adding the loan token portion from the lender to loanTokenSent +(add the loan to the loan tokens sent from the user). +newPrincipal* + +*withdrawAmount already sent to the borrower, so we aren't sending it to the protocol. +Default is false, but added just as to make sure. +newPrincipal, newCollateral* + +*Setting not-first-trade flag to prevent binding to an affiliate existing users post factum.* + +*REFACTOR: move to a general interface: ProtocolSettingsLike?* + + +```solidity +function _avgBorrowInterestRate(uint256 assetBorrow) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`assetBorrow`|`uint256`|The amount of loan tokens on debt.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The average borrow interest rate.| + + +### _nextBorrowInterestRate + +Compute the next borrow interest adjustment. + + +```solidity +function _nextBorrowInterestRate(uint256 borrowAmount) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`borrowAmount`|`uint256`|The amount of tokens to borrow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The next borrow interest adjustment.| + + +### _nextBorrowInterestRate2 + +Compute the next borrow interest adjustment under target-kink +level analysis. +The "kink" in the cDAI interest rate model reflects the utilization rate +at which the slope of the interest rate goes from "gradual" to "steep". +That is, below this utilization rate, the slope of the interest rate +curve is gradual. Above this utilization rate, it is steep. +Because of this dynamic between the interest rate curves before and +after the "kink", the "kink" can be thought of as the target utilization +rate. Above that rate, it quickly becomes expensive to borrow (and +commensurately lucrative for suppliers). + + +```solidity +function _nextBorrowInterestRate2(uint256 newBorrowAmount, uint256 assetSupply) + internal + view + returns (uint256 nextRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newBorrowAmount`|`uint256`|The new amount of tokens to borrow.| +|`assetSupply`|`uint256`|The amount of loan tokens supplied.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`nextRate`|`uint256`|The next borrow interest adjustment.| + + +### _getMarginBorrowAmountAndRate + +Compute the loan size and interest rate. + +*Scale rate proportionally up to 100% +Will not overflow.* + + +```solidity +function _getMarginBorrowAmountAndRate(uint256 leverageAmount, uint256 depositAmount) + internal + view + returns (uint256 borrowAmount, uint256 interestRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`leverageAmount`|`uint256`|The leverage with 18 decimals.| +|`depositAmount`|`uint256`|The amount the user deposited in underlying loan tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`borrowAmount`|`uint256`|The amount of tokens to borrow.| +|`interestRate`|`uint256`|The interest rate to pay on the position.| + + +### _checkPause + +Make sure call is not paused. + +*Mathematical imperfection. we calculate the interest rate based on +the loanSizeBeforeInterest, but the actual borrowed amount will be bigger.* + +*Assumes that loan, collateral, and interest token are the same.* + +*Used for internal verification if the called function is paused. +It throws an exception in case it's not.* + + +```solidity +function _checkPause() internal view; +``` + +### _adjustLoanSize + +keccak256("iToken_FunctionPause") + +Adjusts the loan size to make sure the expected exposure remains after prepaying the interest. + +*loanSizeWithInterest = loanSizeBeforeInterest * 100 / (100 - interestForDuration)* + + +```solidity +function _adjustLoanSize(uint256 interestRate, uint256 maxDuration, uint256 loanSizeBeforeInterest) + internal + pure + returns (uint256 loanSizeWithInterest); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`interestRate`|`uint256`|The interest rate to pay on the position.| +|`maxDuration`|`uint256`|The maximum duration of the position (until rollover).| +|`loanSizeBeforeInterest`|`uint256`|The loan size before interest is added.| + + +### _utilizationRate + +Calculate the utilization rate. + +*Utilization rate = assetBorrow / assetSupply* + + +```solidity +function _utilizationRate(uint256 assetBorrow, uint256 assetSupply) internal pure returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`assetBorrow`|`uint256`|The amount of loan tokens on debt.| +|`assetSupply`|`uint256`|The amount of loan tokens supplied.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The utilization rate.| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicStorage.sol/contract.LoanTokenLogicStorage.md b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicStorage.sol/contract.LoanTokenLogicStorage.md new file mode 100644 index 000000000..c2ea9719f --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/LoanTokenLogicStorage.sol/contract.LoanTokenLogicStorage.md @@ -0,0 +1,125 @@ +# LoanTokenLogicStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/LoanTokenLogicStorage.sol) + +**Inherits:** +[AdvancedToken](/contracts/connectors/loantoken/AdvancedToken.sol/contract.AdvancedToken.md) + + +## State Variables +### sovrynContractAddress +DO NOT ADD VARIABLES HERE - SEE BELOW + +*It is important to maintain the variables order so the delegate +calls can access sovrynContractAddress +------------- MUST BE THE SAME AS IN LoanToken CONTRACT -------------------* + + +```solidity +address public sovrynContractAddress; +``` + + +### wrbtcTokenAddress + +```solidity +address public wrbtcTokenAddress; +``` + + +### target_ + +```solidity +address public target_; +``` + + +### admin + +```solidity +address public admin; +``` + + +### earlyAccessToken +------------- END MUST BE THE SAME AS IN LoanToken CONTRACT ------------------- + +*Add new variables here on the bottom.* + + +```solidity +address public earlyAccessToken; +``` + + +### pauser + +```solidity +address public pauser; +``` + + +### liquidityMiningAddress +The address of the liquidity mining contract + + +```solidity +address public liquidityMiningAddress; +``` + + +### stakingContractAddress +The address of the staking contract + + +```solidity +address public stakingContractAddress; +``` + + +### VERSION +*Used by flashBorrow function.* + + +```solidity +uint256 public constant VERSION = 6; +``` + + +### arbitraryCaller +*Used by flashBorrow function.* + + +```solidity +address internal constant arbitraryCaller = 0x000F400e6818158D541C3EBE45FE3AA0d47372FF; +``` + + +### iToken_ProfitSoFar + +```solidity +bytes32 internal constant iToken_ProfitSoFar = 0x37aa2b7d583612f016e4a4de4292cb015139b3d7762663d06a53964912ea2fb6; +``` + + +### TINY_AMOUNT + +```solidity +uint256 public constant TINY_AMOUNT = 25e13; +``` + + +## Functions +### stringToBytes32 + + +```solidity +function stringToBytes32(string memory source) public pure returns (bytes32 result); +``` + +### onlyPauserOrOwner + + +```solidity +modifier onlyPauserOrOwner(); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/Pausable.sol/contract.Pausable.md b/foundry/docs/src/contracts/connectors/loantoken/Pausable.sol/contract.Pausable.md new file mode 100644 index 000000000..196b594f5 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/Pausable.sol/contract.Pausable.md @@ -0,0 +1,54 @@ +# Pausable +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/Pausable.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized margin +trading and lending https://bzx.network similar to the dYdX protocol. +The contract implements pausable functionality by reading on slots the +pause state of contract functions. + + +## State Variables +### Pausable_FunctionPause +keccak256("Pausable_FunctionPause") + + +```solidity +bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; +``` + + +## Functions +### pausable + + +```solidity +modifier pausable(bytes4 sig); +``` + +### _isPaused + +Check whether a function is paused. + +*Used to read externally from the smart contract to see if a +function is paused.* + + +```solidity +function _isPaused(bytes4 sig) internal view returns (bool isPaused); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sig`|`bytes4`|The function ID, the selector on bytes4.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`isPaused`|`bool`|Whether the function is paused: true or false.| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/README.md b/foundry/docs/src/contracts/connectors/loantoken/README.md new file mode 100644 index 000000000..8af73b7cf --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/README.md @@ -0,0 +1,19 @@ + + +# Contents +- [interfaces](/contracts/connectors/loantoken/interfaces) +- [lib](/contracts/connectors/loantoken/lib) +- [modules](/contracts/connectors/loantoken/modules) +- [AdvancedToken](AdvancedToken.sol/contract.AdvancedToken.md) +- [AdvancedTokenStorage](AdvancedTokenStorage.sol/contract.AdvancedTokenStorage.md) +- [LoanToken](LoanToken.sol/contract.LoanToken.md) +- [LoanTokenBase](LoanTokenBase.sol/contract.LoanTokenBase.md) +- [LoanTokenLogicBeacon](LoanTokenLogicBeacon.sol/contract.LoanTokenLogicBeacon.md) +- [ILoanTokenLogicModules](LoanTokenLogicBeacon.sol/interface.ILoanTokenLogicModules.md) +- [LoanTokenLogicProxy](LoanTokenLogicProxy.sol/contract.LoanTokenLogicProxy.md) +- [ILoanTokenLogicBeacon](LoanTokenLogicProxy.sol/interface.ILoanTokenLogicBeacon.md) +- [LoanTokenLogicShared](LoanTokenLogicShared.sol/contract.LoanTokenLogicShared.md) +- [LoanTokenLogicSplit](LoanTokenLogicSplit.sol/contract.LoanTokenLogicSplit.md) +- [LoanTokenLogicStandard](LoanTokenLogicStandard.sol/contract.LoanTokenLogicStandard.md) +- [LoanTokenLogicStorage](LoanTokenLogicStorage.sol/contract.LoanTokenLogicStorage.md) +- [Pausable](Pausable.sol/contract.Pausable.md) diff --git a/foundry/docs/src/contracts/connectors/loantoken/interfaces/FeedsLike.sol/interface.FeedsLike.md b/foundry/docs/src/contracts/connectors/loantoken/interfaces/FeedsLike.sol/interface.FeedsLike.md new file mode 100644 index 000000000..5e82e976c --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/interfaces/FeedsLike.sol/interface.FeedsLike.md @@ -0,0 +1,18 @@ +# FeedsLike +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/interfaces/FeedsLike.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### queryRate + + +```solidity +function queryRate(address sourceTokenAddress, address destTokenAddress) + external + view + returns (uint256 rate, uint256 precision); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/interfaces/ProtocolLike.sol/interface.ProtocolLike.md b/foundry/docs/src/contracts/connectors/loantoken/interfaces/ProtocolLike.sol/interface.ProtocolLike.md new file mode 100644 index 000000000..6008575b7 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/interfaces/ProtocolLike.sol/interface.ProtocolLike.md @@ -0,0 +1,155 @@ +# ProtocolLike +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/interfaces/ProtocolLike.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### borrowOrTradeFromPool + + +```solidity +function borrowOrTradeFromPool( + bytes32 loanParamsId, + bytes32 loanId, + bool isTorqueLoan, + uint256 initialMargin, + MarginTradeStructHelpers.SentAddresses calldata sentAddresses, + MarginTradeStructHelpers.SentAmounts calldata sentValues, + bytes calldata loanDataBytes +) external payable returns (uint256 newPrincipal, uint256 newCollateral); +``` + +### getTotalPrincipal + + +```solidity +function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); +``` + +### withdrawAccruedInterest + + +```solidity +function withdrawAccruedInterest(address loanToken) external; +``` + +### getLenderInterestData + + +```solidity +function getLenderInterestData(address lender, address loanToken) + external + view + returns ( + uint256 interestPaid, + uint256 interestPaidDate, + uint256 interestOwedPerDay, + uint256 interestUnPaid, + uint256 interestFeePercent, + uint256 principalTotal + ); +``` + +### priceFeeds + + +```solidity +function priceFeeds() external view returns (address); +``` + +### getEstimatedMarginExposure + + +```solidity +function getEstimatedMarginExposure( + address loanToken, + address collateralToken, + uint256 loanTokenSent, + uint256 collateralTokenSent, + uint256 interestRate, + uint256 newPrincipal +) external view returns (uint256); +``` + +### getRequiredCollateral + + +```solidity +function getRequiredCollateral( + address loanToken, + address collateralToken, + uint256 newPrincipal, + uint256 marginAmount, + bool isTorqueLoan +) external view returns (uint256 collateralAmountRequired); +``` + +### getBorrowAmount + + +```solidity +function getBorrowAmount( + address loanToken, + address collateralToken, + uint256 collateralTokenAmount, + uint256 marginAmount, + bool isTorqueLoan +) external view returns (uint256 borrowAmount); +``` + +### isLoanPool + + +```solidity +function isLoanPool(address loanPool) external view returns (bool); +``` + +### lendingFeePercent + + +```solidity +function lendingFeePercent() external view returns (uint256); +``` + +### getSwapExpectedReturn + + +```solidity +function getSwapExpectedReturn(address sourceToken, address destToken, uint256 sourceTokenAmount) + external + view + returns (uint256); +``` + +### borrowerNonce + + +```solidity +function borrowerNonce(address) external view returns (uint256); +``` + +### closeWithSwap + + +```solidity +function closeWithSwap( + bytes32 loanId, + address receiver, + uint256 swapAmount, + bool returnTokenIsCollateral, + bytes calldata +) external returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` + +### closeWithDeposit + + +```solidity +function closeWithDeposit(bytes32 loanId, address receiver, uint256 depositAmount) + external + payable + returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/interfaces/ProtocolSettingsLike.sol/interface.ProtocolSettingsLike.md b/foundry/docs/src/contracts/connectors/loantoken/interfaces/ProtocolSettingsLike.sol/interface.ProtocolSettingsLike.md new file mode 100644 index 000000000..7a53b4c87 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/interfaces/ProtocolSettingsLike.sol/interface.ProtocolSettingsLike.md @@ -0,0 +1,31 @@ +# ProtocolSettingsLike +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/interfaces/ProtocolSettingsLike.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### setupLoanParams + + +```solidity +function setupLoanParams(LoanParamsStruct.LoanParams[] calldata loanParamsList) + external + returns (bytes32[] memory loanParamsIdList); +``` + +### disableLoanParams + + +```solidity +function disableLoanParams(bytes32[] calldata loanParamsIdList) external; +``` + +### minInitialMargin + + +```solidity +function minInitialMargin(bytes32 loanParamsId) external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/interfaces/README.md b/foundry/docs/src/contracts/connectors/loantoken/interfaces/README.md new file mode 100644 index 000000000..ffe82a6cb --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/interfaces/README.md @@ -0,0 +1,6 @@ + + +# Contents +- [FeedsLike](FeedsLike.sol/interface.FeedsLike.md) +- [ProtocolLike](ProtocolLike.sol/interface.ProtocolLike.md) +- [ProtocolSettingsLike](ProtocolSettingsLike.sol/interface.ProtocolSettingsLike.md) diff --git a/foundry/docs/src/contracts/connectors/loantoken/lib/MarginTradeStructHelpers.sol/library.MarginTradeStructHelpers.md b/foundry/docs/src/contracts/connectors/loantoken/lib/MarginTradeStructHelpers.sol/library.MarginTradeStructHelpers.md new file mode 100644 index 000000000..5b58a2845 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/lib/MarginTradeStructHelpers.sol/library.MarginTradeStructHelpers.md @@ -0,0 +1,32 @@ +# MarginTradeStructHelpers +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/lib/MarginTradeStructHelpers.sol) + + +## Structs +### SentAddresses + +```solidity +struct SentAddresses { + address lender; + address borrower; + address receiver; + address manager; +} +``` + +### SentAmounts + +```solidity +struct SentAmounts { + uint256 interestRate; + uint256 newPrincipal; + uint256 interestInitialAmount; + uint256 loanTokenSent; + uint256 collateralTokenSent; + uint256 minEntryPrice; + uint256 loanToCollateralSwapRate; + uint256 interestDuration; + uint256 entryLeverage; +} +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/lib/README.md b/foundry/docs/src/contracts/connectors/loantoken/lib/README.md new file mode 100644 index 000000000..cc5ae5a9c --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/lib/README.md @@ -0,0 +1,4 @@ + + +# Contents +- [MarginTradeStructHelpers](MarginTradeStructHelpers.sol/library.MarginTradeStructHelpers.md) diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/README.md b/foundry/docs/src/contracts/connectors/loantoken/modules/README.md new file mode 100644 index 000000000..39d64c32c --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/README.md @@ -0,0 +1,6 @@ + + +# Contents +- [beaconLogicLM](/contracts/connectors/loantoken/modules/beaconLogicLM) +- [beaconLogicWRBTC](/contracts/connectors/loantoken/modules/beaconLogicWRBTC) +- [shared](/contracts/connectors/loantoken/modules/shared) diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogic.sol/contract.LoanTokenLogic.md b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogic.sol/contract.LoanTokenLogic.md new file mode 100644 index 000000000..fa44b5864 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogic.sol/contract.LoanTokenLogic.md @@ -0,0 +1,32 @@ +# LoanTokenLogic +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogic.sol) + +**Inherits:** +[LoanTokenLogicStandard](/contracts/connectors/loantoken/LoanTokenLogicStandard.sol/contract.LoanTokenLogicStandard.md) + + +## Functions +### getListFunctionSignatures + +This function is MANDATORY, which will be called by LoanTokenLogicBeacon and be registered. +Every new public function, the signature needs to be included in this function. + +*This function will return the list of function signature in this contract that are available for public call +Then this function will be called by LoanTokenLogicBeacon, and the function signatures will be registred in LoanTokenLogicBeacon.* + +*To save the gas we can just directly return the list of function signature from this pure function. +The other workaround (fancy way) is we can create a storage for the list of the function signature, and then we can store each function signature to that storage from the constructor. +Then, in this function we just need to return that storage variable.* + + +```solidity +function getListFunctionSignatures() external pure returns (bytes4[] memory functionSignatures, bytes32 moduleName); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`functionSignatures`|`bytes4[]`|The list of function signatures (bytes4[])| +|`moduleName`|`bytes32`|| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogicLM.sol/contract.LoanTokenLogicLM.md b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogicLM.sol/contract.LoanTokenLogicLM.md new file mode 100644 index 000000000..f2c6b97ae --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogicLM.sol/contract.LoanTokenLogicLM.md @@ -0,0 +1,83 @@ +# LoanTokenLogicLM +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/modules/beaconLogicLM/LoanTokenLogicLM.sol) + +**Inherits:** +[LoanTokenLogicSplit](/contracts/connectors/loantoken/LoanTokenLogicSplit.sol/contract.LoanTokenLogicSplit.md) + + +## Functions +### getListFunctionSignatures + +This function is MANDATORY, which will be called by LoanTokenLogicBeacon and be registered. +Every new public function, the signature needs to be included in this function. + +*This function will return the list of function signature in this contract that are available for public call +Then this function will be called by LoanTokenLogicBeacon, and the function signatures will be registred in LoanTokenLogicBeacon.* + +*To save the gas we can just directly return the list of function signature from this pure function. +The other workaround (fancy way) is we can create a storage for the list of the function signature, and then we can store each function signature to that storage from the constructor. +Then, in this function we just need to return that storage variable.* + + +```solidity +function getListFunctionSignatures() external pure returns (bytes4[] memory functionSignatures, bytes32 moduleName); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`functionSignatures`|`bytes4[]`|The list of function signatures (bytes4[])| +|`moduleName`|`bytes32`|| + + +### mint + +BE CAREFUL, +LoanTokenLogicStandard also has mint & burn function (overloading). +You need to compute the function signature manually --> bytes4(keccak256("mint(address,uint256,bool)")) +LoanTokenLogicStandard +LoanTokenLogicLM +LoanTokenLogicStandard +LoanTokenLogicLM + +deposit into the lending pool and optionally participate at the Liquidity Mining Program + + +```solidity +function mint(address receiver, uint256 depositAmount, bool useLM) + external + nonReentrant + globallyNonReentrant + returns (uint256 minted); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|the receiver of the tokens| +|`depositAmount`|`uint256`|The amount of underlying tokens provided on the loan. (Not the number of loan tokens to mint).| +|`useLM`|`bool`|if true -> deposit the pool tokens into the Liquidity Mining contract| + + +### burn + +withdraws from the lending pool and optionally retrieves the pool tokens from the +Liquidity Mining Contract + + +```solidity +function burn(address receiver, uint256 burnAmount, bool useLM) + external + nonReentrant + globallyNonReentrant + returns (uint256 redeemed); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|the receiver of the underlying tokens. note: potetial LM rewards are always sent to the msg.sender| +|`burnAmount`|`uint256`|The amount of pool tokens to redeem.| +|`useLM`|`bool`|if true -> deposit the pool tokens into the Liquidity Mining contract| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/README.md b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/README.md new file mode 100644 index 000000000..e4f50dd15 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicLM/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [LoanTokenLogic](LoanTokenLogic.sol/contract.LoanTokenLogic.md) +- [LoanTokenLogicLM](LoanTokenLogicLM.sol/contract.LoanTokenLogicLM.md) diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtc.sol/contract.LoanTokenLogicWrbtc.md b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtc.sol/contract.LoanTokenLogicWrbtc.md new file mode 100644 index 000000000..9d903cfa4 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtc.sol/contract.LoanTokenLogicWrbtc.md @@ -0,0 +1,66 @@ +# LoanTokenLogicWrbtc +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtc.sol) + +**Inherits:** +[LoanTokenLogicStandard](/contracts/connectors/loantoken/LoanTokenLogicStandard.sol/contract.LoanTokenLogicStandard.md) + + +## Functions +### getListFunctionSignatures + +This function is MANDATORY, which will be called by LoanTokenLogicBeacon and be registered. +Every new public function, the signature needs to be included in this function. + +*This function will return the list of function signature in this contract that are available for public call +Then this function will be called by LoanTokenLogicBeacon, and the function signatures will be registred in LoanTokenLogicBeacon.* + +*To save the gas we can just directly return the list of function signature from this pure function. +The other workaround (fancy way) is we can create a storage for the list of the function signature, and then we can store each function signature to that storage from the constructor. +Then, in this function we just need to return that storage variable.* + + +```solidity +function getListFunctionSignatures() external pure returns (bytes4[] memory functionSignatures, bytes32 moduleName); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`functionSignatures`|`bytes4[]`|The list of function signatures (bytes4[])| +|`moduleName`|`bytes32`|| + + +### _verifyTransfers + +Handle transfers prior to adding newPrincipal to loanTokenSent. + +*internal override functions* + +*Put all of internal override function dedicated to the loanTokenWrtbc module here +e.g: _verifyTransfers will override the implementation of _verifyTransfers in loanTokenLogicSplit* + + +```solidity +function _verifyTransfers( + address collateralTokenAddress, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + MarginTradeStructHelpers.SentAmounts memory sentAmounts, + uint256 withdrawalAmount +) internal returns (uint256 msgValue); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`collateralTokenAddress`|`address`|The address of the collateral token.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The struct which contains addresses of - lender - borrower - receiver - manager| +|`sentAmounts`|`MarginTradeStructHelpers.SentAmounts`|The struct which contains uint256 of: - interestRate - newPrincipal - interestInitialAmount - loanTokenSent - collateralTokenSent| +|`withdrawalAmount`|`uint256`|The amount to withdraw.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`msgValue`|`uint256`|The amount of value sent.| + + diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtcLM.sol/contract.LoanTokenLogicWrbtcLM.md b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtcLM.sol/contract.LoanTokenLogicWrbtcLM.md new file mode 100644 index 000000000..140994d23 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtcLM.sol/contract.LoanTokenLogicWrbtcLM.md @@ -0,0 +1,55 @@ +# LoanTokenLogicWrbtcLM +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/modules/beaconLogicWRBTC/LoanTokenLogicWrbtcLM.sol) + +**Inherits:** +[LoanTokenLogicSplit](/contracts/connectors/loantoken/LoanTokenLogicSplit.sol/contract.LoanTokenLogicSplit.md) + + +## Functions +### getListFunctionSignatures + +This function is MANDATORY, which will be called by LoanTokenLogicBeacon and be registered. +Every new public function, the signature needs to be included in this function. + +*This function will return the list of function signature in this contract that are available for public call +Then this function will be called by LoanTokenLogicBeacon, and the function signatures will be registred in LoanTokenLogicBeacon.* + +*To save the gas we can just directly return the list of function signature from this pure function. +The other workaround (fancy way) is we can create a storage for the list of the function signature, and then we can store each function signature to that storage from the constructor. +Then, in this function we just need to return that storage variable.* + + +```solidity +function getListFunctionSignatures() external pure returns (bytes4[] memory functionSignatures, bytes32 moduleName); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`functionSignatures`|`bytes4[]`|The list of function signatures (bytes4[])| +|`moduleName`|`bytes32`|| + + +### mintWithBTC + + +```solidity +function mintWithBTC(address receiver, bool useLM) + external + payable + nonReentrant + globallyNonReentrant + returns (uint256 mintAmount); +``` + +### burnToBTC + + +```solidity +function burnToBTC(address receiver, uint256 burnAmount, bool useLM) + external + nonReentrant + globallyNonReentrant + returns (uint256 loanAmountPaid); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/README.md b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/README.md new file mode 100644 index 000000000..c4fe4f3f0 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/beaconLogicWRBTC/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [LoanTokenLogicWrbtc](LoanTokenLogicWrbtc.sol/contract.LoanTokenLogicWrbtc.md) +- [LoanTokenLogicWrbtcLM](LoanTokenLogicWrbtcLM.sol/contract.LoanTokenLogicWrbtcLM.md) diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/shared/LoanTokenSettingsLowerAdmin.sol/contract.LoanTokenSettingsLowerAdmin.md b/foundry/docs/src/contracts/connectors/loantoken/modules/shared/LoanTokenSettingsLowerAdmin.sol/contract.LoanTokenSettingsLowerAdmin.md new file mode 100644 index 000000000..cbce36361 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/shared/LoanTokenSettingsLowerAdmin.sol/contract.LoanTokenSettingsLowerAdmin.md @@ -0,0 +1,337 @@ +# LoanTokenSettingsLowerAdmin +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/connectors/loantoken/modules/shared/LoanTokenSettingsLowerAdmin.sol) + +**Inherits:** +[LoanTokenLogicStorage](/contracts/connectors/loantoken/LoanTokenLogicStorage.sol/contract.LoanTokenLogicStorage.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### onlyAdmin + +*TODO: Check for restrictions in this contract.* + + +```solidity +modifier onlyAdmin(); +``` + +### getListFunctionSignatures + +This function is MANDATORY, which will be called by LoanTokenLogicBeacon and be registered. +Every new public function, the signature needs to be included in this function. + +*This function will return the list of function signature in this contract that are available for public call +Then this function will be called by LoanTokenLogicBeacon, and the function signatures will be registred in LoanTokenLogicBeacon.* + +*To save the gas we can just directly return the list of function signature from this pure function. +The other workaround (fancy way) is we can create a storage for the list of the function signature, and then we can store each function signature to that storage from the constructor. +Then, in this function we just need to return that storage variable.* + + +```solidity +function getListFunctionSignatures() external pure returns (bytes4[] memory functionSignatures, bytes32 moduleName); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`functionSignatures`|`bytes4[]`|The list of function signatures (bytes4[])| +|`moduleName`|`bytes32`|| + + +### setAdmin + +Set admin account. + + +```solidity +function setAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The address of the account to grant admin permissions.| + + +### setPauser + +Set pauser account. + + +```solidity +function setPauser(address _pauser) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_pauser`|`address`|The address of the account to grant pause permissions.| + + +### function + +Fallback function not allowed + + +```solidity +function() external; +``` + +### setupLoanParams + +Set loan token parameters. + + +```solidity +function setupLoanParams(LoanParamsStruct.LoanParams[] memory loanParamsList, bool areTorqueLoans) public onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsList`|`LoanParamsStruct.LoanParams[]`|The array of loan parameters.| +|`areTorqueLoans`|`bool`|Whether the loan is a torque loan.| + + +### disableLoanParams + +isTorqueLoan + +Disable loan token parameters. + + +```solidity +function disableLoanParams(address[] calldata collateralTokens, bool[] calldata isTorqueLoans) external onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`collateralTokens`|`address[]`|The array of collateral tokens.| +|`isTorqueLoans`|`bool[]`|Whether the loan is a torque loan.| + + +### setDemandCurve + +Set loan token parameters about the demand curve. + +*These params should be percentages represented +like so: 5% = 5000000000000000000 /// 18 digits precision. +rateMultiplier + baseRate can't exceed 100% +To maintain a healthy credit score, it's important to keep your +credit utilization rate (CUR) low (_lowUtilBaseRate). In general +you don't want your CUR to exceed 30%, but increasingly financial +experts are recommending that you don't want to go above 10% if you +really want an excellent credit score. +Interest rates tend to cluster around the kink level of a kinked +interest rate model. More info at https://arxiv.org/pdf/2006.13922.pdf +and https://compound.finance/governance/proposals/12* + + +```solidity +function setDemandCurve( + uint256 _baseRate, + uint256 _rateMultiplier, + uint256 _lowUtilBaseRate, + uint256 _lowUtilRateMultiplier, + uint256 _targetLevel, + uint256 _kinkLevel, + uint256 _maxScaleRate +) public onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_baseRate`|`uint256`|The interest rate.| +|`_rateMultiplier`|`uint256`|The precision multiplier for base rate.| +|`_lowUtilBaseRate`|`uint256`|The credit utilization rate (CUR) low value.| +|`_lowUtilRateMultiplier`|`uint256`|The precision multiplier for low util base rate.| +|`_targetLevel`|`uint256`|The target level.| +|`_kinkLevel`|`uint256`|The level that interest rates cluster on kinked model.| +|`_maxScaleRate`|`uint256`|The maximum rate of the scale.| + + +### toggleFunctionPause + +80 ether +90 ether +100 ether + +Set the pause flag for a function to true or false. + +*Combining the hash of "iToken_FunctionPause" string and a function +selector gets a slot to write a flag for pause state.* + + +```solidity +function toggleFunctionPause(string memory funcId, bool isPaused) public onlyPauserOrOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`funcId`|`string`|The ID of a function, the selector.| +|`isPaused`|`bool`|true/false value of the flag.| + + +### setTransactionLimits + +keccak256("iToken_FunctionPause") +Set the transaction limit per token address. + + +```solidity +function setTransactionLimits(address[] memory addresses, uint256[] memory limits) public onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`addresses`|`address[]`|The token addresses.| +|`limits`|`uint256[]`|The limit denominated in the currency of the token address.| + + +### changeLoanTokenNameAndSymbol + +Update the loan token parameters. + + +```solidity +function changeLoanTokenNameAndSymbol(string memory _name, string memory _symbol) public onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_name`|`string`|The new name of the loan token.| +|`_symbol`|`string`|The new symbol of the loan token.| + + +### withdrawRBTCTo + +Withdraws RBTC from the contract by Multisig. + + +```solidity +function withdrawRBTCTo(address payable _receiverAddress, uint256 _amount) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiverAddress`|`address payable`|The address where the rBTC has to be transferred.| +|`_amount`|`uint256`|The amount of rBTC to be transferred.| + + +### setLiquidityMiningAddress + +sets the liquidity mining contract address + + +```solidity +function setLiquidityMiningAddress(address LMAddress) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`LMAddress`|`address`|the address of the liquidity mining contract| + + +### getLiquidityMiningAddress + +We need separate getter for newly added storage variable + +Getter for liquidityMiningAddress + + +```solidity +function getLiquidityMiningAddress() public view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|liquidityMiningAddress| + + +### setStakingContractAddress + +sets the staking contract address + + +```solidity +function setStakingContractAddress(address _stakingContractAddress) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_stakingContractAddress`|`address`|the address of the staking contract| + + +### getStakingContractAddress + +We need separate getter for newly added storage variable + +Getter for stakingContractAddress + + +```solidity +function getStakingContractAddress() public view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|stakingContractAddress| + + +### checkPause + +Check whether a function is paused. + +*Used to read externally from the smart contract to see if a +function is paused.* + + +```solidity +function checkPause(string memory funcId) public view returns (bool isPaused); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`funcId`|`string`|The function ID, the selector.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`isPaused`|`bool`|Whether the function is paused: true or false.| + + +## Events +### SetTransactionLimits + +```solidity +event SetTransactionLimits(address[] addresses, uint256[] limits); +``` + +### ToggledFunctionPaused + +```solidity +event ToggledFunctionPaused(string functionId, bool prevFlag, bool newFlag); +``` + +### WithdrawRBTCTo + +```solidity +event WithdrawRBTCTo(address indexed to, uint256 amount); +``` + diff --git a/foundry/docs/src/contracts/connectors/loantoken/modules/shared/README.md b/foundry/docs/src/contracts/connectors/loantoken/modules/shared/README.md new file mode 100644 index 000000000..71dbf0a32 --- /dev/null +++ b/foundry/docs/src/contracts/connectors/loantoken/modules/shared/README.md @@ -0,0 +1,4 @@ + + +# Contents +- [LoanTokenSettingsLowerAdmin](LoanTokenSettingsLowerAdmin.sol/contract.LoanTokenSettingsLowerAdmin.md) diff --git a/foundry/docs/src/contracts/core/Objects.sol/contract.Objects.md b/foundry/docs/src/contracts/core/Objects.sol/contract.Objects.md new file mode 100644 index 000000000..0971e3694 --- /dev/null +++ b/foundry/docs/src/contracts/core/Objects.sol/contract.Objects.md @@ -0,0 +1,15 @@ +# Objects +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/Objects.sol) + +**Inherits:** +[LoanStruct](/contracts/core/objects/LoanStruct.sol/contract.LoanStruct.md), [LoanParamsStruct](/contracts/core/objects/LoanParamsStruct.sol/contract.LoanParamsStruct.md), [OrderStruct](/contracts/core/objects/OrderStruct.sol/contract.OrderStruct.md), [LenderInterestStruct](/contracts/core/objects/LenderInterestStruct.sol/contract.LenderInterestStruct.md), [LoanInterestStruct](/contracts/core/objects/LoanInterestStruct.sol/contract.LoanInterestStruct.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract inherints and aggregates several structures needed to handle +loans on the protocol. + + diff --git a/foundry/docs/src/contracts/core/Protocol.sol/contract.sovrynProtocol.md b/foundry/docs/src/contracts/core/Protocol.sol/contract.sovrynProtocol.md new file mode 100644 index 000000000..844a656f7 --- /dev/null +++ b/foundry/docs/src/contracts/core/Protocol.sol/contract.sovrynProtocol.md @@ -0,0 +1,82 @@ +# sovrynProtocol +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/Protocol.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the proxy functionality to deploy Protocol anchor +and logic apart, turning it upgradable. + +*TODO: can I change this proxy to EIP-1822 proxy standard, please. +https://eips.ethereum.org/EIPS/eip-1822* + + +## Functions +### function + +Fallback function performs a delegate call +to the actual implementation address is pointing this proxy. +Returns whatever the implementation call returns. + + +```solidity +function() external payable; +``` + +### replaceContract + +External owner target initializer. + + +```solidity +function replaceContract(address target) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The target addresses.| + + +### setTargets + +External owner setter for target addresses. + + +```solidity +function setTargets(string[] calldata sigsArr, address[] calldata targetsArr) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sigsArr`|`string[]`|The array of signatures.| +|`targetsArr`|`address[]`|The array of addresses.| + + +### getTarget + +External getter for target addresses. + + +```solidity +function getTarget(string calldata sig) external view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sig`|`string`|The signature.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The address for a given signature.| + + diff --git a/foundry/docs/src/contracts/core/README.md b/foundry/docs/src/contracts/core/README.md new file mode 100644 index 000000000..9a5adbbc6 --- /dev/null +++ b/foundry/docs/src/contracts/core/README.md @@ -0,0 +1,7 @@ + + +# Contents +- [objects](/contracts/core/objects) +- [Objects](Objects.sol/contract.Objects.md) +- [sovrynProtocol](Protocol.sol/contract.sovrynProtocol.md) +- [State](State.sol/contract.State.md) diff --git a/foundry/docs/src/contracts/core/State.sol/contract.State.md b/foundry/docs/src/contracts/core/State.sol/contract.State.md new file mode 100644 index 000000000..16aef263d --- /dev/null +++ b/foundry/docs/src/contracts/core/State.sol/contract.State.md @@ -0,0 +1,588 @@ +# State +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/State.sol) + +**Inherits:** +[Objects](/contracts/core/Objects.sol/contract.Objects.md), [ReentrancyGuard](/contracts/openzeppelin/ReentrancyGuard.sol/contract.ReentrancyGuard.md), [SharedReentrancyGuard](/contracts/reentrancy/SharedReentrancyGuard.sol/contract.SharedReentrancyGuard.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the storage values of the Protocol. + + +## State Variables +### priceFeeds +Handles asset reference price lookups. + + +```solidity +address public priceFeeds; +``` + + +### swapsImpl +Handles asset swaps using dex liquidity. + + +```solidity +address public swapsImpl; +``` + + +### sovrynSwapContractRegistryAddress +Contract registry address of the Sovryn swap network. + + +```solidity +address public sovrynSwapContractRegistryAddress; +``` + + +### logicTargets +Implementations of protocol functions. + + +```solidity +mapping(bytes4 => address) public logicTargets; +``` + + +### loans +Loans: loanId => Loan + + +```solidity +mapping(bytes32 => Loan) public loans; +``` + + +### loanParams +Loan parameters: loanParamsId => LoanParams + + +```solidity +mapping(bytes32 => LoanParams) public loanParams; +``` + + +### lenderOrders +lender => orderParamsId => Order + + +```solidity +mapping(address => mapping(bytes32 => Order)) public lenderOrders; +``` + + +### borrowerOrders +borrower => orderParamsId => Order + + +```solidity +mapping(address => mapping(bytes32 => Order)) public borrowerOrders; +``` + + +### delegatedManagers +loanId => delegated => approved + + +```solidity +mapping(bytes32 => mapping(address => bool)) public delegatedManagers; +``` + + +### lenderInterest +Interest *** +lender => loanToken => LenderInterest object + + +```solidity +mapping(address => mapping(address => LenderInterest)) public lenderInterest; +``` + + +### loanInterest +loanId => LoanInterest object + + +```solidity +mapping(bytes32 => LoanInterest) public loanInterest; +``` + + +### logicTargetsSet +Internals *** +Implementations set. + + +```solidity +EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; +``` + + +### activeLoansSet +Active loans set. + + +```solidity +EnumerableBytes32Set.Bytes32Set internal activeLoansSet; +``` + + +### lenderLoanSets +Lender loans set. + + +```solidity +mapping(address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; +``` + + +### borrowerLoanSets +Borrow loans set. + + +```solidity +mapping(address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; +``` + + +### userLoanParamSets +User loan params set. + + +```solidity +mapping(address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; +``` + + +### feesController +Address controlling fee withdrawals. + + +```solidity +address public feesController; +``` + + +### lendingFeePercent +10% fee /// Fee taken from lender interest payments. + + +```solidity +uint256 public lendingFeePercent = 10 ** 19; +``` + + +### lendingFeeTokensHeld +Total interest fees received and not withdrawn per asset. + + +```solidity +mapping(address => uint256) public lendingFeeTokensHeld; +``` + + +### lendingFeeTokensPaid +Total interest fees withdraw per asset. +lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid + + +```solidity +mapping(address => uint256) public lendingFeeTokensPaid; +``` + + +### tradingFeePercent +0.15% fee /// Fee paid for each trade. + + +```solidity +uint256 public tradingFeePercent = 15 * 10 ** 16; +``` + + +### tradingFeeTokensHeld +Total trading fees received and not withdrawn per asset. + + +```solidity +mapping(address => uint256) public tradingFeeTokensHeld; +``` + + +### tradingFeeTokensPaid +Total trading fees withdraw per asset +lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid + + +```solidity +mapping(address => uint256) public tradingFeeTokensPaid; +``` + + +### borrowingFeePercent +0.09% fee /// Origination fee paid for each loan. + + +```solidity +uint256 public borrowingFeePercent = 9 * 10 ** 16; +``` + + +### borrowingFeeTokensHeld +Total borrowing fees received and not withdrawn per asset. + + +```solidity +mapping(address => uint256) public borrowingFeeTokensHeld; +``` + + +### borrowingFeeTokensPaid +Total borrowing fees withdraw per asset. +lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid + + +```solidity +mapping(address => uint256) public borrowingFeeTokensPaid; +``` + + +### protocolTokenHeld +Current protocol token deposit balance. + + +```solidity +uint256 public protocolTokenHeld; +``` + + +### protocolTokenPaid +Lifetime total payout of protocol token. + + +```solidity +uint256 public protocolTokenPaid; +``` + + +### affiliateFeePercent +5% fee share in form of SOV /// Fee share for affiliate program. + + +```solidity +uint256 public affiliateFeePercent = 5 * 10 ** 18; +``` + + +### liquidationIncentivePercent +5% collateral discount /// Discount on collateral for liquidators. + + +```solidity +uint256 public liquidationIncentivePercent = 5 * 10 ** 18; +``` + + +### loanPoolToUnderlying +loanPool => underlying + + +```solidity +mapping(address => address) public loanPoolToUnderlying; +``` + + +### underlyingToLoanPool +underlying => loanPool + + +```solidity +mapping(address => address) public underlyingToLoanPool; +``` + + +### loanPoolsSet +Loan pools set. + + +```solidity +EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; +``` + + +### supportedTokens +Supported tokens for swaps. + + +```solidity +mapping(address => bool) public supportedTokens; +``` + + +### maxDisagreement +% disagreement between swap rate and reference rate. + + +```solidity +uint256 public maxDisagreement = 5 * 10 ** 18; +``` + + +### sourceBuffer +Used as buffer for swap source amount estimations. + + +```solidity +uint256 public sourceBuffer = 10000; +``` + + +### maxSwapSize +Maximum support swap size in rBTC + + +```solidity +uint256 public maxSwapSize = 50 ether; +``` + + +### borrowerNonce +Nonce per borrower. Used for loan id creation. + + +```solidity +mapping(address => uint256) public borrowerNonce; +``` + + +### rolloverBaseReward +Rollover transaction costs around 0.0000168 rBTC, it is denominated in wrBTC. + + +```solidity +uint256 public rolloverBaseReward = 16800000000000; +``` + + +### rolloverFlexFeePercent + +```solidity +uint256 public rolloverFlexFeePercent = 0.1 ether; +``` + + +### wrbtcToken +0.1% + + +```solidity +IWrbtcERC20 public wrbtcToken; +``` + + +### protocolTokenAddress + +```solidity +address public protocolTokenAddress; +``` + + +### feeRebatePercent +50% fee rebate +potocolToken reward to user, it is worth % of trading/borrowing fee. + + +```solidity +uint256 public feeRebatePercent = 50 * 10 ** 18; +``` + + +### admin + +```solidity +address public admin; +``` + + +### protocolAddress +For modules interaction. + + +```solidity +address public protocolAddress; +``` + + +### userNotFirstTradeFlag +Affiliates *** +The flag is set on the user's first trade. + + +```solidity +mapping(address => bool) public userNotFirstTradeFlag; +``` + + +### affiliatesUserReferrer +User => referrer (affiliate). + + +```solidity +mapping(address => address) public affiliatesUserReferrer; +``` + + +### referralsList +List of referral addresses affiliated to the referrer. + + +```solidity +mapping(address => EnumerableAddressSet.AddressSet) internal referralsList; +``` + + +### minReferralsToPayout +*Referral threshold for paying out to the referrer. +The referrer reward is being accumulated and locked until the threshold is passed.* + + +```solidity +uint256 public minReferralsToPayout = 3; +``` + + +### affiliateRewardsHeld +*Total affiliate SOV rewards that held in the protocol +(Because the minimum referrals is less than the rule)* + + +```solidity +mapping(address => uint256) public affiliateRewardsHeld; +``` + + +### sovTokenAddress +*For affiliates SOV Bonus proccess.* + + +```solidity +address public sovTokenAddress; +``` + + +### lockedSOVAddress + +```solidity +address public lockedSOVAddress; +``` + + +### affiliateTradingTokenFeePercent +*20% fee share of trading token fee. +Fee share of trading token fee for affiliate program.* + + +```solidity +uint256 public affiliateTradingTokenFeePercent = 20 * 10 ** 18; +``` + + +### affiliatesReferrerTokensList +*Addresses of tokens in which commissions were paid to referrers.* + + +```solidity +mapping(address => EnumerableAddressSet.AddressSet) internal affiliatesReferrerTokensList; +``` + + +### affiliatesReferrerBalances +*[referrerAddress][tokenAddress] is a referrer's token balance of accrued fees.* + + +```solidity +mapping(address => mapping(address => uint256)) public affiliatesReferrerBalances; +``` + + +### specialRebates + +```solidity +mapping(address => mapping(address => uint256)) public specialRebates; +``` + + +### pause + +```solidity +bool public pause; +``` + + +### swapExtrernalFeePercent + +```solidity +uint256 internal swapExtrernalFeePercent; +``` + + +### tradingRebateRewardsBasisPoint +Fee percentage for protocol swap + +*Defines the portion of the trading rebate rewards (SOV) which is to be paid out in a liquid form in basis points. The rest is vested. The max value is 9999 (means 99.99% liquid, 0.01% vested)* + + +```solidity +uint256 internal tradingRebateRewardsBasisPoint; +``` + + +### defaultPathConversion +*Defines the defaultPath of conversion swap. This is created to prevent the non-rbtc pairs returning the shortest path which will not give the best rate. +Will be used in internal swap.* + + +```solidity +mapping(address => mapping(address => IERC20[])) internal defaultPathConversion; +``` + + +### pauser + +```solidity +address internal pauser; +``` + + +## Functions +### _setTarget + +Add signature and target to storage. + +*Protocol is a proxy and requires a way to add every +module function dynamically during deployment.* + + +```solidity +function _setTarget(bytes4 sig, address target) internal; +``` + +### onlyAdminOrOwner + + +```solidity +modifier onlyAdminOrOwner(); +``` + +### onlyPauserOrOwner + + +```solidity +modifier onlyPauserOrOwner(); +``` + diff --git a/foundry/docs/src/contracts/core/objects/LenderInterestStruct.sol/contract.LenderInterestStruct.md b/foundry/docs/src/contracts/core/objects/LenderInterestStruct.sol/contract.LenderInterestStruct.md new file mode 100644 index 000000000..318c03c33 --- /dev/null +++ b/foundry/docs/src/contracts/core/objects/LenderInterestStruct.sol/contract.LenderInterestStruct.md @@ -0,0 +1,24 @@ +# LenderInterestStruct +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/objects/LenderInterestStruct.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the storage structure of the Lender Interest. + + +## Structs +### LenderInterest + +```solidity +struct LenderInterest { + uint256 principalTotal; + uint256 owedPerDay; + uint256 owedTotal; + uint256 paidTotal; + uint256 updatedTimestamp; +} +``` + diff --git a/foundry/docs/src/contracts/core/objects/LoanInterestStruct.sol/contract.LoanInterestStruct.md b/foundry/docs/src/contracts/core/objects/LoanInterestStruct.sol/contract.LoanInterestStruct.md new file mode 100644 index 000000000..315bd504b --- /dev/null +++ b/foundry/docs/src/contracts/core/objects/LoanInterestStruct.sol/contract.LoanInterestStruct.md @@ -0,0 +1,22 @@ +# LoanInterestStruct +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/objects/LoanInterestStruct.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the storage structure of the Loan Interest. + + +## Structs +### LoanInterest + +```solidity +struct LoanInterest { + uint256 owedPerDay; + uint256 depositTotal; + uint256 updatedTimestamp; +} +``` + diff --git a/foundry/docs/src/contracts/core/objects/LoanParamsStruct.sol/contract.LoanParamsStruct.md b/foundry/docs/src/contracts/core/objects/LoanParamsStruct.sol/contract.LoanParamsStruct.md new file mode 100644 index 000000000..6c63d5548 --- /dev/null +++ b/foundry/docs/src/contracts/core/objects/LoanParamsStruct.sol/contract.LoanParamsStruct.md @@ -0,0 +1,27 @@ +# LoanParamsStruct +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/objects/LoanParamsStruct.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the storage structure of the Loan Parameters. + + +## Structs +### LoanParams + +```solidity +struct LoanParams { + bytes32 id; + bool active; + address owner; + address loanToken; + address collateralToken; + uint256 minInitialMargin; + uint256 maintenanceMargin; + uint256 maxLoanTerm; +} +``` + diff --git a/foundry/docs/src/contracts/core/objects/LoanStruct.sol/contract.LoanStruct.md b/foundry/docs/src/contracts/core/objects/LoanStruct.sol/contract.LoanStruct.md new file mode 100644 index 000000000..8bceb619a --- /dev/null +++ b/foundry/docs/src/contracts/core/objects/LoanStruct.sol/contract.LoanStruct.md @@ -0,0 +1,31 @@ +# LoanStruct +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/objects/LoanStruct.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the storage structure of the Loan Object. + + +## Structs +### Loan + +```solidity +struct Loan { + bytes32 id; + bytes32 loanParamsId; + bytes32 pendingTradesId; + bool active; + uint256 principal; + uint256 collateral; + uint256 startTimestamp; + uint256 endTimestamp; + uint256 startMargin; + uint256 startRate; + address borrower; + address lender; +} +``` + diff --git a/foundry/docs/src/contracts/core/objects/OrderStruct.sol/contract.OrderStruct.md b/foundry/docs/src/contracts/core/objects/OrderStruct.sol/contract.OrderStruct.md new file mode 100644 index 000000000..04ee5ced8 --- /dev/null +++ b/foundry/docs/src/contracts/core/objects/OrderStruct.sol/contract.OrderStruct.md @@ -0,0 +1,25 @@ +# OrderStruct +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/core/objects/OrderStruct.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the storage structure of the Loan Order. + + +## Structs +### Order + +```solidity +struct Order { + uint256 lockedAmount; + uint256 interestRate; + uint256 minLoanTerm; + uint256 maxLoanTerm; + uint256 createdTimestamp; + uint256 expirationTimestamp; +} +``` + diff --git a/foundry/docs/src/contracts/core/objects/README.md b/foundry/docs/src/contracts/core/objects/README.md new file mode 100644 index 000000000..d912dd1dd --- /dev/null +++ b/foundry/docs/src/contracts/core/objects/README.md @@ -0,0 +1,8 @@ + + +# Contents +- [LenderInterestStruct](LenderInterestStruct.sol/contract.LenderInterestStruct.md) +- [LoanInterestStruct](LoanInterestStruct.sol/contract.LoanInterestStruct.md) +- [LoanParamsStruct](LoanParamsStruct.sol/contract.LoanParamsStruct.md) +- [LoanStruct](LoanStruct.sol/contract.LoanStruct.md) +- [OrderStruct](OrderStruct.sol/contract.OrderStruct.md) diff --git a/foundry/docs/src/contracts/escrow/Escrow.sol/contract.Escrow.md b/foundry/docs/src/contracts/escrow/Escrow.sol/contract.Escrow.md new file mode 100644 index 000000000..734160df3 --- /dev/null +++ b/foundry/docs/src/contracts/escrow/Escrow.sol/contract.Escrow.md @@ -0,0 +1,439 @@ +# Escrow +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/escrow/Escrow.sol) + +**Author:** +Franklin Richards - powerhousefrank@protonmail.com + +You can use this contract for deposit of SOV tokens for some time and withdraw later. + + +## State Variables +### totalDeposit +The total tokens deposited. + +*Used for calculating the reward % share of users related to total deposit.* + + +```solidity +uint256 public totalDeposit; +``` + + +### releaseTime +The release timestamp for the tokens deposited. + + +```solidity +uint256 public releaseTime; +``` + + +### depositLimit +The amount of token we would be accepting as deposit at max. + + +```solidity +uint256 public depositLimit; +``` + + +### SOV +The SOV token contract. + + +```solidity +IERC20 public SOV; +``` + + +### multisig +The multisig contract which handles the fund. + + +```solidity +address public multisig; +``` + + +### userBalances +The user balances. + + +```solidity +mapping(address => uint256) userBalances; +``` + + +### status + +```solidity +Status public status; +``` + + +## Functions +### onlyMultisig + + +```solidity +modifier onlyMultisig(); +``` + +### checkStatus + + +```solidity +modifier checkStatus(Status s); +``` + +### checkRelease + + +```solidity +modifier checkRelease(); +``` + +### constructor + +Setup the required parameters. + + +```solidity +constructor(address _SOV, address _multisig, uint256 _releaseTime, uint256 _depositLimit) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`address`|The SOV token address.| +|`_multisig`|`address`|The owner of the tokens & contract.| +|`_releaseTime`|`uint256`|The token release time, zero if undecided.| +|`_depositLimit`|`uint256`|The amount of tokens we will be accepting.| + + +### init + +This function is called once after deployment for starting the deposit action. + +*Without calling this function, the contract will not start accepting tokens.* + + +```solidity +function init() external onlyMultisig checkStatus(Status.Deployed); +``` + +### updateMultisig + +Update Multisig. + + +```solidity +function updateMultisig(address _newMultisig) external onlyMultisig; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newMultisig`|`address`|The new owner of the tokens & contract.| + + +### updateReleaseTimestamp + +Update Release Timestamp. + +*Zero is also a valid timestamp, if the release time is not scheduled yet.* + + +```solidity +function updateReleaseTimestamp(uint256 _newReleaseTime) external onlyMultisig; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newReleaseTime`|`uint256`|The new release timestamp for token release.| + + +### updateDepositLimit + +Update Deposit Limit. + +*IMPORTANT: Should not decrease than already deposited.* + + +```solidity +function updateDepositLimit(uint256 _newDepositLimit) external onlyMultisig; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newDepositLimit`|`uint256`|The new deposit limit.| + + +### depositTokens + +Deposit tokens to this contract by User. + +*The contract has to be approved by the user inorder for this function to work. +These tokens can be withdrawn/transferred during Holding State by the Multisig.* + + +```solidity +function depositTokens(uint256 _amount) external checkStatus(Status.Deposit); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|the amount of tokens deposited.| + + +### changeStateToHolding + +Update contract state to Holding. + +*Once called, the contract no longer accepts any more deposits. +The multisig can now withdraw tokens from the contract after the contract is in Holding State.* + + +```solidity +function changeStateToHolding() external onlyMultisig checkStatus(Status.Deposit); +``` + +### withdrawTokensByMultisig + +Withdraws all token from the contract by Multisig. + +*Can only be called after the token state is changed to Holding.* + + +```solidity +function withdrawTokensByMultisig(address _receiverAddress) external onlyMultisig checkStatus(Status.Holding); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiverAddress`|`address`|The address where the tokens has to be transferred. Zero address if the withdraw is to be done in Multisig.| + + +### depositTokensByMultisig + +Sending the amount to multisig. + +Deposit tokens to this contract by the Multisig. + +*The contract has to be approved by the multisig inorder for this function to work. +Once the token deposit is higher than the total deposits done, the contract state is changed to Withdraw.* + + +```solidity +function depositTokensByMultisig(uint256 _amount) external onlyMultisig checkStatus(Status.Holding); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|the amount of tokens deposited.| + + +### withdrawTokens + +Withdraws token from the contract by User. + +*Only works after the contract state is in Withdraw.* + + +```solidity +function withdrawTokens() public checkRelease checkStatus(Status.Withdraw); +``` + +### getUserBalance + +Function to read the current token balance of a particular user. + + +```solidity +function getUserBalance(address _addr) external view returns (uint256 balance); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`balance`|`uint256`|_addr The user address whose balance has to be checked.| + + +## Events +### EscrowActivated +Emitted when the contract deposit starts. + + +```solidity +event EscrowActivated(); +``` + +### EscrowInHoldingState +Emitted when the contract is put in holding state. No new token deposit accepted by User. + + +```solidity +event EscrowInHoldingState(); +``` + +### EscrowInWithdrawState +Emitted when the contract is put in withdraw state. Users can now withdraw tokens. + + +```solidity +event EscrowInWithdrawState(); +``` + +### EscrowFundExpired +Emitted when the contract is expired after withdraws are made/total token transfer. + + +```solidity +event EscrowFundExpired(); +``` + +### NewMultisig +Emitted when a new multisig is added to the contract. + +*Can only be initiated by the current multisig.* + + +```solidity +event NewMultisig(address indexed _initiator, address indexed _newMultisig); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_newMultisig`|`address`|The address which is added as the new multisig.| + +### TokenReleaseUpdated +Emitted when the release timestamp is updated. + + +```solidity +event TokenReleaseUpdated(address indexed _initiator, uint256 _releaseTimestamp); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_releaseTimestamp`|`uint256`|The updated release timestamp for the withdraw.| + +### TokenDepositLimitUpdated +Emitted when the deposit limit is updated. + + +```solidity +event TokenDepositLimitUpdated(address indexed _initiator, uint256 _depositLimit); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_depositLimit`|`uint256`|The updated deposit limit.| + +### TokenDeposit +Emitted when a new token deposit is done by User. + + +```solidity +event TokenDeposit(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The amount of token deposited.| + +### DepositLimitReached +Emitted when we reach the token deposit limit. + + +```solidity +event DepositLimitReached(); +``` + +### TokenWithdrawByMultisig +Emitted when a token withdraw is done by Multisig. + + +```solidity +event TokenWithdrawByMultisig(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The amount of token withdrawed.| + +### TokenDepositByMultisig +Emitted when a new token deposit is done by Multisig. + + +```solidity +event TokenDepositByMultisig(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The amount of token deposited.| + +### TokenWithdraw +Emitted when a token withdraw is done by User. + + +```solidity +event TokenWithdraw(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The amount of token withdrawed.| + +## Enums +### Status +The current contract status. + +Deployed - Deployed the contract. + +Deposit - Time to deposit in the contract by the users. + +Holding - Deposit is closed and now the holding period starts. + +Withdraw - Time to withdraw in the contract by the users. + +Expired - The contract is now closed completely. + + +```solidity +enum Status { + Deployed, + Deposit, + Holding, + Withdraw, + Expired +} +``` + diff --git a/foundry/docs/src/contracts/escrow/EscrowReward.sol/contract.EscrowReward.md b/foundry/docs/src/contracts/escrow/EscrowReward.sol/contract.EscrowReward.md new file mode 100644 index 000000000..24511fa10 --- /dev/null +++ b/foundry/docs/src/contracts/escrow/EscrowReward.sol/contract.EscrowReward.md @@ -0,0 +1,165 @@ +# EscrowReward +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/escrow/EscrowReward.sol) + +**Inherits:** +[Escrow](/contracts/escrow/Escrow.sol/contract.Escrow.md) + +**Author:** +Franklin Richards - powerhousefrank@protonmail.com + +Multisig can use this contract for depositing of Reward tokens based on the total token deposit. + + +## State Variables +### totalRewardDeposit +The total reward tokens deposited. + +*Used for calculating the reward % share of users related to total deposit.* + + +```solidity +uint256 public totalRewardDeposit; +``` + + +### lockedSOV +The Locked SOV contract. + + +```solidity +ILockedSOV public lockedSOV; +``` + + +## Functions +### constructor + +Setup the required parameters. + + +```solidity +constructor(address _lockedSOV, address _SOV, address _multisig, uint256 _releaseTime, uint256 _depositLimit) + public + Escrow(_SOV, _multisig, _releaseTime, _depositLimit); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_lockedSOV`|`address`|The Locked SOV Contract address.| +|`_SOV`|`address`|The SOV token address.| +|`_multisig`|`address`|The owner of the tokens & contract.| +|`_releaseTime`|`uint256`|The token release time, zero if undecided.| +|`_depositLimit`|`uint256`|The amount of tokens we will be accepting.| + + +### updateLockedSOV + +Set the Locked SOV Contract Address if not already done. + + +```solidity +function updateLockedSOV(address _lockedSOV) external onlyMultisig; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_lockedSOV`|`address`|The Locked SOV Contract address.| + + +### depositRewardByMultisig + +Deposit tokens to this contract by the Multisig. + +*The contract has to be approved by the multisig inorder for this function to work.* + + +```solidity +function depositRewardByMultisig(uint256 _amount) external onlyMultisig; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|the amount of tokens deposited.| + + +### withdrawTokensAndReward + +Withdraws token and reward from the contract by User. Reward is gone to lockedSOV contract for future vesting. + +*Only works after the contract state is in Withdraw.* + + +```solidity +function withdrawTokensAndReward() external checkRelease checkStatus(Status.Withdraw); +``` + +### getReward + +Function to read the reward a particular user can get. + + +```solidity +function getReward(address _addr) external view returns (uint256 reward); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_addr`|`address`|The address of the user whose reward is to be read.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`reward`|`uint256`|The reward received by the user.| + + +## Events +### LockedSOVUpdated +Emitted when the Locked SOV Contract address is updated. + + +```solidity +event LockedSOVUpdated(address indexed _initiator, address indexed _lockedSOV); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_lockedSOV`|`address`|The address of the Locked SOV Contract.| + +### RewardDepositByMultisig +Emitted when a new reward token deposit is done by Multisig. + + +```solidity +event RewardDepositByMultisig(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The amount of token deposited.| + +### RewardTokenWithdraw +Emitted when a Reward token withdraw is done by User. + + +```solidity +event RewardTokenWithdraw(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The amount of token withdrawed.| + diff --git a/foundry/docs/src/contracts/escrow/README.md b/foundry/docs/src/contracts/escrow/README.md new file mode 100644 index 000000000..dea395895 --- /dev/null +++ b/foundry/docs/src/contracts/escrow/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [Escrow](Escrow.sol/contract.Escrow.md) +- [EscrowReward](EscrowReward.sol/contract.EscrowReward.md) diff --git a/foundry/docs/src/contracts/events/AffiliatesEvents.sol/contract.AffiliatesEvents.md b/foundry/docs/src/contracts/events/AffiliatesEvents.sol/contract.AffiliatesEvents.md new file mode 100644 index 000000000..f5a1ec1ac --- /dev/null +++ b/foundry/docs/src/contracts/events/AffiliatesEvents.sol/contract.AffiliatesEvents.md @@ -0,0 +1,68 @@ +# AffiliatesEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/AffiliatesEvents.sol) + +**Inherits:** +[ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Events +### SetAffiliatesReferrer + +```solidity +event SetAffiliatesReferrer(address indexed user, address indexed referrer); +``` + +### SetAffiliatesReferrerFail + +```solidity +event SetAffiliatesReferrerFail( + address indexed user, address indexed referrer, bool alreadySet, bool userNotFirstTrade +); +``` + +### SetUserNotFirstTradeFlag + +```solidity +event SetUserNotFirstTradeFlag(address indexed user); +``` + +### PayTradingFeeToAffiliate + +```solidity +event PayTradingFeeToAffiliate( + address indexed referrer, + address trader, + address indexed token, + bool indexed isHeld, + uint256 tradingFeeTokenAmount, + uint256 tokenBonusAmount, + uint256 sovBonusAmount, + uint256 sovBonusAmountPaid +); +``` + +### PayTradingFeeToAffiliateFail + +```solidity +event PayTradingFeeToAffiliateFail( + address indexed referrer, + address trader, + address indexed token, + uint256 tradingFeeTokenAmount, + uint256 tokenBonusAmount, + uint256 sovBonusAmount, + uint256 sovBonusAmountTryingToPaid +); +``` + +### WithdrawAffiliatesReferrerTokenFees + +```solidity +event WithdrawAffiliatesReferrerTokenFees( + address indexed referrer, address indexed receiver, address indexed tokenAddress, uint256 amount +); +``` + diff --git a/foundry/docs/src/contracts/events/FeesEvents.sol/contract.FeesEvents.md b/foundry/docs/src/contracts/events/FeesEvents.sol/contract.FeesEvents.md new file mode 100644 index 000000000..77acf48de --- /dev/null +++ b/foundry/docs/src/contracts/events/FeesEvents.sol/contract.FeesEvents.md @@ -0,0 +1,56 @@ +# FeesEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/FeesEvents.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the events for fee payments. + + +## Events +### PayLendingFee + +```solidity +event PayLendingFee(address indexed payer, address indexed token, uint256 amount); +``` + +### PayTradingFee + +```solidity +event PayTradingFee(address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount); +``` + +### PayBorrowingFee + +```solidity +event PayBorrowingFee(address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount); +``` + +### EarnReward + +```solidity +event EarnReward( + address indexed receiver, + address indexed token, + bytes32 indexed loanId, + uint256 feeRebatePercent, + uint256 amount, + uint256 basisPoint +); +``` + +### EarnRewardFail + +```solidity +event EarnRewardFail( + address indexed receiver, + address indexed token, + bytes32 indexed loanId, + uint256 feeRebatePercent, + uint256 amount, + uint256 basisPoint +); +``` + diff --git a/foundry/docs/src/contracts/events/LoanClosingsEvents.sol/contract.LoanClosingsEvents.md b/foundry/docs/src/contracts/events/LoanClosingsEvents.sol/contract.LoanClosingsEvents.md new file mode 100644 index 000000000..fe06f302d --- /dev/null +++ b/foundry/docs/src/contracts/events/LoanClosingsEvents.sol/contract.LoanClosingsEvents.md @@ -0,0 +1,93 @@ +# LoanClosingsEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/LoanClosingsEvents.sol) + +**Inherits:** +[ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the events for loan closing operations. + + +## Events +### CloseWithDeposit +topic0: 0x6349c1a02ec126f7f4fc6e6837e1859006e90e9901635c442d29271e77b96fb6 + + +```solidity +event CloseWithDeposit( + address indexed user, + address indexed lender, + bytes32 indexed loanId, + address closer, + address loanToken, + address collateralToken, + uint256 repayAmount, + uint256 collateralWithdrawAmount, + uint256 collateralToLoanRate, + uint256 currentMargin +); +``` + +### CloseWithSwap +topic0: 0x2ed7b29b4ca95cf3bb9a44f703872a66e6aa5e8f07b675fa9a5c124a1e5d7352 + + +```solidity +event CloseWithSwap( + address indexed user, + address indexed lender, + bytes32 indexed loanId, + address collateralToken, + address loanToken, + address closer, + uint256 positionCloseSize, + uint256 loanCloseAmount, + uint256 exitPrice, + uint256 currentLeverage +); +``` + +### Liquidate +topic0: 0x46fa03303782eb2f686515f6c0100f9a62dabe587b0d3f5a4fc0c822d6e532d3 + + +```solidity +event Liquidate( + address indexed user, + address indexed liquidator, + bytes32 indexed loanId, + address lender, + address loanToken, + address collateralToken, + uint256 repayAmount, + uint256 collateralWithdrawAmount, + uint256 collateralToLoanRate, + uint256 currentMargin +); +``` + +### Rollover + +```solidity +event Rollover( + address indexed user, + address indexed lender, + bytes32 indexed loanId, + uint256 principal, + uint256 collateral, + uint256 endTimestamp, + address rewardReceiver, + uint256 reward +); +``` + +### swapExcess + +```solidity +event swapExcess(bool shouldRefund, uint256 amount, uint256 amountInRbtc, uint256 threshold); +``` + diff --git a/foundry/docs/src/contracts/events/LoanMaintenanceEvents.sol/contract.LoanMaintenanceEvents.md b/foundry/docs/src/contracts/events/LoanMaintenanceEvents.sol/contract.LoanMaintenanceEvents.md new file mode 100644 index 000000000..e014b740e --- /dev/null +++ b/foundry/docs/src/contracts/events/LoanMaintenanceEvents.sol/contract.LoanMaintenanceEvents.md @@ -0,0 +1,18 @@ +# LoanMaintenanceEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/LoanMaintenanceEvents.sol) + +**Inherits:** +[ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the events for loan maintenance operations. + + +## Events +### DepositCollateral + +```solidity +event DepositCollateral(bytes32 indexed loanId, uint256 depositAmount, uint256 rate); +``` + diff --git a/foundry/docs/src/contracts/events/LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md b/foundry/docs/src/contracts/events/LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md new file mode 100644 index 000000000..d18c56f4c --- /dev/null +++ b/foundry/docs/src/contracts/events/LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md @@ -0,0 +1,64 @@ +# LoanOpeningsEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/LoanOpeningsEvents.sol) + +**Inherits:** +[ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the events for loan openings operations. + + +## Events +### Borrow +topic0: 0x7bd8cbb7ba34b33004f3deda0fd36c92fc0360acbd97843360037b467a538f90 + + +```solidity +event Borrow( + address indexed user, + address indexed lender, + bytes32 indexed loanId, + address loanToken, + address collateralToken, + uint256 newPrincipal, + uint256 newCollateral, + uint256 interestRate, + uint256 interestDuration, + uint256 collateralToLoanRate, + uint256 currentMargin +); +``` + +### Trade +topic0: 0xf640c1cfe1a912a0b0152b5a542e5c2403142eed75b06cde526cee54b1580e5c + + +```solidity +event Trade( + address indexed user, + address indexed lender, + bytes32 indexed loanId, + address collateralToken, + address loanToken, + uint256 positionSize, + uint256 borrowedAmount, + uint256 interestRate, + uint256 settlementDate, + uint256 entryPrice, + uint256 entryLeverage, + uint256 currentLeverage +); +``` + +### DelegatedManagerSet +topic0: 0x0eef4f90457a741c97d76fcf13fa231fefdcc7649bdb3cb49157c37111c98433 + + +```solidity +event DelegatedManagerSet(bytes32 indexed loanId, address indexed delegator, address indexed delegated, bool isActive); +``` + diff --git a/foundry/docs/src/contracts/events/LoanSettingsEvents.sol/contract.LoanSettingsEvents.md b/foundry/docs/src/contracts/events/LoanSettingsEvents.sol/contract.LoanSettingsEvents.md new file mode 100644 index 000000000..882b8e247 --- /dev/null +++ b/foundry/docs/src/contracts/events/LoanSettingsEvents.sol/contract.LoanSettingsEvents.md @@ -0,0 +1,55 @@ +# LoanSettingsEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/LoanSettingsEvents.sol) + +**Inherits:** +[ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the events for loan settings operations. + + +## Events +### LoanParamsSetup + +```solidity +event LoanParamsSetup( + bytes32 indexed id, + address owner, + address indexed loanToken, + address indexed collateralToken, + uint256 minInitialMargin, + uint256 maintenanceMargin, + uint256 maxLoanTerm +); +``` + +### LoanParamsIdSetup + +```solidity +event LoanParamsIdSetup(bytes32 indexed id, address indexed owner); +``` + +### LoanParamsDisabled + +```solidity +event LoanParamsDisabled( + bytes32 indexed id, + address owner, + address indexed loanToken, + address indexed collateralToken, + uint256 minInitialMargin, + uint256 maintenanceMargin, + uint256 maxLoanTerm +); +``` + +### LoanParamsIdDisabled + +```solidity +event LoanParamsIdDisabled(bytes32 indexed id, address indexed owner); +``` + diff --git a/foundry/docs/src/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md b/foundry/docs/src/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md new file mode 100644 index 000000000..f485bb4a4 --- /dev/null +++ b/foundry/docs/src/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md @@ -0,0 +1,15 @@ +# ModulesCommonEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/ModulesCommonEvents.sol) + +This contract contains the events which will be used by all modules + + +## Events +### ProtocolModuleContractReplaced + +```solidity +event ProtocolModuleContractReplaced( + address indexed prevModuleContractAddress, address indexed newModuleContractAddress, bytes32 indexed module +); +``` + diff --git a/foundry/docs/src/contracts/events/ProtocolSettingsEvents.sol/contract.ProtocolSettingsEvents.md b/foundry/docs/src/contracts/events/ProtocolSettingsEvents.sol/contract.ProtocolSettingsEvents.md new file mode 100644 index 000000000..152a4548d --- /dev/null +++ b/foundry/docs/src/contracts/events/ProtocolSettingsEvents.sol/contract.ProtocolSettingsEvents.md @@ -0,0 +1,245 @@ +# ProtocolSettingsEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/ProtocolSettingsEvents.sol) + +**Inherits:** +[ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the events for protocol settings operations. + + +## Events +### SetPriceFeedContract + +```solidity +event SetPriceFeedContract(address indexed sender, address oldValue, address newValue); +``` + +### SetSwapsImplContract + +```solidity +event SetSwapsImplContract(address indexed sender, address oldValue, address newValue); +``` + +### SetLoanPool + +```solidity +event SetLoanPool(address indexed sender, address indexed loanPool, address indexed underlying); +``` + +### SetSupportedTokens + +```solidity +event SetSupportedTokens(address indexed sender, address indexed token, bool isActive); +``` + +### SetLendingFeePercent + +```solidity +event SetLendingFeePercent(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetTradingFeePercent + +```solidity +event SetTradingFeePercent(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetBorrowingFeePercent + +```solidity +event SetBorrowingFeePercent(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetSwapExternalFeePercent + +```solidity +event SetSwapExternalFeePercent(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetAffiliateFeePercent + +```solidity +event SetAffiliateFeePercent(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetAffiliateTradingTokenFeePercent + +```solidity +event SetAffiliateTradingTokenFeePercent(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetLiquidationIncentivePercent + +```solidity +event SetLiquidationIncentivePercent(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetMaxSwapSize + +```solidity +event SetMaxSwapSize(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetFeesController + +```solidity +event SetFeesController(address indexed sender, address indexed oldController, address indexed newController); +``` + +### SetWrbtcToken + +```solidity +event SetWrbtcToken(address indexed sender, address indexed oldWethToken, address indexed newWethToken); +``` + +### SetSovrynSwapContractRegistryAddress + +```solidity +event SetSovrynSwapContractRegistryAddress( + address indexed sender, + address indexed oldSovrynSwapContractRegistryAddress, + address indexed newSovrynSwapContractRegistryAddress +); +``` + +### SetProtocolTokenAddress + +```solidity +event SetProtocolTokenAddress( + address indexed sender, address indexed oldProtocolToken, address indexed newProtocolToken +); +``` + +### WithdrawFees + +```solidity +event WithdrawFees( + address indexed sender, + address indexed token, + address indexed receiver, + uint256 lendingAmount, + uint256 tradingAmount, + uint256 borrowingAmount, + uint256 wRBTCConverted +); +``` + +### WithdrawLendingFees + +```solidity +event WithdrawLendingFees(address indexed sender, address indexed token, address indexed receiver, uint256 amount); +``` + +### WithdrawTradingFees + +```solidity +event WithdrawTradingFees(address indexed sender, address indexed token, address indexed receiver, uint256 amount); +``` + +### WithdrawBorrowingFees + +```solidity +event WithdrawBorrowingFees(address indexed sender, address indexed token, address indexed receiver, uint256 amount); +``` + +### SetRolloverBaseReward + +```solidity +event SetRolloverBaseReward(address indexed sender, uint256 oldValue, uint256 newValue); +``` + +### SetRebatePercent + +```solidity +event SetRebatePercent(address indexed sender, uint256 oldRebatePercent, uint256 newRebatePercent); +``` + +### SetSpecialRebates + +```solidity +event SetSpecialRebates( + address indexed sender, + address indexed sourceToken, + address indexed destToken, + uint256 oldSpecialRebatesPercent, + uint256 newSpecialRebatesPercent +); +``` + +### SetProtocolAddress + +```solidity +event SetProtocolAddress(address indexed sender, address indexed oldProtocol, address indexed newProtocol); +``` + +### SetMinReferralsToPayoutAffiliates + +```solidity +event SetMinReferralsToPayoutAffiliates(address indexed sender, uint256 oldMinReferrals, uint256 newMinReferrals); +``` + +### SetSOVTokenAddress + +```solidity +event SetSOVTokenAddress(address indexed sender, address indexed oldTokenAddress, address indexed newTokenAddress); +``` + +### SetLockedSOVAddress + +```solidity +event SetLockedSOVAddress(address indexed sender, address indexed oldAddress, address indexed newAddress); +``` + +### TogglePaused + +```solidity +event TogglePaused(address indexed sender, bool indexed oldFlag, bool indexed newFlag); +``` + +### SetTradingRebateRewardsBasisPoint + +```solidity +event SetTradingRebateRewardsBasisPoint(address indexed sender, uint256 oldBasisPoint, uint256 newBasisPoint); +``` + +### SetRolloverFlexFeePercent + +```solidity +event SetRolloverFlexFeePercent( + address indexed sender, uint256 oldRolloverFlexFeePercent, uint256 newRolloverFlexFeePercent +); +``` + +### SetDefaultPathConversion + +```solidity +event SetDefaultPathConversion( + address indexed sender, address indexed sourceTokenAddress, address indexed destTokenAddress, IERC20[] defaultPath +); +``` + +### RemoveDefaultPathConversion + +```solidity +event RemoveDefaultPathConversion( + address indexed sender, address indexed sourceTokenAddress, address indexed destTokenAddress, IERC20[] defaultPath +); +``` + +### SetAdmin + +```solidity +event SetAdmin(address indexed sender, address indexed oldAdmin, address indexed newAdmin); +``` + +### SetPauser + +```solidity +event SetPauser(address indexed sender, address indexed oldPauser, address indexed newPauser); +``` + diff --git a/foundry/docs/src/contracts/events/README.md b/foundry/docs/src/contracts/events/README.md new file mode 100644 index 000000000..f7b179f93 --- /dev/null +++ b/foundry/docs/src/contracts/events/README.md @@ -0,0 +1,12 @@ + + +# Contents +- [AffiliatesEvents](AffiliatesEvents.sol/contract.AffiliatesEvents.md) +- [FeesEvents](FeesEvents.sol/contract.FeesEvents.md) +- [LoanClosingsEvents](LoanClosingsEvents.sol/contract.LoanClosingsEvents.md) +- [LoanMaintenanceEvents](LoanMaintenanceEvents.sol/contract.LoanMaintenanceEvents.md) +- [LoanOpeningsEvents](LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md) +- [LoanSettingsEvents](LoanSettingsEvents.sol/contract.LoanSettingsEvents.md) +- [ModulesCommonEvents](ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) +- [ProtocolSettingsEvents](ProtocolSettingsEvents.sol/contract.ProtocolSettingsEvents.md) +- [SwapsEvents](SwapsEvents.sol/contract.SwapsEvents.md) diff --git a/foundry/docs/src/contracts/events/SwapsEvents.sol/contract.SwapsEvents.md b/foundry/docs/src/contracts/events/SwapsEvents.sol/contract.SwapsEvents.md new file mode 100644 index 000000000..22e15f0c6 --- /dev/null +++ b/foundry/docs/src/contracts/events/SwapsEvents.sol/contract.SwapsEvents.md @@ -0,0 +1,40 @@ +# SwapsEvents +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/events/SwapsEvents.sol) + +**Inherits:** +[ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the events for swap operations. + + +## Events +### LoanSwap + +```solidity +event LoanSwap( + bytes32 indexed loanId, + address indexed sourceToken, + address indexed destToken, + address borrower, + uint256 sourceAmount, + uint256 destAmount +); +``` + +### ExternalSwap + +```solidity +event ExternalSwap( + address indexed user, + address indexed sourceToken, + address indexed destToken, + uint256 sourceAmount, + uint256 destAmount +); +``` + diff --git a/foundry/docs/src/contracts/farm/ILiquidityMining.sol/interface.ILiquidityMining.md b/foundry/docs/src/contracts/farm/ILiquidityMining.sol/interface.ILiquidityMining.md new file mode 100644 index 000000000..22c282734 --- /dev/null +++ b/foundry/docs/src/contracts/farm/ILiquidityMining.sol/interface.ILiquidityMining.md @@ -0,0 +1,26 @@ +# ILiquidityMining +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/farm/ILiquidityMining.sol) + + +## Functions +### withdraw + + +```solidity +function withdraw(address _poolToken, uint256 _amount, address _user) external; +``` + +### onTokensDeposited + + +```solidity +function onTokensDeposited(address _user, uint256 _amount) external; +``` + +### getUserPoolTokenBalance + + +```solidity +function getUserPoolTokenBalance(address _poolToken, address _user) external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/farm/LiquidityMining.sol/contract.LiquidityMining.md b/foundry/docs/src/contracts/farm/LiquidityMining.sol/contract.LiquidityMining.md new file mode 100644 index 000000000..04a782f1a --- /dev/null +++ b/foundry/docs/src/contracts/farm/LiquidityMining.sol/contract.LiquidityMining.md @@ -0,0 +1,739 @@ +# LiquidityMining +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/farm/LiquidityMining.sol) + +**Inherits:** +[ILiquidityMining](/contracts/farm/ILiquidityMining.sol/interface.ILiquidityMining.md), [LiquidityMiningStorage](/contracts/farm/LiquidityMiningStorage.sol/contract.LiquidityMiningStorage.md) + + +## State Variables +### PRECISION + +```solidity +uint256 public constant PRECISION = 1e12; +``` + + +### BONUS_BLOCK_MULTIPLIER + +```solidity +uint256 public constant BONUS_BLOCK_MULTIPLIER = 10; +``` + + +### SECONDS_PER_BLOCK + +```solidity +uint256 public constant SECONDS_PER_BLOCK = 30; +``` + + +## Functions +### initialize + +Initialize mining. + + +```solidity +function initialize( + IERC20 _SOV, + uint256 _rewardTokensPerBlock, + uint256 _startDelayBlocks, + uint256 _numberOfBonusBlocks, + address _wrapper, + ILockedSOV _lockedSOV, + uint256 _unlockedImmediatelyPercent +) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`IERC20`|The SOV token.| +|`_rewardTokensPerBlock`|`uint256`|The number of reward tokens per block.| +|`_startDelayBlocks`|`uint256`|The number of blocks should be passed to start mining.| +|`_numberOfBonusBlocks`|`uint256`|The number of blocks when each block will be calculated as N blocks (BONUS_BLOCK_MULTIPLIER).| +|`_wrapper`|`address`|| +|`_lockedSOV`|`ILockedSOV`|The contract instance address of the lockedSOV vault. SOV rewards are not paid directly to liquidity providers. Instead they are deposited into a lockedSOV vault contract.| +|`_unlockedImmediatelyPercent`|`uint256`|The % which determines how much will be unlocked immediately.| + + +### setLockedSOV + +Sets lockedSOV contract. + +*Non-idempotent function. Must be called just once.* + + +```solidity +function setLockedSOV(ILockedSOV _lockedSOV) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_lockedSOV`|`ILockedSOV`|The contract instance address of the lockedSOV vault.| + + +### setUnlockedImmediatelyPercent + +Sets unlocked immediately percent. + +*10000 is 100%* + + +```solidity +function setUnlockedImmediatelyPercent(uint256 _unlockedImmediatelyPercent) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_unlockedImmediatelyPercent`|`uint256`|The % which determines how much will be unlocked immediately.| + + +### setPoolTokenUnlockedImmediatelyPercent + +Sets unlocked immediately percent overwrite for specific pool token. + +*10000 is 100%* + + +```solidity +function setPoolTokenUnlockedImmediatelyPercent(address _poolToken, uint256 _poolTokenUnlockedImmediatelyPercent) + external + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_poolTokenUnlockedImmediatelyPercent`|`uint256`|The % which determines how much will be unlocked immediately.| + + +### setWrapper + +sets wrapper proxy contract + +*can be set to zero address to remove wrapper* + + +```solidity +function setWrapper(address _wrapper) external onlyAuthorized; +``` + +### stopMining + +stops mining by setting end block + + +```solidity +function stopMining() external onlyAuthorized; +``` + +### transferSOV + +Transfers SOV tokens to given address. +Owner use this function to withdraw SOV from LM contract +into another account. + + +```solidity +function transferSOV(address _receiver, uint256 _amount) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|The address of the SOV receiver.| +|`_amount`|`uint256`|The amount to be transferred.| + + +### getMissedBalance + +Get the missed SOV balance of LM contract. + +*Do not transfer more SOV than available.* + +*The actual transfer.* + +*Event log.* + + +```solidity +function getMissedBalance() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The amount of SOV tokens according to totalUsersBalance in excess of actual SOV balance of the LM contract.| + + +### add + +adds a new lp to the pool. Can only be called by the owner or an admin + + +```solidity +function add(address _poolToken, uint96 _allocationPoint, bool _withUpdate) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_allocationPoint`|`uint96`|the allocation point (weight) for the given pool| +|`_withUpdate`|`bool`|the flag whether we need to update all pools| + + +### update + +updates the given pool's reward tokens allocation point + + +```solidity +function update(address _poolToken, uint96 _allocationPoint, bool _updateAllFlag) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_allocationPoint`|`uint96`|the allocation point (weight) for the given pool| +|`_updateAllFlag`|`bool`|the flag whether we need to update all pools| + + +### _updateToken + + +```solidity +function _updateToken(address _poolToken, uint96 _allocationPoint) internal; +``` + +### updateTokens + +updates the given pools' reward tokens allocation points + + +```solidity +function updateTokens(address[] calldata _poolTokens, uint96[] calldata _allocationPoints, bool _updateAllFlag) + external + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolTokens`|`address[]`|array of addresses of pool tokens| +|`_allocationPoints`|`uint96[]`|array of allocation points (weight) for the given pools| +|`_updateAllFlag`|`bool`|the flag whether we need to update all pools| + + +### _getPassedBlocksWithBonusMultiplier + +returns reward multiplier over the given _from to _to block + + +```solidity +function _getPassedBlocksWithBonusMultiplier(uint256 _from, uint256 _to) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_from`|`uint256`|the first block for a calculation| +|`_to`|`uint256`|the last block for a calculation| + + +### _getUserAccumulatedReward + + +```solidity +function _getUserAccumulatedReward(uint256 _poolId, address _user) internal view returns (uint256); +``` + +### getUserAccumulatedReward + +returns accumulated reward + + +```solidity +function getUserAccumulatedReward(address _poolToken, address _user) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_user`|`address`|the user address| + + +### getEstimatedReward + +returns estimated reward + + +```solidity +function getEstimatedReward(address _poolToken, uint256 _amount, uint256 _duration) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_amount`|`uint256`|the amount of tokens to be deposited| +|`_duration`|`uint256`|the duration of liquidity providing in seconds| + + +### updateAllPools + +Updates reward variables for all pools. + +*Be careful of gas spending!* + + +```solidity +function updateAllPools() public; +``` + +### updatePool + +Updates reward variables of the given pool to be up-to-date + + +```solidity +function updatePool(address _poolToken) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| + + +### _updatePool + + +```solidity +function _updatePool(uint256 _poolId) internal; +``` + +### _getPoolAccumulatedReward + + +```solidity +function _getPoolAccumulatedReward(PoolInfo storage _pool) internal view returns (uint256, uint256); +``` + +### _getPoolAccumulatedReward + + +```solidity +function _getPoolAccumulatedReward( + PoolInfo storage _pool, + uint256 _additionalAmount, + uint256 _startBlock, + uint256 _endBlock +) internal view returns (uint256, uint256); +``` + +### deposit + +deposits pool tokens + + +```solidity +function deposit(address _poolToken, uint256 _amount, address _user) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_amount`|`uint256`|the amount of pool tokens| +|`_user`|`address`|the address of user, tokens will be deposited to it or to msg.sender| + + +### onTokensDeposited + +if the lending pools directly mint/transfer tokens to this address, process it like a user deposit + +*only callable by the pool which issues the tokens* + + +```solidity +function onTokensDeposited(address _user, uint256 _amount) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|the user address| +|`_amount`|`uint256`|the minted amount| + + +### _deposit + +internal function for depositing pool tokens + + +```solidity +function _deposit(address _poolToken, uint256 _amount, address _user, bool alreadyTransferred) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_amount`|`uint256`|the amount of pool tokens| +|`_user`|`address`|the address of user, tokens will be deposited to it| +|`alreadyTransferred`|`bool`|true if the pool tokens have already been transferred| + + +### claimReward + +transfers reward tokens + + +```solidity +function claimReward(address _poolToken, address _user) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_user`|`address`|the address of user to claim reward from (can be passed only by wrapper contract)| + + +### _claimReward + + +```solidity +function _claimReward(uint256 _poolId, address _userAddress, bool _isStakingTokens) internal; +``` + +### claimRewardFromAllPools + +transfers reward tokens from all pools + + +```solidity +function claimRewardFromAllPools(address _user) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|the address of user to claim reward from (can be passed only by wrapper contract)| + + +### withdraw + +withdraws pool tokens and transfers reward tokens + + +```solidity +function withdraw(address _poolToken, uint256 _amount, address _user) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_amount`|`uint256`|the amount of pool tokens| +|`_user`|`address`|the user address will be used to process a withdrawal (can be passed only by wrapper contract)| + + +### _getUserAddress + + +```solidity +function _getUserAddress(address _user) internal view returns (address); +``` + +### _updateReward + + +```solidity +function _updateReward(PoolInfo storage pool, UserInfo storage user) internal; +``` + +### _updateRewardDebt + + +```solidity +function _updateRewardDebt(PoolInfo storage pool, UserInfo storage user) internal; +``` + +### _transferReward + +Send reward in SOV to the lockedSOV vault. + + +```solidity +function _transferReward( + address _poolToken, + UserInfo storage _user, + address _userAddress, + bool _isStakingTokens, + bool _isCheckingBalance +) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|| +|`_user`|`UserInfo`|The user info, to get its reward share.| +|`_userAddress`|`address`|The address of the user, to send SOV in its behalf.| +|`_isStakingTokens`|`bool`|The flag whether we need to stake tokens| +|`_isCheckingBalance`|`bool`|The flag whether we need to throw error or don't process reward if SOV balance isn't enough| + + +### emergencyWithdraw + +withdraws pool tokens without transferring reward tokens + +*get unlock immediate percent of the pool token.* + +*Transfer if enough SOV balance on this LM contract.* + +*If calculatedUnlockedImmediatelyPercent is 100%, transfer the reward to the LP (user). +else, deposit it into lockedSOV vault contract, but first +SOV deposit must be approved to move the SOV tokens +from this LM contract into the lockedSOV vault.* + +*Event log.* + +*EMERGENCY ONLY* + + +```solidity +function emergencyWithdraw(address _poolToken) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| + + +### getPoolId + +returns pool id + + +```solidity +function getPoolId(address _poolToken) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| + + +### _getPoolId + + +```solidity +function _getPoolId(address _poolToken) internal view returns (uint256); +``` + +### getPoolLength + +returns count of pool tokens + + +```solidity +function getPoolLength() external view returns (uint256); +``` + +### getPoolInfoList + +returns list of pool token's info + + +```solidity +function getPoolInfoList() external view returns (PoolInfo[] memory); +``` + +### getPoolInfo + +returns pool info for the given token + + +```solidity +function getPoolInfo(address _poolToken) external view returns (PoolInfo memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| + + +### getUserBalanceList + +returns list of [amount, accumulatedReward] for the given user for each pool token + + +```solidity +function getUserBalanceList(address _user) external view returns (uint256[2][] memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|the address of the user| + + +### getUserInfo + +returns UserInfo for the given pool and user + + +```solidity +function getUserInfo(address _poolToken, address _user) public view returns (UserInfo memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_user`|`address`|the address of the user| + + +### getUserInfoList + +returns list of UserInfo for the given user for each pool token + + +```solidity +function getUserInfoList(address _user) external view returns (UserInfo[] memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|the address of the user| + + +### getUserAccumulatedRewardList + +returns accumulated reward for the given user for each pool token + + +```solidity +function getUserAccumulatedRewardList(address _user) external view returns (uint256[] memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|the address of the user| + + +### getUserPoolTokenBalance + +returns the pool token balance a user has on the contract + + +```solidity +function getUserPoolTokenBalance(address _poolToken, address _user) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_poolToken`|`address`|the address of pool token| +|`_user`|`address`|the address of the user| + + +### getUserAccumulatedRewardToBePaidLiquid + +returns the accumulated liquid reward for the given user for each pool token + + +```solidity +function getUserAccumulatedRewardToBePaidLiquid(address _user) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|the address of the user| + + +### getUserAccumulatedRewardToBeVested + +returns the accumulated vested reward for the given user for each pool token + + +```solidity +function getUserAccumulatedRewardToBeVested(address _user) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|the address of the user| + + +### calcUnlockedImmediatelyPercent + +*calculate the unlocked immediate percentage of specific pool token +use the poolTokensUnlockedImmediatelyPercent by default, if it is not set, then use the unlockedImmediatelyPercent* + + +```solidity +function calcUnlockedImmediatelyPercent(address _poolToken) public view returns (uint256); +``` + +## Events +### SOVTransferred + +```solidity +event SOVTransferred(address indexed receiver, uint256 amount); +``` + +### PoolTokenAdded + +```solidity +event PoolTokenAdded(address indexed user, address indexed poolToken, uint256 allocationPoint); +``` + +### PoolTokenUpdated + +```solidity +event PoolTokenUpdated( + address indexed user, address indexed poolToken, uint256 newAllocationPoint, uint256 oldAllocationPoint +); +``` + +### Deposit + +```solidity +event Deposit(address indexed user, address indexed poolToken, uint256 amount); +``` + +### RewardClaimed + +```solidity +event RewardClaimed(address indexed user, address indexed poolToken, uint256 amount); +``` + +### Withdraw + +```solidity +event Withdraw(address indexed user, address indexed poolToken, uint256 amount); +``` + +### EmergencyWithdraw + +```solidity +event EmergencyWithdraw(address indexed user, address indexed poolToken, uint256 amount, uint256 accumulatedReward); +``` + diff --git a/foundry/docs/src/contracts/farm/LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md b/foundry/docs/src/contracts/farm/LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md new file mode 100644 index 000000000..b9169a526 --- /dev/null +++ b/foundry/docs/src/contracts/farm/LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md @@ -0,0 +1,52 @@ +# LiquidityMiningConfigToken +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/farm/LiquidityMiningConfigToken.sol) + +**Inherits:** +[IERC20_](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md) + +*We need this token for having a flexibility with LiquidityMining configuration* + + +## Functions +### totalSupply + + +```solidity +function totalSupply() external view returns (uint256); +``` + +### balanceOf + + +```solidity +function balanceOf(address account) external view returns (uint256); +``` + +### transfer + + +```solidity +function transfer(address recipient, uint256 amount) external returns (bool); +``` + +### allowance + + +```solidity +function allowance(address owner, address spender) external view returns (uint256); +``` + +### approve + + +```solidity +function approve(address spender, uint256 amount) external returns (bool); +``` + +### transferFrom + + +```solidity +function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); +``` + diff --git a/foundry/docs/src/contracts/farm/LiquidityMiningProxy.sol/contract.LiquidityMiningProxy.md b/foundry/docs/src/contracts/farm/LiquidityMiningProxy.sol/contract.LiquidityMiningProxy.md new file mode 100644 index 000000000..e3ed62a38 --- /dev/null +++ b/foundry/docs/src/contracts/farm/LiquidityMiningProxy.sol/contract.LiquidityMiningProxy.md @@ -0,0 +1,9 @@ +# LiquidityMiningProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/farm/LiquidityMiningProxy.sol) + +**Inherits:** +[LiquidityMiningStorage](/contracts/farm/LiquidityMiningStorage.sol/contract.LiquidityMiningStorage.md), [UpgradableProxy](/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + +*LiquidityMining contract should be upgradable, use UpgradableProxy* + + diff --git a/foundry/docs/src/contracts/farm/LiquidityMiningStorage.sol/contract.LiquidityMiningStorage.md b/foundry/docs/src/contracts/farm/LiquidityMiningStorage.sol/contract.LiquidityMiningStorage.md new file mode 100644 index 000000000..dfaa28cc0 --- /dev/null +++ b/foundry/docs/src/contracts/farm/LiquidityMiningStorage.sol/contract.LiquidityMiningStorage.md @@ -0,0 +1,136 @@ +# LiquidityMiningStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/farm/LiquidityMiningStorage.sol) + +**Inherits:** +[AdminRole](/contracts/utils/AdminRole.sol/contract.AdminRole.md) + + +## State Variables +### rewardTokensPerBlock + +```solidity +uint256 public rewardTokensPerBlock; +``` + + +### startBlock + +```solidity +uint256 public startBlock; +``` + + +### bonusEndBlock + +```solidity +uint256 public bonusEndBlock; +``` + + +### endBlock + +```solidity +uint256 public endBlock; +``` + + +### wrapper + +```solidity +address public wrapper; +``` + + +### poolInfoList + +```solidity +PoolInfo[] public poolInfoList; +``` + + +### poolIdList + +```solidity +mapping(address => uint256) poolIdList; +``` + + +### totalAllocationPoint + +```solidity +uint256 public totalAllocationPoint; +``` + + +### userInfoMap + +```solidity +mapping(uint256 => mapping(address => UserInfo)) public userInfoMap; +``` + + +### totalUsersBalance + +```solidity +uint256 public totalUsersBalance; +``` + + +### SOV +*The SOV token* + + +```solidity +IERC20 public SOV; +``` + + +### lockedSOV +*The locked vault contract to deposit LP's rewards into.* + + +```solidity +ILockedSOV public lockedSOV; +``` + + +### unlockedImmediatelyPercent +*10000 is 100%* + + +```solidity +uint256 public unlockedImmediatelyPercent; +``` + + +### poolTokensUnlockedImmediatelyPercent +*overwrite the unlockedImmediatelyPercent for specific token.* + + +```solidity +mapping(address => uint256) public poolTokensUnlockedImmediatelyPercent; +``` + + +## Structs +### UserInfo + +```solidity +struct UserInfo { + uint256 amount; + uint256 rewardDebt; + uint256 accumulatedReward; +} +``` + +### PoolInfo + +```solidity +struct PoolInfo { + IERC20 poolToken; + uint96 allocationPoint; + uint256 lastRewardBlock; + uint256 accumulatedRewardPerShare; +} +``` + diff --git a/foundry/docs/src/contracts/farm/README.md b/foundry/docs/src/contracts/farm/README.md new file mode 100644 index 000000000..15e78048f --- /dev/null +++ b/foundry/docs/src/contracts/farm/README.md @@ -0,0 +1,8 @@ + + +# Contents +- [ILiquidityMining](ILiquidityMining.sol/interface.ILiquidityMining.md) +- [LiquidityMining](LiquidityMining.sol/contract.LiquidityMining.md) +- [LiquidityMiningConfigToken](LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md) +- [LiquidityMiningProxy](LiquidityMiningProxy.sol/contract.LiquidityMiningProxy.md) +- [LiquidityMiningStorage](LiquidityMiningStorage.sol/contract.LiquidityMiningStorage.md) diff --git a/foundry/docs/src/contracts/feeds/BProPriceFeed.sol/contract.BProPriceFeed.md b/foundry/docs/src/contracts/feeds/BProPriceFeed.sol/contract.BProPriceFeed.md new file mode 100644 index 000000000..712a52240 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/BProPriceFeed.sol/contract.BProPriceFeed.md @@ -0,0 +1,86 @@ +# BProPriceFeed +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/BProPriceFeed.sol) + +**Inherits:** +[IPriceFeedsExt](/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + + +## State Variables +### mocStateAddress + +```solidity +address public mocStateAddress; +``` + + +## Functions +### constructor + +Initializes a new MoC state. + + +```solidity +constructor(address _mocStateAddress) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_mocStateAddress`|`address`|MoC state address| + + +### latestAnswer + +Get BPro USD price. + + +```solidity +function latestAnswer() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|the BPro USD Price [using mocPrecision]| + + +### latestTimestamp + +Supposed to get the MoC update time, but instead +get the current timestamp. + + +```solidity +function latestTimestamp() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|Always returns current block's timestamp.| + + +### setMoCStateAddress + +MoC state doesn't return update timestamp. + +Set MoC state address. + + +```solidity +function setMoCStateAddress(address _mocStateAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_mocStateAddress`|`address`|The MoC state address.| + + +## Events +### SetMoCStateAddress + +```solidity +event SetMoCStateAddress(address indexed mocStateAddress, address changerAddress); +``` + diff --git a/foundry/docs/src/contracts/feeds/DummyFallbackOracle.sol/contract.DummyFallbackOracle.md b/foundry/docs/src/contracts/feeds/DummyFallbackOracle.sol/contract.DummyFallbackOracle.md new file mode 100644 index 000000000..c3e3d5cd0 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/DummyFallbackOracle.sol/contract.DummyFallbackOracle.md @@ -0,0 +1,33 @@ +# DummyFallbackOracle +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/DummyFallbackOracle.sol) + +**Inherits:** +[IExternalPriceFeed](/contracts/feeds/DummyFallbackOracle.sol/interface.IExternalPriceFeed.md) + +*Dummy Oracle contract that supports MoC medianizer interface (latestAnswer) which will always return (0, false) value* + + +## Functions +### constructor + + +```solidity +constructor() public; +``` + +### latestAnswer + +*dummy function to support MoC medianizer* + + +```solidity +function latestAnswer() external view returns (uint256, bool); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|priceValue which is hardcoded to 0| +|``|`bool`|flag that indicate if the price is valid or not, hardcoded to false| + + diff --git a/foundry/docs/src/contracts/feeds/DummyFallbackOracle.sol/interface.IExternalPriceFeed.md b/foundry/docs/src/contracts/feeds/DummyFallbackOracle.sol/interface.IExternalPriceFeed.md new file mode 100644 index 000000000..5c15eafc3 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/DummyFallbackOracle.sol/interface.IExternalPriceFeed.md @@ -0,0 +1,21 @@ +# IExternalPriceFeed +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/DummyFallbackOracle.sol) + + +## Functions +### latestAnswer + +*The returned price should be 18-decimal value* + + +```solidity +function latestAnswer() external view returns (uint256, bool); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|the prive value and a boolean stating if the query was successful| +|``|`bool`|| + + diff --git a/foundry/docs/src/contracts/feeds/IMoCState.sol/interface.IMoCState.md b/foundry/docs/src/contracts/feeds/IMoCState.sol/interface.IMoCState.md new file mode 100644 index 000000000..1b45d132a --- /dev/null +++ b/foundry/docs/src/contracts/feeds/IMoCState.sol/interface.IMoCState.md @@ -0,0 +1,82 @@ +# IMoCState +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/IMoCState.sol) + + +## Functions +### getRbtcInBitPro + + +```solidity +function getRbtcInBitPro(bytes32 bucket) external view returns (uint256); +``` + +### globalMaxBPro + + +```solidity +function globalMaxBPro() external view returns (uint256); +``` + +### maxBPro + + +```solidity +function maxBPro(bytes32 bucket) external view returns (uint256); +``` + +### absoluteMaxBPro + + +```solidity +function absoluteMaxBPro() external view returns (uint256); +``` + +### maxBProWithDiscount + + +```solidity +function maxBProWithDiscount() external view returns (uint256); +``` + +### bproTecPrice + + +```solidity +function bproTecPrice() external view returns (uint256); +``` + +### bucketBProTecPrice + + +```solidity +function bucketBProTecPrice(bytes32 bucket) external view returns (uint256); +``` + +### bproDiscountPrice + + +```solidity +function bproDiscountPrice() external view returns (uint256); +``` + +### bproUsdPrice + + +```solidity +function bproUsdPrice() external view returns (uint256); +``` + +### bproSpotDiscountRate + + +```solidity +function bproSpotDiscountRate() external view returns (uint256); +``` + +### getBucketNBPro + + +```solidity +function getBucketNBPro(bytes32 bucket) external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/feeds/IPriceFeeds.sol/interface.IPriceFeeds.md b/foundry/docs/src/contracts/feeds/IPriceFeeds.sol/interface.IPriceFeeds.md new file mode 100644 index 000000000..aa7c83249 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/IPriceFeeds.sol/interface.IPriceFeeds.md @@ -0,0 +1,107 @@ +# IPriceFeeds +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/IPriceFeeds.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### queryRate + + +```solidity +function queryRate(address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); +``` + +### queryPrecision + + +```solidity +function queryPrecision(address sourceToken, address destToken) external view returns (uint256 precision); +``` + +### queryReturn + + +```solidity +function queryReturn(address sourceToken, address destToken, uint256 sourceAmount) + external + view + returns (uint256 destAmount); +``` + +### checkPriceDisagreement + + +```solidity +function checkPriceDisagreement( + address sourceToken, + address destToken, + uint256 sourceAmount, + uint256 destAmount, + uint256 maxSlippage +) external view returns (uint256 sourceToDestSwapRate); +``` + +### amountInEth + + +```solidity +function amountInEth(address Token, uint256 amount) external view returns (uint256 ethAmount); +``` + +### getMaxDrawdown + + +```solidity +function getMaxDrawdown( + address loanToken, + address collateralToken, + uint256 loanAmount, + uint256 collateralAmount, + uint256 maintenanceMargin +) external view returns (uint256); +``` + +### getCurrentMarginAndCollateralSize + + +```solidity +function getCurrentMarginAndCollateralSize( + address loanToken, + address collateralToken, + uint256 loanAmount, + uint256 collateralAmount +) external view returns (uint256 currentMargin, uint256 collateralInEthAmount); +``` + +### getCurrentMargin + + +```solidity +function getCurrentMargin(address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) + external + view + returns (uint256 currentMargin, uint256 collateralToLoanRate); +``` + +### shouldLiquidate + + +```solidity +function shouldLiquidate( + address loanToken, + address collateralToken, + uint256 loanAmount, + uint256 collateralAmount, + uint256 maintenanceMargin +) external view returns (bool); +``` + +### getFastGasPrice + + +```solidity +function getFastGasPrice(address payToken) external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/feeds/IRSKOracle.sol/interface.IRSKOracle.md b/foundry/docs/src/contracts/feeds/IRSKOracle.sol/interface.IRSKOracle.md new file mode 100644 index 000000000..96031f690 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/IRSKOracle.sol/interface.IRSKOracle.md @@ -0,0 +1,33 @@ +# IRSKOracle +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/IRSKOracle.sol) + + +## Functions +### updatePrice + + +```solidity +function updatePrice(uint256 price, uint256 timestamp) external; +``` + +### getPricing + + +```solidity +function getPricing() external view returns (uint256, uint256); +``` + +### setOracleAddress + + +```solidity +function setOracleAddress(address addr) external; +``` + +### clearOracleAddress + + +```solidity +function clearOracleAddress() external; +``` + diff --git a/foundry/docs/src/contracts/feeds/IV1PoolOracle.sol/interface.ILiquidityPoolV1Converter.md b/foundry/docs/src/contracts/feeds/IV1PoolOracle.sol/interface.ILiquidityPoolV1Converter.md new file mode 100644 index 000000000..9110025dc --- /dev/null +++ b/foundry/docs/src/contracts/feeds/IV1PoolOracle.sol/interface.ILiquidityPoolV1Converter.md @@ -0,0 +1,12 @@ +# ILiquidityPoolV1Converter +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/IV1PoolOracle.sol) + + +## Functions +### reserveTokens + + +```solidity +function reserveTokens(uint256 index) external view returns (address); +``` + diff --git a/foundry/docs/src/contracts/feeds/IV1PoolOracle.sol/interface.IV1PoolOracle.md b/foundry/docs/src/contracts/feeds/IV1PoolOracle.sol/interface.IV1PoolOracle.md new file mode 100644 index 000000000..a8512ccea --- /dev/null +++ b/foundry/docs/src/contracts/feeds/IV1PoolOracle.sol/interface.IV1PoolOracle.md @@ -0,0 +1,36 @@ +# IV1PoolOracle +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/IV1PoolOracle.sol) + + +## Functions +### read + + +```solidity +function read(uint256 price, uint256 timestamp) + external + view + returns (uint256, uint256, uint256, uint256, uint256, uint256); +``` + +### latestAnswer + + +```solidity +function latestAnswer() external view returns (uint256); +``` + +### liquidityPool + + +```solidity +function liquidityPool() external view returns (address); +``` + +### latestPrice + + +```solidity +function latestPrice(address _baseToken) external view returns (uint256 answer); +``` + diff --git a/foundry/docs/src/contracts/feeds/PriceFeedRSKOracle.sol/contract.PriceFeedRSKOracle.md b/foundry/docs/src/contracts/feeds/PriceFeedRSKOracle.sol/contract.PriceFeedRSKOracle.md new file mode 100644 index 000000000..76656c6bd --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeedRSKOracle.sol/contract.PriceFeedRSKOracle.md @@ -0,0 +1,87 @@ +# PriceFeedRSKOracle +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeedRSKOracle.sol) + +**Inherits:** +[IPriceFeedsExt](/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +The Price Feed RSK Oracle contract. +This contract implements RSK Oracle query functionality, +getting the price and the last timestamp from an external oracle contract. + + +## State Variables +### rskOracleAddress + +```solidity +address public rskOracleAddress; +``` + + +## Functions +### constructor + +Initialize a new RSK Oracle. + + +```solidity +constructor(address _rskOracleAddress) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_rskOracleAddress`|`address`|The RSK Oracle address.| + + +### latestAnswer + +Get the oracle price. + + +```solidity +function latestAnswer() external view returns (uint256 _price); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_price`|`uint256`|The price from Oracle.| + + +### latestTimestamp + +Get the las time oracle updated the price. + + +```solidity +function latestTimestamp() external view returns (uint256 _timestamp); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_timestamp`|`uint256`|The latest time.| + + +### setRSKOracleAddress + +Set the RSK Oracle address. + + +```solidity +function setRSKOracleAddress(address _rskOracleAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_rskOracleAddress`|`address`|The RSK Oracle address.| + + +## Events +### SetRSKOracleAddress + +```solidity +event SetRSKOracleAddress(address indexed rskOracleAddress, address changerAddress); +``` + diff --git a/foundry/docs/src/contracts/feeds/PriceFeedV1PoolOracle.sol/contract.PriceFeedV1PoolOracle.md b/foundry/docs/src/contracts/feeds/PriceFeedV1PoolOracle.sol/contract.PriceFeedV1PoolOracle.md new file mode 100644 index 000000000..fb50be50b --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeedV1PoolOracle.sol/contract.PriceFeedV1PoolOracle.md @@ -0,0 +1,168 @@ +# PriceFeedV1PoolOracle +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeedV1PoolOracle.sol) + +**Inherits:** +[IPriceFeedsExt](/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +The Price Feed V1 Pool Oracle contract. +This contract implements V1 Pool Oracle query functionality, +getting the price from v1 pool oracle. + + +## State Variables +### v1PoolOracleAddress + +```solidity +address public v1PoolOracleAddress; +``` + + +### wRBTCAddress + +```solidity +address public wRBTCAddress; +``` + + +### docAddress + +```solidity +address public docAddress; +``` + + +### baseCurrency + +```solidity +address public baseCurrency; +``` + + +## Functions +### constructor + +Initialize a new V1 Pool Oracle. + + +```solidity +constructor(address _v1PoolOracleAddress, address _wRBTCAddress, address _docAddress, address _baseCurrency) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_v1PoolOracleAddress`|`address`|The V1 Pool Oracle address.| +|`_wRBTCAddress`|`address`|The wrbtc token address.| +|`_docAddress`|`address`|The doc token address.| +|`_baseCurrency`|`address`|| + + +### latestAnswer + +Get the oracle price. + + +```solidity +function latestAnswer() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The price from Oracle.| + + +### _convertAnswerToUsd + + +```solidity +function _convertAnswerToUsd(uint256 _valueInBTC) private view returns (uint256); +``` + +### setV1PoolOracleAddress + +Need to multiply by query precision (doc's precision) and divide by 1*10^18 (Because the based price in v1 pool is using 18 decimals) + +Set the V1 Pool Oracle address. + + +```solidity +function setV1PoolOracleAddress(address _v1PoolOracleAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_v1PoolOracleAddress`|`address`|The V1 Pool Oracle address.| + + +### setRBTCAddress + +Set the rBtc address. V1 pool based price is BTC, so need to convert the value from v1 pool to USD. That's why we need to get the price of the rBtc + + +```solidity +function setRBTCAddress(address _wRBTCAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_wRBTCAddress`|`address`|The rBTC address| + + +### setDOCAddress + +Set the DoC address. V1 pool based price is BTC, so need to convert the value from v1 pool to USD. That's why we need to get the price of the DoC + + +```solidity +function setDOCAddress(address _docAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_docAddress`|`address`|The DoC address| + + +### setBaseCurrency + +Set the base currency address. That's the reserve address which is not WRBTC + + +```solidity +function setBaseCurrency(address _baseCurrency) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_baseCurrency`|`address`|The base currency address| + + +## Events +### SetV1PoolOracleAddress + +```solidity +event SetV1PoolOracleAddress(address indexed v1PoolOracleAddress, address changerAddress); +``` + +### SetWRBTCAddress + +```solidity +event SetWRBTCAddress(address indexed wRBTCAddress, address changerAddress); +``` + +### SetDOCAddress + +```solidity +event SetDOCAddress(address indexed docAddress, address changerAddress); +``` + +### SetBaseCurrency + +```solidity +event SetBaseCurrency(address indexed baseCurrency, address changerAddress); +``` + diff --git a/foundry/docs/src/contracts/feeds/PriceFeeds.sol/contract.PriceFeeds.md b/foundry/docs/src/contracts/feeds/PriceFeeds.sol/contract.PriceFeeds.md new file mode 100644 index 000000000..34b143e7a --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeeds.sol/contract.PriceFeeds.md @@ -0,0 +1,458 @@ +# PriceFeeds +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeeds.sol) + +**Inherits:** +[Constants](/contracts/feeds/PriceFeedsConstants.sol/contract.Constants.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract queries the price feeds contracts where +oracles updates token prices computing relative token prices. +And besides it includes some calculations about loans such as +drawdown, margin and collateral. + + +## State Variables +### pricesFeeds +Mapping of PriceFeedsExt instances. +token => pricefeed + + +```solidity +mapping(address => IPriceFeedsExt) public pricesFeeds; +``` + + +### decimals +Decimals of supported tokens. + + +```solidity +mapping(address => uint256) public decimals; +``` + + +### protocolTokenEthPrice +Value on rBTC weis for the protocol token. + + +```solidity +uint256 public protocolTokenEthPrice = 0.0002 ether; +``` + + +### globalPricingPaused +Flag to pause pricings. + + +```solidity +bool public globalPricingPaused = false; +``` + + +## Functions +### constructor + +Contract deployment requires 3 parameters. + + +```solidity +constructor(address _wrbtcTokenAddress, address _protocolTokenAddress, address _baseTokenAddress) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_wrbtcTokenAddress`|`address`|The address of the wrapped wrBTC token.| +|`_protocolTokenAddress`|`address`|The address of the protocol token.| +|`_baseTokenAddress`|`address`|The address of the base token.| + + +### queryRate + +Set decimals for this token. + +Calculate the price ratio between two tokens. + +*Public wrapper for _queryRate internal function.* + + +```solidity +function queryRate(address sourceToken, address destToken) public view returns (uint256 rate, uint256 precision); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`rate`|`uint256`|The price ratio source/dest.| +|`precision`|`uint256`|The ratio precision.| + + +### queryPrecision + +Calculate the relative precision between two tokens. + +*Public wrapper for _getDecimalPrecision internal function.* + + +```solidity +function queryPrecision(address sourceToken, address destToken) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The precision ratio source/dest.| + + +### queryReturn + +Price conversor: Calculate the price of an amount of source +tokens in destiny token units. + +*NOTE: This function returns 0 during a pause, rather than a revert. +Ensure calling contracts handle correctly.* + + +```solidity +function queryReturn(address sourceToken, address destToken, uint256 sourceAmount) + public + view + returns (uint256 destAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| +|`sourceAmount`|`uint256`|The amount of the source tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`destAmount`|`uint256`|The amount of destiny tokens equivalent in price to the amount of source tokens.| + + +### checkPriceDisagreement + +Calculate the swap rate between two tokens. +Regarding slippage, there is a hardcoded slippage limit of 5%, enforced +by this function for all borrowing, lending and margin trading +originated swaps performed in the Sovryn exchange. +This means all operations in the Sovryn exchange are subject to losing +up to 5% from the internal swap performed. + + +```solidity +function checkPriceDisagreement( + address sourceToken, + address destToken, + uint256 sourceAmount, + uint256 destAmount, + uint256 maxSlippage +) public view returns (uint256 sourceToDestSwapRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| +|`sourceAmount`|`uint256`|The amount of source tokens.| +|`destAmount`|`uint256`|The amount of destiny tokens.| +|`maxSlippage`|`uint256`|The maximum slippage limit.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToDestSwapRate`|`uint256`|The swap rate between tokens.| + + +### amountInEth + +Calculate the rBTC amount equivalent to a given token amount. +Native coin on RSK is rBTC. This code comes from Ethereum applications, +so Eth refers to 10**18 weis of native coin, i.e.: 1 rBTC. + + +```solidity +function amountInEth(address tokenAddress, uint256 amount) public view returns (uint256 ethAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokenAddress`|`address`|The address of the token to calculate price.| +|`amount`|`uint256`|The amount of tokens to calculate price.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`ethAmount`|`uint256`|The amount of rBTC equivalent.| + + +### getMaxDrawdown + +Token is wrBTC, amount in rBTC is the same. + +Calculate the maximum drawdown of a loan. +A drawdown is commonly defined as the decline from a high peak to a +pullback low of a specific investment or equity in an account. +Drawdown magnitude refers to the amount of value that a user loses +during the drawdown period. + + +```solidity +function getMaxDrawdown( + address loanToken, + address collateralToken, + uint256 loanAmount, + uint256 collateralAmount, + uint256 margin +) public view returns (uint256 maxDrawdown); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The address of the loan token.| +|`collateralToken`|`address`|The address of the collateral token.| +|`loanAmount`|`uint256`|The amount of the loan.| +|`collateralAmount`|`uint256`|The amount of the collateral.| +|`margin`|`uint256`|The relation between the position size and the loan. margin = (total position size - loan) / loan| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`maxDrawdown`|`uint256`|The maximum drawdown.| + + +### getCurrentMarginAndCollateralSize + +Calculate the margin and the collateral on rBTC. + + +```solidity +function getCurrentMarginAndCollateralSize( + address loanToken, + address collateralToken, + uint256 loanAmount, + uint256 collateralAmount +) public view returns (uint256 currentMargin, uint256 collateralInEthAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The address of the loan token.| +|`collateralToken`|`address`|The address of the collateral token.| +|`loanAmount`|`uint256`|The amount of the loan.| +|`collateralAmount`|`uint256`|The amount of the collateral.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`currentMargin`|`uint256`|The margin of the loan.| +|`collateralInEthAmount`|`uint256`|The amount of collateral on rBTC.| + + +### getCurrentMargin + +Calculate the margin of a loan. + +*current margin = (total position size - loan) / loan +The collateral amount passed as parameter equals the total position size.* + + +```solidity +function getCurrentMargin(address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) + public + view + returns (uint256 currentMargin, uint256 collateralToLoanRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The address of the loan token.| +|`collateralToken`|`address`|The address of the collateral token.| +|`loanAmount`|`uint256`|The amount of the loan.| +|`collateralAmount`|`uint256`|The amount of the collateral.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`currentMargin`|`uint256`|The margin of the loan.| +|`collateralToLoanRate`|`uint256`|The price ratio between collateral and loan tokens.| + + +### shouldLiquidate + +Get assessment about liquidating a loan. + + +```solidity +function shouldLiquidate( + address loanToken, + address collateralToken, + uint256 loanAmount, + uint256 collateralAmount, + uint256 maintenanceMargin +) public view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The address of the loan token.| +|`collateralToken`|`address`|The address of the collateral token.| +|`loanAmount`|`uint256`|The amount of the loan.| +|`collateralAmount`|`uint256`|The amount of the collateral.| +|`maintenanceMargin`|`uint256`|The minimum margin before liquidation.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|True/false to liquidate the loan.| + + +### setProtocolTokenEthPrice + +Set new value for protocolTokenEthPrice + + +```solidity +function setProtocolTokenEthPrice(uint256 newPrice) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newPrice`|`uint256`|The new value for protocolTokenEthPrice| + + +### setPriceFeed + +Populate pricesFeeds mapping w/ values from feeds[] + + +```solidity +function setPriceFeed(address[] calldata tokens, IPriceFeedsExt[] calldata feeds) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokens`|`address[]`|The array of tokens to loop and get addresses.| +|`feeds`|`IPriceFeedsExt[]`|The array of contract instances for every token.| + + +### setDecimals + +Populate decimals mapping w/ values from tokens[].decimals + + +```solidity +function setDecimals(IERC20[] calldata tokens) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokens`|`IERC20[]`|The array of tokens to loop and get values from.| + + +### setGlobalPricingPaused + +Set flag globalPricingPaused + + +```solidity +function setGlobalPricingPaused(bool isPaused) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`isPaused`|`bool`|The new status of pause (true/false).| + + +### _queryRate + +Calculate the price ratio between two tokens. + + +```solidity +function _queryRate(address sourceToken, address destToken) internal view returns (uint256 rate, uint256 precision); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`rate`|`uint256`|The price ratio source/dest.| +|`precision`|`uint256`|The ratio precision.| + + +### _getDecimalPrecision + +Different tokens, query prices and perform division. +Query token price on priceFeedsExt instance. +Query token price on priceFeedsExt instance. +Same tokens, return 1 with decimals. + +Calculate the relative precision between two tokens. + + +```solidity +function _getDecimalPrecision(address sourceToken, address destToken) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The precision ratio source/dest.| + + +## Events +### GlobalPricingPaused + +```solidity +event GlobalPricingPaused(address indexed sender, bool indexed isPaused); +``` + diff --git a/foundry/docs/src/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md b/foundry/docs/src/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md new file mode 100644 index 000000000..602a171d1 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md @@ -0,0 +1,15 @@ +# IPriceFeedsExt +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeeds.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### latestAnswer + + +```solidity +function latestAnswer() external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/feeds/PriceFeedsConstants.sol/contract.Constants.md b/foundry/docs/src/contracts/feeds/PriceFeedsConstants.sol/contract.Constants.md new file mode 100644 index 000000000..cbb25a746 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeedsConstants.sol/contract.Constants.md @@ -0,0 +1,80 @@ +# Constants +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeedsConstants.sol) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract keep the addresses of token instances for wrBTC, base token +and protocol token. + + +## State Variables +### wrbtcToken + +```solidity +IWrbtcERC20 public wrbtcToken; +``` + + +### baseToken + +```solidity +IWrbtcERC20 public baseToken; +``` + + +### protocolTokenAddress + +```solidity +address internal protocolTokenAddress; +``` + + +## Functions +### _setWrbtcToken + +Set wrBTC token address. + + +```solidity +function _setWrbtcToken(address _wrbtcTokenAddress) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_wrbtcTokenAddress`|`address`|The address of the wrapped wrBTC token.| + + +### _setProtocolTokenAddress + +Set protocol token address. + + +```solidity +function _setProtocolTokenAddress(address _protocolTokenAddress) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_protocolTokenAddress`|`address`|The address of the protocol token.| + + +### _setBaseToken + +Set base token address. + + +```solidity +function _setBaseToken(address _baseTokenAddress) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_baseTokenAddress`|`address`|The address of the base token.| + + diff --git a/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/contract.PriceFeedsMoC.md b/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/contract.PriceFeedsMoC.md new file mode 100644 index 000000000..63a425d46 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/contract.PriceFeedsMoC.md @@ -0,0 +1,97 @@ +# PriceFeedsMoC +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeedsMoC.sol) + +**Inherits:** +[IPriceFeedsExt](/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + + +## State Variables +### mocOracleAddress + +```solidity +address public mocOracleAddress; +``` + + +### fallbackOracleAddress + +```solidity +address public fallbackOracleAddress; +``` + + +## Functions +### constructor + +Initialize a new MoC Oracle. + + +```solidity +constructor(address _mocOracleAddress, address _fallbackOracleAddress) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_mocOracleAddress`|`address`|The MoC Oracle address.| +|`_fallbackOracleAddress`|`address`|The fallback Oracle address.| + + +### latestAnswer + +Get the las time oracle updated the price. + + +```solidity +function latestAnswer() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The latest time.| + + +### setMoCOracleAddress + +Set the MoC Oracle address. + + +```solidity +function setMoCOracleAddress(address _mocOracleAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_mocOracleAddress`|`address`|The MoC Oracle address.| + + +### setFallbackOracleAddress + +Set the fallback Oracle address. + + +```solidity +function setFallbackOracleAddress(address _fallbackOracleAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_fallbackOracleAddress`|`address`|The fallback Oracle address.| + + +## Events +### SetMoCOracleAddress + +```solidity +event SetMoCOracleAddress(address indexed mocOracleAddress, address changerAddress); +``` + +### SetFallbackOracleAddress + +```solidity +event SetFallbackOracleAddress(address indexed fallbackOracleAddress, address changerAddress); +``` + diff --git a/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/interface.IPriceFeedLatestAnswer.md b/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/interface.IPriceFeedLatestAnswer.md new file mode 100644 index 000000000..f3bda4a9a --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/interface.IPriceFeedLatestAnswer.md @@ -0,0 +1,12 @@ +# IPriceFeedLatestAnswer +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeedsMoC.sol) + + +## Functions +### latestAnswer + + +```solidity +function latestAnswer() external view returns (uint256 price, bool success); +``` + diff --git a/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/interface.Medianizer.md b/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/interface.Medianizer.md new file mode 100644 index 000000000..b3bc9d9ab --- /dev/null +++ b/foundry/docs/src/contracts/feeds/PriceFeedsMoC.sol/interface.Medianizer.md @@ -0,0 +1,12 @@ +# Medianizer +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/PriceFeedsMoC.sol) + + +## Functions +### peek + + +```solidity +function peek() external view returns (bytes32, bool); +``` + diff --git a/foundry/docs/src/contracts/feeds/README.md b/foundry/docs/src/contracts/feeds/README.md new file mode 100644 index 000000000..cf7c6622a --- /dev/null +++ b/foundry/docs/src/contracts/feeds/README.md @@ -0,0 +1,21 @@ + + +# Contents +- [testnet](/contracts/feeds/testnet) +- [BProPriceFeed](BProPriceFeed.sol/contract.BProPriceFeed.md) +- [IExternalPriceFeed](DummyFallbackOracle.sol/interface.IExternalPriceFeed.md) +- [DummyFallbackOracle](DummyFallbackOracle.sol/contract.DummyFallbackOracle.md) +- [IMoCState](IMoCState.sol/interface.IMoCState.md) +- [IPriceFeeds](IPriceFeeds.sol/interface.IPriceFeeds.md) +- [IRSKOracle](IRSKOracle.sol/interface.IRSKOracle.md) +- [IV1PoolOracle](IV1PoolOracle.sol/interface.IV1PoolOracle.md) +- [ILiquidityPoolV1Converter](IV1PoolOracle.sol/interface.ILiquidityPoolV1Converter.md) +- [PriceFeedRSKOracle](PriceFeedRSKOracle.sol/contract.PriceFeedRSKOracle.md) +- [PriceFeedV1PoolOracle](PriceFeedV1PoolOracle.sol/contract.PriceFeedV1PoolOracle.md) +- [IPriceFeedsExt](PriceFeeds.sol/interface.IPriceFeedsExt.md) +- [PriceFeeds](PriceFeeds.sol/contract.PriceFeeds.md) +- [Constants](PriceFeedsConstants.sol/contract.Constants.md) +- [Medianizer](PriceFeedsMoC.sol/interface.Medianizer.md) +- [IPriceFeedLatestAnswer](PriceFeedsMoC.sol/interface.IPriceFeedLatestAnswer.md) +- [PriceFeedsMoC](PriceFeedsMoC.sol/contract.PriceFeedsMoC.md) +- [USDTPriceFeed](USDTPriceFeed.sol/contract.USDTPriceFeed.md) diff --git a/foundry/docs/src/contracts/feeds/USDTPriceFeed.sol/contract.USDTPriceFeed.md b/foundry/docs/src/contracts/feeds/USDTPriceFeed.sol/contract.USDTPriceFeed.md new file mode 100644 index 000000000..bbafec548 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/USDTPriceFeed.sol/contract.USDTPriceFeed.md @@ -0,0 +1,51 @@ +# USDTPriceFeed +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/USDTPriceFeed.sol) + +**Inherits:** +[IPriceFeedsExt](/contracts/feeds/PriceFeeds.sol/interface.IPriceFeedsExt.md) + +The Price Feed USDT contract. +This contract implements USDT query functionality, +getting the price and the last timestamp from a +trivial formula, always returning 1 and now. + + +## State Variables +### USDT_RATE + +```solidity +uint256 private constant USDT_RATE = 1 ether; +``` + + +## Functions +### latestAnswer + +Get the USDT price. + + +```solidity +function latestAnswer() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|Always returns the trivial rate of 1.| + + +### latestTimestamp + +Get the las time the price was updated. + + +```solidity +function latestTimestamp() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|Always trivial current block's timestamp.| + + diff --git a/foundry/docs/src/contracts/feeds/testnet/MockMoCMedianizer.sol/contract.MockMoCMedianizer.md b/foundry/docs/src/contracts/feeds/testnet/MockMoCMedianizer.sol/contract.MockMoCMedianizer.md new file mode 100644 index 000000000..e0ca14d46 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/testnet/MockMoCMedianizer.sol/contract.MockMoCMedianizer.md @@ -0,0 +1,53 @@ +# MockMoCMedianizer +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/testnet/MockMoCMedianizer.sol) + +Mock medianizer contract that will support for MoC medianizer interface to be used for testnet + + +## State Variables +### price + +```solidity +uint256 public price; +``` + + +## Functions +### constructor + + +```solidity +constructor(uint256 _price) public; +``` + +### setPrice + +*set mock price* + + +```solidity +function setPrice(uint256 _price) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_price`|`uint256`|new price| + + +### peek + +*returning fixed price of rbtc (e.g: 100k)* + + +```solidity +function peek() external view returns (bytes32 value, bool hasValue); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`value`|`bytes32`|value price of rbtc| +|`hasValue`|`bool`|flag that is indicating the price is working or not| + + diff --git a/foundry/docs/src/contracts/feeds/testnet/PriceFeedsLocal.sol/contract.PriceFeedsLocal.md b/foundry/docs/src/contracts/feeds/testnet/PriceFeedsLocal.sol/contract.PriceFeedsLocal.md new file mode 100644 index 000000000..fd97503f9 --- /dev/null +++ b/foundry/docs/src/contracts/feeds/testnet/PriceFeedsLocal.sol/contract.PriceFeedsLocal.md @@ -0,0 +1,86 @@ +# PriceFeedsLocal +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/feeds/testnet/PriceFeedsLocal.sol) + +**Inherits:** +[PriceFeeds](/contracts/feeds/PriceFeeds.sol/contract.PriceFeeds.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the logic of setting and getting rates between two tokens. + + +## State Variables +### rates + +```solidity +mapping(address => mapping(address => uint256)) public rates; +``` + + +## Functions +### constructor + +uint256 public slippageMultiplier = 100 ether; + +Deploy local price feed contract. + + +```solidity +constructor(address _wrbtcTokenAddress, address _protocolTokenAddress) + public + PriceFeeds(_wrbtcTokenAddress, _protocolTokenAddress, _wrbtcTokenAddress); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_wrbtcTokenAddress`|`address`|The address of the wrBTC instance.| +|`_protocolTokenAddress`|`address`|The address of the protocol token instance.| + + +### _queryRate + +Calculate the price ratio between two tokens. + + +```solidity +function _queryRate(address sourceToken, address destToken) internal view returns (uint256 rate, uint256 precision); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`rate`|`uint256`|The price ratio source/dest.| +|`precision`|`uint256`|The ratio precision.| + + +### setRates + +Hack for testnet; only returns price in rBTC. +Hack for testnet; only returns price in rBTC. + +Owner set price ratio between two tokens. + + +```solidity +function setRates(address sourceToken, address destToken, uint256 rate) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destiny tokens.| +|`rate`|`uint256`|The price ratio source/dest.| + + diff --git a/foundry/docs/src/contracts/feeds/testnet/README.md b/foundry/docs/src/contracts/feeds/testnet/README.md new file mode 100644 index 000000000..c7de238ba --- /dev/null +++ b/foundry/docs/src/contracts/feeds/testnet/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [MockMoCMedianizer](MockMoCMedianizer.sol/contract.MockMoCMedianizer.md) +- [PriceFeedsLocal](PriceFeedsLocal.sol/contract.PriceFeedsLocal.md) diff --git a/foundry/docs/src/contracts/governance/ApprovalReceiver.sol/contract.ApprovalReceiver.md b/foundry/docs/src/contracts/governance/ApprovalReceiver.sol/contract.ApprovalReceiver.md new file mode 100644 index 000000000..334c09a06 --- /dev/null +++ b/foundry/docs/src/contracts/governance/ApprovalReceiver.sol/contract.ApprovalReceiver.md @@ -0,0 +1,114 @@ +# ApprovalReceiver +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/ApprovalReceiver.sol) + +**Inherits:** +[ErrorDecoder](/contracts/governance/ErrorDecoder.sol/contract.ErrorDecoder.md), [IApproveAndCall](/contracts/token/IApproveAndCall.sol/interface.IApproveAndCall.md) + + +## Functions +### onlyThisContract + + +```solidity +modifier onlyThisContract(); +``` + +### receiveApproval + +Receives approval from SOV token. + + +```solidity +function receiveApproval(address _sender, uint256 _amount, address _token, bytes calldata _data) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|| +|`_amount`|`uint256`|| +|`_token`|`address`|| +|`_data`|`bytes`|The data will be used for low level call.| + + +### _getToken + +Returns token address, only this address can be a sender for receiveApproval. + +*Should be overridden in child contracts, otherwise error will be thrown.* + + +```solidity +function _getToken() internal view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|By default, 0x. When overriden, the token address making the call.| + + +### _getSelectors + +Returns list of function selectors allowed to be invoked. + +*Should be overridden in child contracts, otherwise error will be thrown.* + + +```solidity +function _getSelectors() internal pure returns (bytes4[] memory); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes4[]`|By default, empty array. When overriden, allowed selectors.| + + +### _call + +Makes call and reverts w/ enhanced error message. + + +```solidity +function _call(bytes memory _data) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_data`|`bytes`|Error message as bytes.| + + +### _getSig + +Extracts the called function selector, a hash of the signature. + +*The first four bytes of the call data for a function call specifies +the function to be called. It is the first (left, high-order in big-endian) +four bytes of the Keccak-256 (SHA-3) hash of the signature of the function. +Solidity doesn't yet support a casting of byte[4] to bytes4. +Example: +msg.data: +0xcdcd77c000000000000000000000000000000000000000000000000000000000000 +000450000000000000000000000000000000000000000000000000000000000000001 +selector (or method ID): 0xcdcd77c0 +signature: baz(uint32,bool)* + + +```solidity +function _getSig(bytes memory _data) internal pure returns (bytes4 sig); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_data`|`bytes`|The msg.data from the low level call.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`sig`|`bytes4`|First 4 bytes of msg.data i.e. the selector, hash of the signature.| + + diff --git a/foundry/docs/src/contracts/governance/ErrorDecoder.sol/contract.ErrorDecoder.md b/foundry/docs/src/contracts/governance/ErrorDecoder.sol/contract.ErrorDecoder.md new file mode 100644 index 000000000..d21bdbb40 --- /dev/null +++ b/foundry/docs/src/contracts/governance/ErrorDecoder.sol/contract.ErrorDecoder.md @@ -0,0 +1,57 @@ +# ErrorDecoder +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/ErrorDecoder.sol) + +*On EVM if the return data length of a call is less than 68, +then the transaction fails silently without a revert message! +As described in the Solidity documentation +https://solidity.readthedocs.io/en/v0.5.17/control-structures.html#revert +the revert reason is an ABI-encoded string consisting of: +0x08c379a0 // Function selector (method id) for "Error(string)" signature +0x0000000000000000000000000000000000000000000000000000000000000020 // Data offset +0x000000000000000000000000000000000000000000000000000000000000001a // String length +0x4e6f7420656e6f7567682045746865722070726f76696465642e000000000000 // String data +Another example, debug data from test: +0x08c379a0 +0000000000000000000000000000000000000000000000000000000000000020 +0000000000000000000000000000000000000000000000000000000000000034 +54696d656c6f636b3a3a73657444656c61793a2044656c6179206d7573742065 +7863656564206d696e696d756d2064656c61792e000000000000000000000000 +Parsed into: +Data offset: 20 +Length: 34 +Error message: +54696d656c6f636b3a3a73657444656c61793a2044656c6179206d7573742065 +7863656564206d696e696d756d2064656c61792e000000000000000000000000* + + +## State Variables +### ERROR_MESSAGE_SHIFT + +```solidity +uint256 constant ERROR_MESSAGE_SHIFT = 68; +``` + + +## Functions +### _addErrorMessage + +Concats two error strings taking into account ERROR_MESSAGE_SHIFT. + + +```solidity +function _addErrorMessage(string memory str1, string memory str2) internal pure returns (string memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`str1`|`string`|First string, usually a hardcoded context written by dev.| +|`str2`|`string`|Second string, usually the error message from the reverted call.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`string`|The concatenated error string| + + diff --git a/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/contract.FeeSharingCollector.md b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/contract.FeeSharingCollector.md new file mode 100644 index 000000000..85c676609 --- /dev/null +++ b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/contract.FeeSharingCollector.md @@ -0,0 +1,910 @@ +# FeeSharingCollector +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol) + +**Inherits:** +[SafeMath96](/contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md), [IFeeSharingCollector](/contracts/governance/IFeeSharingCollector.sol/interface.IFeeSharingCollector.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md), [FeeSharingCollectorStorage](/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/contract.FeeSharingCollectorStorage.md) + +This contract withdraws fees to be paid to SOV Stakers from the protocol. +Stakers call withdraw() to get their share of the fees. + +Staking is not only granting voting rights, but also access to fee +sharing according to the own voting power in relation to the total. Whenever +somebody decides to collect the fees from the protocol, they get transferred +to a proxy contract which invests the funds in the lending pool and keeps +the pool tokens. +The fee sharing proxy will be set as feesController of the protocol contract. +This allows the fee sharing proxy to withdraw the fees. The fee sharing +proxy holds the pool tokens and keeps track of which user owns how many +tokens. In order to know how many tokens a user owns, the fee sharing proxy +needs to know the user’s weighted stake in relation to the total weighted +stake (aka total voting power). +Because both values are subject to change, they may be different on each fee +withdrawal. To be able to calculate a user’s share of tokens when he wants +to withdraw, we need checkpoints. +This contract is intended to be set as the protocol fee collector. +Anybody can invoke the withdrawFees function which uses +protocol.withdrawFees to obtain available fees from operations on a +certain token. These fees are deposited in the corresponding loanPool. +Also, the staking contract sends slashed tokens to this contract. +When a user calls the withdraw function, the contract transfers the fee sharing +rewards in proportion to the user’s weighted stake since the last withdrawal. +The protocol initially collects fees in all tokens. +Then the FeeSharingCollector wihtdraws fees from the protocol. +When the fees are withdrawn all the tokens except SOV will be converted to wRBTC +and then transferred to wRBTC loan pool. +For SOV, it will be directly deposited into the feeSharingCollector from the protocol. + + +## State Variables +### ZERO_ADDRESS + +```solidity +address constant ZERO_ADDRESS = address(0); +``` + + +### RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT + +```solidity +address public constant RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT = + address(uint160(uint256(keccak256("RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT")))); +``` + + +## Functions +### oneTimeExecution + + +```solidity +modifier oneTimeExecution(bytes4 _funcSig); +``` + +### function + +*fallback function to support rbtc transfer when unwrap the wrbtc.* + + +```solidity +function() external payable; +``` + +### initialize + +*initialize function for fee sharing collector proxy* + + +```solidity +function initialize(address wrbtcToken, address loanWrbtcToken) + external + onlyOwner + oneTimeExecution(this.initialize.selector); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`wrbtcToken`|`address`|wrbtc token address| +|`loanWrbtcToken`|`address`|address of loan token wrbtc (IWrbtc)| + + +### setWrbtcToken + +Set the wrbtc token address of fee sharing collector. +only owner can perform this action. + + +```solidity +function setWrbtcToken(address newWrbtcTokenAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newWrbtcTokenAddress`|`address`|The new address of the wrbtc token.| + + +### setLoanTokenWrbtc + +Set the loan wrbtc token address of fee sharing collector. +only owner can perform this action. + + +```solidity +function setLoanTokenWrbtc(address newLoanTokenWrbtcAddress) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newLoanTokenWrbtcAddress`|`address`|The new address of the loan wrbtc token.| + + +### withdrawFees + +Withdraw fees for the given token: +lendingFee + tradingFee + borrowingFee +the fees (except SOV) will be converted in wRBTC form, and then will be transferred to wRBTC loan pool. +For SOV, it will be directly deposited into the feeSharingCollector from the protocol. + + +```solidity +function withdrawFees(address[] calldata _tokens) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokens`|`address[]`|array address of the token| + + +### withdrawFeesAMM + +Update unprocessed amount of tokens + +Withdraw amm fees for the given converter addresses: +protocolFee from the conversion +the fees will be converted in wRBTC form, and then will be transferred to wRBTC loan pool + + +```solidity +function withdrawFeesAMM(address[] memory _converters) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_converters`|`address[]`|array addresses of the converters| + + +### transferTokens + +Update unprocessed amount of tokens + +Transfer tokens to this contract. + +*We just update amount of tokens here and write checkpoint in a separate methods +in order to prevent adding checkpoints too often.* + + +```solidity +function transferTokens(address _token, uint96 _amount) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|Address of the token.| +|`_amount`|`uint96`|Amount to be transferred.| + + +### transferRBTC + +Transfer tokens from msg.sender + +Transfer RBTC / native tokens to this contract. + +*We just write checkpoint here (based on the rbtc value that is sent) in a separate methods +in order to prevent adding checkpoints too often.* + + +```solidity +function transferRBTC() external payable; +``` + +### _addCheckpoint + +Add checkpoint with accumulated amount by function invocation. + + +```solidity +function _addCheckpoint(address _token, uint96 _amount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|Address of the token.| +|`_amount`|`uint96`|| + + +### _withdraw + +Reset unprocessed amount of tokens to zero. + +Write a regular checkpoint. + + +```solidity +function _withdraw(address _token, uint32 _maxCheckpoints, address _receiver) + internal + returns (uint256 totalAmount, uint256 endTokenCheckpoint); +``` + +### withdraw + +Withdraw accumulated fee to the message sender. +The Sovryn protocol collects fees on every trade/swap and loan. +These fees will be distributed to SOV stakers based on their voting +power as a percentage of total voting power. Therefore, staking more +SOV and/or staking for longer will increase your share of the fees +generated, meaning you will earn more from staking. +This function will directly burnToBTC and use the msg.sender (user) as the receiver + +*Prevents block gas limit hit when processing checkpoints* + + +```solidity +function withdraw(address _token, uint32 _maxCheckpoints, address _receiver) public nonReentrant; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.| +|`_maxCheckpoints`|`uint32`|Maximum number of checkpoints to be processed. Must be positive value.| +|`_receiver`|`address`|The receiver of tokens or msg.sender| + + +### validFromCheckpointsParam + +Validates if the checkpoint is payable for the user + + +```solidity +function validFromCheckpointsParam(TokenWithSkippedCheckpointsWithdraw[] memory _tokens, address _user) private view; +``` + +### validRBTCBasedTokens + + +```solidity +function validRBTCBasedTokens(address[] memory _tokens) private view; +``` + +### _withdrawStartingFromCheckpoints + +Withdraw accumulated fee to the message sender/receiver. +The Sovryn protocol collects fees on every trade/swap and loan. +These fees will be distributed to SOV stakers based on their voting +power as a percentage of total voting power. +This function will directly burnToBTC and use the msg.sender (user) as the receiver + +*WARNING! This function skips all the checkpoints before '_fromCheckpoint' irreversibly, use with care* + + +```solidity +function _withdrawStartingFromCheckpoints( + TokenWithSkippedCheckpointsWithdraw[] memory _tokens, + uint32 _maxCheckpoints, + address _receiver +) internal returns (uint256 totalProcessedCheckpoints); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokens`|`TokenWithSkippedCheckpointsWithdraw[]`|Array of TokenWithSkippedCheckpointsWithdraw struct, which contains the token address, and fromCheckpoiint fromCheckpoints Skips all the checkpoints before '_fromCheckpoint' should be calculated offchain with getNextPositiveUserCheckpoint function| +|`_maxCheckpoints`|`uint32`|Maximum number of checkpoints to be processed.| +|`_receiver`|`address`|The receiver of tokens or msg.sender| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`totalProcessedCheckpoints`|`uint256`|total processed checkpoints| + + +### claimAllCollectedFees + +*Function to wrap: +1. regular withdrawal for both rbtc & non-rbtc token +2. skipped checkpoints withdrawal for both rbtc & non-rbtc token* + + +```solidity +function claimAllCollectedFees( + address[] calldata _nonRbtcTokensRegularWithdraw, + address[] calldata _rbtcTokensRegularWithdraw, + TokenWithSkippedCheckpointsWithdraw[] calldata _tokensWithSkippedCheckpoints, + uint32 _maxCheckpoints, + address _receiver +) external nonReentrant; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_nonRbtcTokensRegularWithdraw`|`address[]`|array of non-rbtc token address with no skipped checkpoints that will be withdrawn| +|`_rbtcTokensRegularWithdraw`|`address[]`|array of rbtc token address with no skipped checkpoints that will be withdrawn| +|`_tokensWithSkippedCheckpoints`|`TokenWithSkippedCheckpointsWithdraw[]`|array of rbtc & non-rbtc TokenWithSkippedCheckpointsWithdraw struct, which has skipped checkpoints that will be withdrawn| +|`_maxCheckpoints`|`uint32`|| +|`_receiver`|`address`|| + + +### _withdrawStartingFromCheckpoint + +Process normal multiple withdrawal for RBTC based tokens +Process normal non-rbtc token withdrawal + + +```solidity +function _withdrawStartingFromCheckpoint( + address _token, + uint256 _fromCheckpoint, + uint32 _maxCheckpoints, + address _receiver +) internal returns (uint256 totalAmount, uint256 endTokenCheckpoint); +``` + +### _withdrawRbtcToken + + +```solidity +function _withdrawRbtcToken(address _token, uint32 _maxCheckpoints) + internal + returns (uint256 totalAmount, uint256 endTokenCheckpoint); +``` + +### _withdrawRbtcTokens + +*will use the burned result from IWRBTC to RBTC as return total amount* + +*withdraw all of the RBTC balance based on particular checkpoints +This function will withdraw RBTC balance which is passed as _token param, so it could be either of these: +- rbtc balance or +- wrbtc balance which will be unwrapped to rbtc or +- iwrbtc balance which will be unwrapped to rbtc or* + + +```solidity +function _withdrawRbtcTokens(address[] memory _tokens, uint32 _maxCheckpoints, address _receiver) + internal + returns (uint256 totalProcessedCheckpoints); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokens`|`address[]`|array of either RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT or wrbtc address or iwrbtc address| +|`_maxCheckpoints`|`uint32`| Maximum number of checkpoints to be processed to workaround block gas limit| +|`_receiver`|`address`|An optional tokens receiver (msg.sender used if 0)| + + +### _withdrawRbtcTokenStartingFromCheckpoint + +*Withdraw either specific RBTC related token balance or all RBTC related tokens balances. +RBTC related here means, it could be either rbtc, wrbtc, or iwrbtc, depends on the _token param.* + + +```solidity +function _withdrawRbtcTokenStartingFromCheckpoint( + address _token, + uint256 _fromCheckpoint, + uint32 _maxCheckpoints, + address _receiver +) private returns (uint256 totalAmount, uint256 endTokenCheckpoint); +``` + +### getNextPositiveUserCheckpoint + +*Returns first user's checkpoint with weighted stake > 0* + + +```solidity +function getNextPositiveUserCheckpoint(address _user, address _token, uint256 _startFrom, uint256 _maxCheckpoints) + external + view + returns (uint256 checkpointNum, bool hasSkippedCheckpoints, bool hasFees); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|The address of the user or contract.| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.| +|`_startFrom`|`uint256`|Checkpoint number to start from. If _startFrom < processedUserCheckpoints then starts from processedUserCheckpoints.| +|`_maxCheckpoints`|`uint256`|Max checkpoints to process in a row to avoid timeout error| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`checkpointNum`|`uint256`|[checkpointNum: checkpoint number where user's weighted stake > 0, hasSkippedCheckpoints, hasFees]| +|`hasSkippedCheckpoints`|`bool`|| +|`hasFees`|`bool`|| + + +### _getNextPositiveUserCheckpoint + +*Returns first user's checkpoint with weighted stake > 0* + + +```solidity +function _getNextPositiveUserCheckpoint(address _user, address _token, uint256 _startFrom, uint256 _maxCheckpoints) + internal + view + returns (uint256 checkpointNum, bool hasSkippedCheckpoints, bool hasFees); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|The address of the user or contract.| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.| +|`_startFrom`|`uint256`|Checkpoint number to start from. If _startFrom < processedUserCheckpoints then starts from processedUserCheckpoints.| +|`_maxCheckpoints`|`uint256`|Max checkpoints to process in a row to avoid timeout error| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`checkpointNum`|`uint256`|[checkpointNum: checkpoint number where user's weighted stake > 0, hasSkippedCheckpoints, hasFees]| +|`hasSkippedCheckpoints`|`bool`|| +|`hasFees`|`bool`|| + + +### getAccumulatedFees + +Get the accumulated loan pool fee of the message sender. + + +```solidity +function getAccumulatedFees(address _user, address _token) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|The address of the user or contract.| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The accumulated fee for the message sender.| + + +### getAccumulatedFeesForCheckpointsRange + +Get the accumulated fee rewards for the message sender for a checkpoints range + +*This function is required to keep consistent with caching of weighted voting power when claiming fees* + + +```solidity +function getAccumulatedFeesForCheckpointsRange( + address _user, + address _token, + uint256 _startFrom, + uint32 _maxCheckpoints +) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|The address of a user (staker) or contract.| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.| +|`_startFrom`|`uint256`|Checkpoint to start calculating fees from.| +|`_maxCheckpoints`|`uint32`|maxCheckpoints to get accumulated fees for the _user| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The accumulated fees rewards for the _user in the given checkpoints interval: [_startFrom, _startFrom + maxCheckpoints].| + + +### getAllUserFeesPerMaxCheckpoints + +*Get all user fees reward per maxCheckpoint starting from latest processed checkpoint* + +*e.g: Total user checkpoint for the particualar token = 300, +when we call this function with 50 maxCheckpoint, it will return 6 fee values in array form. +if there is no more fees, it will return empty array.* + + +```solidity +function getAllUserFeesPerMaxCheckpoints(address _user, address _token, uint256 _startFrom, uint32 _maxCheckpoints) + external + view + returns (uint256[] memory fees); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|The address of a user (staker) or contract.| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.| +|`_startFrom`|`uint256`|Checkpoint to start calculating fees from.| +|`_maxCheckpoints`|`uint32`|maxCheckpoints to get accumulated fees for the _user| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`fees`|`uint256[]`|The next checkpoint num which is the starting point to fetch all of the fees, array of calculated fees.| + + +### _getAccumulatedFees + +Gets accumulated fees for a user starting from a given checkpoint + + +```solidity +function _getAccumulatedFees(address _user, address _token, uint256 _startFrom, uint32 _maxCheckpoints) + internal + view + returns (uint256 feesAmount, uint256 endCheckpoint); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|Address of the user's account.| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of the pool token.| +|`_startFrom`|`uint256`|Checkpoint num to start calculations from| +|`_maxCheckpoints`|`uint32`|Max checkpoints to process at once to fit into block gas limit| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`feesAmount`|`uint256`|- accumulated fees amount| +|`endCheckpoint`|`uint256`|- last checkpoint of fees calculation| + + +### _getEndOfRange + +Withdrawal should only be possible for blocks which were already +mined. If the fees are withdrawn in the same block as the user withdrawal +they are not considered by the withdrawing logic (to avoid inconsistencies). + +*We need to use "checkpoint.blockNumber - 1" here to calculate weighted stake +For the same block like we did for total voting power in _writeTokenCheckpoint* + + +```solidity +function _getEndOfRange(uint256 _start, address _token, uint32 _maxCheckpoints) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_start`|`uint256`|Start of the range.| +|`_token`|`address`|RBTC dummy to fit into existing data structure or SOV. Former address of a pool token.| +|`_maxCheckpoints`|`uint32`|Checkpoint index incremental.| + + +### _writeTokenCheckpoint + +Write a regular checkpoint w/ the foolowing data: +block number, block timestamp, total weighted stake and num of tokens. + +*All checkpoints will be processed (only for getter outside of a transaction).* + +*Withdrawal should only be possible for blocks which were already mined.* + + +```solidity +function _writeTokenCheckpoint(address _token, uint96 _numTokens) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|The pool token address.| +|`_numTokens`|`uint96`|The amount of pool tokens.| + + +### _getVoluntaryWeightedStake + +Queries the total weighted stake and the weighted stake of vesting contracts and returns the difference + + +```solidity +function _getVoluntaryWeightedStake(uint32 blockNumber, uint256 timestamp) + internal + view + returns (uint96 totalWeightedStake); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`blockNumber`|`uint32`|the blocknumber| +|`timestamp`|`uint256`|the timestamp| + + +### addWhitelistedConverterAddress + +*Whitelisting converter address.* + + +```solidity +function addWhitelistedConverterAddress(address converterAddress) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`converterAddress`|`address`|converter address to be whitelisted.| + + +### removeWhitelistedConverterAddress + +*Removing converter address from whitelist.* + + +```solidity +function removeWhitelistedConverterAddress(address converterAddress) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`converterAddress`|`address`|converter address to be removed from whitelist.| + + +### getWhitelistedConverterList + +Getter to query all of the whitelisted converter. + + +```solidity +function getWhitelistedConverterList() external view returns (address[] memory converterList); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`converterList`|`address[]`|All of the whitelisted converter list.| + + +### _validateWhitelistedConverter + +*validate array of given address whether is whitelisted or not.* + +*if one of them is not whitelisted, then revert.* + + +```solidity +function _validateWhitelistedConverter(address[] memory converterAddresses) private view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`converterAddresses`|`address[]`|array of converter addresses.| + + +### withdrawWRBTC + + +```solidity +function withdrawWRBTC(address receiver, uint256 wrbtcAmount) external onlyOwner; +``` + +### recoverIncorrectAllocatedFees + +*This function is dedicated to recover the wrong fee allocation for the 4 year vesting contracts. +This function can only be called once +The affected tokens to be withdrawn +1. RBTC +2. ZUSD +3. SOV +The amount for all of the tokens above is hardcoded +The withdrawn tokens will be sent to the owner.* + + +```solidity +function recoverIncorrectAllocatedFees() + external + oneTimeExecution(this.recoverIncorrectAllocatedFees.selector) + onlyOwner; +``` + +### getAccumulatedRBTCFeeBalances + +*view function that calculate the total RBTC that includes: +- RBTC +- WRBTC +- iWRBTC * iWRBTC.tokenPrice()* + + +```solidity +function getAccumulatedRBTCFeeBalances(address _user) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|address of the user.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|rbtc balance of the given user's address.| + + +### _getRBTCBalances + +*private function that responsible to calculate the user's token that has RBTC as underlying token (rbtc, wrbtc, iWrbtc)* + + +```solidity +function _getRBTCBalances(address _user, uint32 _maxCheckpoints) + private + view + returns ( + uint256 _rbtcAmount, + uint256 _wrbtcAmount, + uint256 _iWrbtcAmount, + uint256 _endRBTC, + uint256 _endWRBTC, + uint256 _endIWRBTC + ); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_user`|`address`|address of the user.| +|`_maxCheckpoints`|`uint32`|maximum checkpoints.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_rbtcAmount`|`uint256`|rbtc amount| +|`_wrbtcAmount`|`uint256`|wrbtc amount| +|`_iWrbtcAmount`|`uint256`|iWrbtc (wrbtc lending pool token) amount * token price| +|`_endRBTC`|`uint256`|end time of accumulated fee calculation for rbtc| +|`_endWRBTC`|`uint256`|end time of accumulated fee calculation for wrbtc| +|`_endIWRBTC`|`uint256`|end time of accumulated fee calculation for iwrbtc| + + +### _getRBTCBalance + +*private function that responsible to calculate the user's token that has RBTC as underlying token (rbtc, wrbtc, iWrbtc)* + + +```solidity +function _getRBTCBalance(address _token, address _user, uint32 _maxCheckpoints) + internal + view + returns (uint256 _tokenAmount, uint256 _endToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|either RBTC_DUMMY_ADDRESS_FOR_CHECKPOINT or wrbtc address or iwrbtc address| +|`_user`|`address`|address of the user.| +|`_maxCheckpoints`|`uint32`|maximum checkpoints.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenAmount`|`uint256`|token (rbtc, or wrbtc, or iwrbtc) amount| +|`_endToken`|`uint256`|end time of accumulated fee calculation for token (rbtc, or wrbtc, or iwrbtc )| + + +### numTokenCheckpoints + +*This getter function `numTokenCheckpoints` is added for backwards compatibility +broken when renamed `numTokenCheckpoints` storage variable to `totalTokenCheckpoints`.* + + +```solidity +function numTokenCheckpoints(address _token) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|token address to get checkpoints for| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|Total token checkpoints| + + +## Events +### FeeWithdrawnInRBTC +Deprecated event after the unification between wrbtc & rbtc + + +```solidity +event FeeWithdrawnInRBTC(address indexed sender, uint256 amount); +``` + +### TokensTransferred +An event emitted when tokens transferred. + + +```solidity +event TokensTransferred(address indexed sender, address indexed token, uint256 amount); +``` + +### CheckpointAdded +An event emitted when checkpoint added. + + +```solidity +event CheckpointAdded(address indexed sender, address indexed token, uint256 amount); +``` + +### UserFeeWithdrawn +An event emitted when user fee get withdrawn. + + +```solidity +event UserFeeWithdrawn(address indexed sender, address indexed receiver, address indexed token, uint256 amount); +``` + +### UserFeeProcessedNoWithdraw +An event emitted when user fee get withdrawn. + + +```solidity +event UserFeeProcessedNoWithdraw( + address indexed sender, address indexed token, uint256 prevProcessedCheckpoints, uint256 newProcessedCheckpoints +); +``` + +### FeeAMMWithdrawn +An event emitted when fee from AMM get withdrawn. + + +```solidity +event FeeAMMWithdrawn(address indexed sender, address indexed converter, uint256 amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sender`|`address`|sender who initiate the withdrawn amm fees.| +|`converter`|`address`|the converter address.| +|`amount`|`uint256`|total amount of fee (Already converted to WRBTC).| + +### WhitelistedConverter +An event emitted when converter address has been registered to be whitelisted. + + +```solidity +event WhitelistedConverter(address indexed sender, address converter); +``` + +### UnwhitelistedConverter +An event emitted when converter address has been removed from whitelist. + + +```solidity +event UnwhitelistedConverter(address indexed sender, address converter); +``` + +### RBTCWithdrawn + +```solidity +event RBTCWithdrawn(address indexed sender, address indexed receiver, uint256 amount); +``` + +### SetWrbtcToken + +```solidity +event SetWrbtcToken(address indexed sender, address indexed oldWrbtcToken, address indexed newWrbtcToken); +``` + +### SetLoanTokenWrbtc + +```solidity +event SetLoanTokenWrbtc(address indexed sender, address indexed oldLoanTokenWrbtc, address indexed newLoanTokenWrbtc); +``` + diff --git a/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanToken.md b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanToken.md new file mode 100644 index 000000000..776c83112 --- /dev/null +++ b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanToken.md @@ -0,0 +1,12 @@ +# ILoanToken +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol) + + +## Functions +### mint + + +```solidity +function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount); +``` + diff --git a/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanTokenWRBTC.md b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanTokenWRBTC.md new file mode 100644 index 000000000..63e2b5f23 --- /dev/null +++ b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol/interface.ILoanTokenWRBTC.md @@ -0,0 +1,19 @@ +# ILoanTokenWRBTC +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/FeeSharingCollector/FeeSharingCollector.sol) + + +## Functions +### burnToBTC + + +```solidity +function burnToBTC(address receiver, uint256 burnAmount, bool useLM) external returns (uint256 loanAmountPaid); +``` + +### tokenPrice + + +```solidity +function tokenPrice() external view returns (uint256 price); +``` + diff --git a/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorProxy.sol/contract.FeeSharingCollectorProxy.md b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorProxy.sol/contract.FeeSharingCollectorProxy.md new file mode 100644 index 000000000..5f012cae4 --- /dev/null +++ b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorProxy.sol/contract.FeeSharingCollectorProxy.md @@ -0,0 +1,29 @@ +# FeeSharingCollectorProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/FeeSharingCollector/FeeSharingCollectorProxy.sol) + +**Inherits:** +[FeeSharingCollectorStorage](/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/contract.FeeSharingCollectorStorage.md), [UpgradableProxy](/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + +*FeeSharingCollectorProxy contract should be upgradable, use UpgradableProxy. +FeeSharingCollectorStorage is deployed with the upgradable functionality +by using this contract instead, that inherits from UpgradableProxy +the possibility of being enhanced and re-deployed.* + + +## Functions +### constructor + +Construct a new feeSharingCollectorProxy contract. + + +```solidity +constructor(IProtocol _protocol, IStaking _staking) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_protocol`|`IProtocol`|The address of the sovryn protocol.| +|`_staking`|`IStaking`|The address of the staking| + + diff --git a/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/contract.FeeSharingCollectorStorage.md b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/contract.FeeSharingCollectorStorage.md new file mode 100644 index 000000000..062eba14c --- /dev/null +++ b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/contract.FeeSharingCollectorStorage.md @@ -0,0 +1,185 @@ +# FeeSharingCollectorStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +Just the storage part of FeeSharingCollector contract, and FeeSharingCollectorProxy. No functions, +only constant, variables and required structures (mappings) + + +## State Variables +### FEE_WITHDRAWAL_INTERVAL + +```solidity +uint256 constant FEE_WITHDRAWAL_INTERVAL = 172800; +``` + + +### protocol + +```solidity +IProtocol public protocol; +``` + + +### staking + +```solidity +IStaking public staking; +``` + + +### tokenCheckpoints +Checkpoints by index per pool token address + + +```solidity +mapping(address => mapping(uint256 => Checkpoint)) public tokenCheckpoints; +``` + + +### totalTokenCheckpoints +The number of checkpoints for each token address. + + +```solidity +mapping(address => uint256) public totalTokenCheckpoints; +``` + + +### processedCheckpoints + +user => token => processed checkpoints + + +```solidity +mapping(address => mapping(address => uint256)) public processedCheckpoints; +``` + + +### lastFeeWithdrawalTime +Last time fees were withdrawn per pool token address: +token => time + + +```solidity +mapping(address => uint256) public lastFeeWithdrawalTime; +``` + + +### unprocessedAmount +Amount of tokens that were transferred, but not saved in checkpoints. +token => amount + + +```solidity +mapping(address => uint96) public unprocessedAmount; +``` + + +### REENTRANCY_GUARD_FREE +*Add extra modifier (Reentrancy) below. +Because we cannot add any additional storage slot before this storage contract after initial deployment* + +*Constant for unlocked guard state - non-zero to prevent extra gas costs. +See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056* + + +```solidity +uint256 internal constant REENTRANCY_GUARD_FREE = 1; +``` + + +### REENTRANCY_GUARD_LOCKED +*Constant for locked guard state* + + +```solidity +uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; +``` + + +### reentrancyLock +*We use a single lock for the whole contract.* + + +```solidity +uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; +``` + + +### whitelistedConverterList +*Additional storage for converter whitelist mechanism.* + +*Initialization here does not works. We need to create a separate setter & getter.* + +*Just set the visibility to internal should be fine.* + + +```solidity +EnumerableAddressSet.AddressSet internal whitelistedConverterList; +``` + + +### isFunctionExecuted + +```solidity +mapping(bytes4 => bool) public isFunctionExecuted; +``` + + +### wrbtcTokenAddress +*Wrbtc token address* + + +```solidity +address public wrbtcTokenAddress; +``` + + +### loanTokenWrbtcAddress +*iWrbtc loan token address* + + +```solidity +address public loanTokenWrbtcAddress; +``` + + +## Functions +### nonReentrant + +*Prevents a contract from calling itself, directly or indirectly. +If you mark a function `nonReentrant`, you should also +mark it `external`. Calling one `nonReentrant` function from +another is not supported. Instead, you can implement a +`private` function doing the actual work, and an `external` +wrapper marked as `nonReentrant`.* + + +```solidity +modifier nonReentrant(); +``` + +## Structs +### Checkpoint + +```solidity +struct Checkpoint { + uint32 blockNumber; + uint32 timestamp; + uint96 totalWeightedStake; + uint96 numTokens; +} +``` + +### TokenWithSkippedCheckpointsWithdraw + +```solidity +struct TokenWithSkippedCheckpointsWithdraw { + address tokenAddress; + uint256 fromCheckpoint; +} +``` + diff --git a/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/interface.IProtocol.md b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/interface.IProtocol.md new file mode 100644 index 000000000..8523649dd --- /dev/null +++ b/foundry/docs/src/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol/interface.IProtocol.md @@ -0,0 +1,46 @@ +# IProtocol +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/FeeSharingCollector/FeeSharingCollectorStorage.sol) + + +## Functions +### withdrawFees + + +```solidity +function withdrawFees(address[] calldata tokens, address receiver) external returns (uint256 totalWRBTCWithdrawn); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokens`|`address[]`|The array address of the token instance.| +|`receiver`|`address`|The address of the withdrawal recipient.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`totalWRBTCWithdrawn`|`uint256`|The withdrawn total amount in wRBTC| + + +### underlyingToLoanPool + + +```solidity +function underlyingToLoanPool(address token) external view returns (address); +``` + +### wrbtcToken + + +```solidity +function wrbtcToken() external view returns (IWrbtcERC20); +``` + +### getSovTokenAddress + + +```solidity +function getSovTokenAddress() external view returns (address); +``` + diff --git a/foundry/docs/src/contracts/governance/FeeSharingCollector/README.md b/foundry/docs/src/contracts/governance/FeeSharingCollector/README.md new file mode 100644 index 000000000..596b58509 --- /dev/null +++ b/foundry/docs/src/contracts/governance/FeeSharingCollector/README.md @@ -0,0 +1,9 @@ + + +# Contents +- [FeeSharingCollector](FeeSharingCollector.sol/contract.FeeSharingCollector.md) +- [ILoanToken](FeeSharingCollector.sol/interface.ILoanToken.md) +- [ILoanTokenWRBTC](FeeSharingCollector.sol/interface.ILoanTokenWRBTC.md) +- [FeeSharingCollectorProxy](FeeSharingCollectorProxy.sol/contract.FeeSharingCollectorProxy.md) +- [FeeSharingCollectorStorage](FeeSharingCollectorStorage.sol/contract.FeeSharingCollectorStorage.md) +- [IProtocol](FeeSharingCollectorStorage.sol/interface.IProtocol.md) diff --git a/foundry/docs/src/contracts/governance/GovernorAlpha.sol/contract.GovernorAlpha.md b/foundry/docs/src/contracts/governance/GovernorAlpha.sol/contract.GovernorAlpha.md new file mode 100644 index 000000000..cec5da9eb --- /dev/null +++ b/foundry/docs/src/contracts/governance/GovernorAlpha.sol/contract.GovernorAlpha.md @@ -0,0 +1,601 @@ +# GovernorAlpha +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/GovernorAlpha.sol) + +**Inherits:** +[SafeMath96](/contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md) + +This is an adapted clone of compound’s governance model. In general, +the process is the same: Token holders can make (executable) proposals if +they possess enough voting power, vote on proposals during a predefined +voting period and in the end evaluate the outcome. If successful, the +proposal will be scheduled on the timelock contract. Only after sufficient +time passed, it can be executed. A minimum voting power is required for +making a proposal as well as a minimum quorum. +Voting power in the Bitocracy: +Stakers will receive voting power in the Bitocracy in return for their +staking commitment. This voting power is weighted by how much SOV is staked +and for how long the staking period is - staking more SOV over longer staking +periods results in higher voting power. With this voting power, users can +vote for or against any SIP in bitocracy.sovryn.app. + + +## State Variables +### NAME +The name of this contract. + + +```solidity +string public constant NAME = "Sovryn Governor Alpha"; +``` + + +### timelock +The address of the Sovryn Protocol Timelock. + + +```solidity +ITimelock public timelock; +``` + + +### staking +The address of the Sovryn staking contract. + + +```solidity +IStaking public staking; +``` + + +### guardian +The address of the Governor Guardian. + + +```solidity +address public guardian; +``` + + +### proposalCount +The total number of proposals. + + +```solidity +uint256 public proposalCount; +``` + + +### quorumPercentageVotes +Percentage of current total voting power require to vote. + + +```solidity +uint96 public quorumPercentageVotes; +``` + + +### majorityPercentageVotes + +```solidity +uint96 public majorityPercentageVotes; +``` + + +### proposals +The official record of all proposals ever proposed. + + +```solidity +mapping(uint256 => Proposal) public proposals; +``` + + +### latestProposalIds +The latest proposal for each proposer. + + +```solidity +mapping(address => uint256) public latestProposalIds; +``` + + +### DOMAIN_TYPEHASH +The EIP-712 typehash for the contract's domain. + + +```solidity +bytes32 public constant DOMAIN_TYPEHASH = + keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); +``` + + +### BALLOT_TYPEHASH +The EIP-712 typehash for the ballot struct used by the contract. + + +```solidity +bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); +``` + + +## Functions +### proposalMaxOperations + +The maximum number of actions that can be included in a proposal. + + +```solidity +function proposalMaxOperations() public pure returns (uint256); +``` + +### votingDelay + +The delay before voting on a proposal may take place, once proposed. + + +```solidity +function votingDelay() public pure returns (uint256); +``` + +### votingPeriod + +The duration of voting on a proposal, in blocks. + + +```solidity +function votingPeriod() public pure returns (uint256); +``` + +### constructor + + +```solidity +constructor( + address timelock_, + address staking_, + address guardian_, + uint96 _quorumPercentageVotes, + uint96 _majorityPercentageVotes +) public; +``` + +### proposalThreshold + +The number of votes required in order for a voter to become a proposer. + + +```solidity +function proposalThreshold() public view returns (uint96); +``` + +### quorumVotes + +The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed. + + +```solidity +function quorumVotes() public view returns (uint96); +``` + +### propose + +Create a new proposal. + + +```solidity +function propose( + address[] memory targets, + uint256[] memory values, + string[] memory signatures, + bytes[] memory calldatas, + string memory description +) public returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`targets`|`address[]`|Array of contract addresses to perform proposal execution.| +|`values`|`uint256[]`|Array of rBTC amounts to send on proposal execution.| +|`signatures`|`string[]`|Array of function signatures to call on proposal execution.| +|`calldatas`|`bytes[]`|Array of payloads for the calls on proposal execution.| +|`description`|`string`|Text describing the purpose of the proposal.| + + +### queue + +Enqueue a proposal and everyone of its calls. + +*quorum: proposalThreshold is 1% of total votes, we can save gas using this pre calculated value.* + +*startTime: Required by the staking contract. not used by the governance contract itself.* + + +```solidity +function queue(uint256 proposalId) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| + + +### _queueOrRevert + +Tries to enqueue a proposal, verifying it has not been previously queued. + + +```solidity +function _queueOrRevert(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) + internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|Contract addresses to perform proposal execution.| +|`value`|`uint256`|rBTC amount to send on proposal execution.| +|`signature`|`string`|Function signature to call on proposal execution.| +|`data`|`bytes`|Payload for the call on proposal execution.| +|`eta`|`uint256`|Estimated Time of Accomplishment. The timestamp that the proposal will be available for execution, set once the vote succeeds.| + + +### execute + +Execute a proposal by looping and performing everyone of its calls. + + +```solidity +function execute(uint256 proposalId) public payable; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| + + +### cancel + +Cancel a proposal by looping and cancelling everyone of its calls. + + +```solidity +function cancel(uint256 proposalId) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| + + +### getActions + +Cancel only if sent by the guardian. + +Get a proposal list of its calls. + + +```solidity +function getActions(uint256 proposalId) + public + view + returns (address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`targets`|`address[]`|Arrays of the 4 call parameters: targets, values, signatures, calldatas.| +|`values`|`uint256[]`|| +|`signatures`|`string[]`|| +|`calldatas`|`bytes[]`|| + + +### getReceipt + +Get a proposal receipt. + + +```solidity +function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| +|`voter`|`address`|A governance stakeholder with voting power.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`Receipt`|The voter receipt of the proposal.| + + +### castVote + +Casts a vote by sender. + + +```solidity +function castVote(uint256 proposalId, bool support) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| +|`support`|`bool`|Vote value, yes or no.| + + +### castVoteBySig + +Voting with EIP-712 Signatures. +Voting power can be delegated to any address, and then can be used to +vote on proposals. A key benefit to users of by-signature functionality +is that they can create a signed vote transaction for free, and have a +trusted third-party spend rBTC(or ETH) on gas fees and write it to the +blockchain for them. +The third party in this scenario, submitting the SOV-holder’s signed +transaction holds a voting power that is for only a single proposal. +The signatory still holds the power to vote on their own behalf in +the proposal if the third party has not yet published the signed +transaction that was given to them. + +*The signature needs to be broken up into 3 parameters, known as +v, r and s: +const r = '0x' + sig.substring(2).substring(0, 64); +const s = '0x' + sig.substring(2).substring(64, 128); +const v = '0x' + sig.substring(2).substring(128, 130);* + + +```solidity +function castVoteBySig(uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| +|`support`|`bool`|Vote value, yes or no.| +|`v`|`uint8`|The recovery byte of the signature.| +|`r`|`bytes32`|Half of the ECDSA signature pair.| +|`s`|`bytes32`|Half of the ECDSA signature pair.| + + +### _castVote + +Cast a vote, adding it to the total counting. + +*The DOMAIN_SEPARATOR is a hash that uniquely identifies a +smart contract. It is built from a string denoting it as an +EIP712 Domain, the name of the token contract, the version, +the chainId in case it changes, and the address that the +contract is deployed at.* + +*GovernorAlpha uses BALLOT_TYPEHASH, while Staking uses DELEGATION_TYPEHASH* + +*Verify address is not null and PK is not null either.* + + +```solidity +function _castVote(address voter, uint256 proposalId, bool support) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`voter`|`address`|A governance stakeholder with voting power that is casting the vote.| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| +|`support`|`bool`|Vote value, yes or no.| + + +### __acceptAdmin + +*Timelock wrapper w/ sender check.* + + +```solidity +function __acceptAdmin() public; +``` + +### __abdicate + +Sets guardian address to zero. + + +```solidity +function __abdicate() public; +``` + +### __queueSetTimelockPendingAdmin + +*Timelock wrapper w/ sender check.* + + +```solidity +function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public; +``` + +### __executeSetTimelockPendingAdmin + +*Timelock wrapper w/ sender check.* + + +```solidity +function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public; +``` + +### state + +Get a proposal state. + + +```solidity +function state(uint256 proposalId) public view returns (ProposalState); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`proposalId`|`uint256`|Proposal index to access the list proposals[] from storage.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`ProposalState`|The state of the proposal: Canceled, Pending, Active, Defeated, Succeeded, Executed, Expired.| + + +### add256 + +*TODO: use OpenZeppelin's SafeMath function instead.* + + +```solidity +function add256(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### sub256 + +*TODO: use OpenZeppelin's SafeMath function instead.* + + +```solidity +function sub256(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### getChainId + +Retrieve CHAIN_ID of the executing chain. +Chain identifier (chainID) introduced in EIP-155 protects transaction +included into one chain from being included into another chain. +Basically, chain identifier is an integer number being used in the +processes of signing transactions and verifying transaction signatures. + +*As of version 0.5.12, Solidity includes an assembly function +chainid() that provides access to the new CHAINID opcode. +TODO: chainId is included in block. So you can get chain id like +block timestamp or block number: block.chainid;* + + +```solidity +function getChainId() internal pure returns (uint256); +``` + +## Events +### ProposalCreated +An event emitted when a new proposal is created. + + +```solidity +event ProposalCreated( + uint256 id, + address proposer, + address[] targets, + uint256[] values, + string[] signatures, + bytes[] calldatas, + uint256 startBlock, + uint256 endBlock, + string description +); +``` + +### VoteCast +An event emitted when a vote has been cast on a proposal. + + +```solidity +event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); +``` + +### ProposalCanceled +An event emitted when a proposal has been canceled. + + +```solidity +event ProposalCanceled(uint256 id); +``` + +### ProposalQueued +An event emitted when a proposal has been queued in the Timelock. + + +```solidity +event ProposalQueued(uint256 id, uint256 eta); +``` + +### ProposalExecuted +An event emitted when a proposal has been executed in the Timelock. + + +```solidity +event ProposalExecuted(uint256 id); +``` + +## Structs +### Proposal + +```solidity +struct Proposal { + uint256 id; + uint32 startBlock; + uint32 endBlock; + uint96 forVotes; + uint96 againstVotes; + uint96 quorum; + uint96 majorityPercentage; + uint64 eta; + uint64 startTime; + bool canceled; + bool executed; + address proposer; + address[] targets; + uint256[] values; + string[] signatures; + bytes[] calldatas; + mapping(address => Receipt) receipts; +} +``` + +### Receipt +Ballot receipt record for a voter + + +```solidity +struct Receipt { + bool hasVoted; + bool support; + uint96 votes; +} +``` + +## Enums +### ProposalState +Possible states that a proposal may be in. + + +```solidity +enum ProposalState { + Pending, + Active, + Canceled, + Defeated, + Succeeded, + Queued, + Expired, + Executed +} +``` + diff --git a/foundry/docs/src/contracts/governance/GovernorAlpha.sol/interface.StakingInterface.md b/foundry/docs/src/contracts/governance/GovernorAlpha.sol/interface.StakingInterface.md new file mode 100644 index 000000000..379cf7ce1 --- /dev/null +++ b/foundry/docs/src/contracts/governance/GovernorAlpha.sol/interface.StakingInterface.md @@ -0,0 +1,19 @@ +# StakingInterface +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/GovernorAlpha.sol) + + +## Functions +### getPriorVotes + + +```solidity +function getPriorVotes(address account, uint256 blockNumber, uint256 date) external view returns (uint96); +``` + +### getPriorTotalVotingPower + + +```solidity +function getPriorTotalVotingPower(uint32 blockNumber, uint256 time) external view returns (uint96); +``` + diff --git a/foundry/docs/src/contracts/governance/GovernorAlpha.sol/interface.TimelockInterface.md b/foundry/docs/src/contracts/governance/GovernorAlpha.sol/interface.TimelockInterface.md new file mode 100644 index 000000000..ac791537a --- /dev/null +++ b/foundry/docs/src/contracts/governance/GovernorAlpha.sol/interface.TimelockInterface.md @@ -0,0 +1,60 @@ +# TimelockInterface +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/GovernorAlpha.sol) + + +## Functions +### delay + + +```solidity +function delay() external view returns (uint256); +``` + +### GRACE_PERIOD + + +```solidity +function GRACE_PERIOD() external view returns (uint256); +``` + +### acceptAdmin + + +```solidity +function acceptAdmin() external; +``` + +### queuedTransactions + + +```solidity +function queuedTransactions(bytes32 hash) external view returns (bool); +``` + +### queueTransaction + + +```solidity +function queueTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) + external + returns (bytes32); +``` + +### cancelTransaction + + +```solidity +function cancelTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) + external; +``` + +### executeTransaction + + +```solidity +function executeTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) + external + payable + returns (bytes memory); +``` + diff --git a/foundry/docs/src/contracts/governance/GovernorVault.sol/contract.GovernorVault.md b/foundry/docs/src/contracts/governance/GovernorVault.sol/contract.GovernorVault.md new file mode 100644 index 000000000..c2ab66ff3 --- /dev/null +++ b/foundry/docs/src/contracts/governance/GovernorVault.sol/contract.GovernorVault.md @@ -0,0 +1,72 @@ +# GovernorVault +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/GovernorVault.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +This contract stores tokens and rBTC only transfereble by owner, +i.e. Sovryn governance. + + +## Functions +### transferTokens + +Transfer tokens. + + +```solidity +function transferTokens(address _receiver, address _token, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|The receiver of tokens.| +|`_token`|`address`|The address of token contract.| +|`_amount`|`uint256`|The amount to be transferred.| + + +### transferRbtc + +Transfer RBTC. + + +```solidity +function transferRbtc(address payable _receiver, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address payable`|The receiver of RBTC.| +|`_amount`|`uint256`|The amount to be transferred.| + + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external payable; +``` + +## Events +### Deposited + +```solidity +event Deposited(address indexed sender, uint256 amount); +``` + +### TokensTransferred + +```solidity +event TokensTransferred(address indexed receiver, address indexed token, uint256 amount); +``` + +### RbtcTransferred + +```solidity +event RbtcTransferred(address indexed receiver, uint256 amount); +``` + diff --git a/foundry/docs/src/contracts/governance/IFeeSharingCollector.sol/interface.IFeeSharingCollector.md b/foundry/docs/src/contracts/governance/IFeeSharingCollector.sol/interface.IFeeSharingCollector.md new file mode 100644 index 000000000..bf9979972 --- /dev/null +++ b/foundry/docs/src/contracts/governance/IFeeSharingCollector.sol/interface.IFeeSharingCollector.md @@ -0,0 +1,28 @@ +# IFeeSharingCollector +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/IFeeSharingCollector.sol) + +*Interfaces are used to cast a contract address into a callable instance.* + + +## Functions +### withdrawFees + + +```solidity +function withdrawFees(address[] calldata _token) external; +``` + +### transferTokens + + +```solidity +function transferTokens(address _token, uint96 _amount) external; +``` + +### withdraw + + +```solidity +function withdraw(address _loanPoolToken, uint32 _maxCheckpoints, address _receiver) external; +``` + diff --git a/foundry/docs/src/contracts/governance/README.md b/foundry/docs/src/contracts/governance/README.md new file mode 100644 index 000000000..85ae870e8 --- /dev/null +++ b/foundry/docs/src/contracts/governance/README.md @@ -0,0 +1,16 @@ + + +# Contents +- [FeeSharingCollector](/contracts/governance/FeeSharingCollector) +- [Staking](/contracts/governance/Staking) +- [StakingRewards](/contracts/governance/StakingRewards) +- [Vesting](/contracts/governance/Vesting) +- [ApprovalReceiver](ApprovalReceiver.sol/contract.ApprovalReceiver.md) +- [ErrorDecoder](ErrorDecoder.sol/contract.ErrorDecoder.md) +- [GovernorAlpha](GovernorAlpha.sol/contract.GovernorAlpha.md) +- [TimelockInterface](GovernorAlpha.sol/interface.TimelockInterface.md) +- [StakingInterface](GovernorAlpha.sol/interface.StakingInterface.md) +- [GovernorVault](GovernorVault.sol/contract.GovernorVault.md) +- [IFeeSharingCollector](IFeeSharingCollector.sol/interface.IFeeSharingCollector.md) +- [ITimelock](Timelock.sol/interface.ITimelock.md) +- [Timelock](Timelock.sol/contract.Timelock.md) diff --git a/foundry/docs/src/contracts/governance/Staking/README.md b/foundry/docs/src/contracts/governance/Staking/README.md new file mode 100644 index 000000000..34e74e170 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/README.md @@ -0,0 +1,7 @@ + + +# Contents +- [interfaces](/contracts/governance/Staking/interfaces) +- [modules](/contracts/governance/Staking/modules) +- [SafeMath96](SafeMath96.sol/contract.SafeMath96.md) +- [StakingProxy](StakingProxy.sol/contract.StakingProxy.md) diff --git a/foundry/docs/src/contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md b/foundry/docs/src/contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md new file mode 100644 index 000000000..f5f83b798 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md @@ -0,0 +1,138 @@ +# SafeMath96 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/SafeMath96.sol) + +Improved Solidity's arithmetic operations with added overflow checks. + +*SafeMath96 uses uint96, unsigned integers of 96 bits length, so every +integer from 0 to 2^96-1 can be operated. +Arithmetic operations in Solidity wrap on overflow. This can easily result +in bugs, because programmers usually assume that an overflow raises an +error, which is the standard behavior in high level programming languages. +SafeMath restores this intuition by reverting the transaction when an +operation overflows. +Using this contract instead of the unchecked operations eliminates an entire +class of bugs, so it's recommended to use it always.* + + +## Functions +### safe32 + + +```solidity +function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32); +``` + +### safe64 + + +```solidity +function safe64(uint256 n, string memory errorMessage) internal pure returns (uint64); +``` + +### safe96 + + +```solidity +function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96); +``` + +### add96 + +Adds two unsigned integers, reverting on overflow. + +*Counterpart to Solidity's `+` operator.* + + +```solidity +function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`a`|`uint96`|First integer.| +|`b`|`uint96`|Second integer.| +|`errorMessage`|`string`|The revert message on overflow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The safe addition a+b.| + + +### sub96 + +Substracts two unsigned integers, reverting on underflow. + +*Counterpart to Solidity's `-` operator.* + + +```solidity +function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`a`|`uint96`|First integer.| +|`b`|`uint96`|Second integer.| +|`errorMessage`|`string`|The revert message on underflow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The safe substraction a-b.| + + +### mul96 + +Multiplies two unsigned integers, reverting on overflow. + +*Counterpart to Solidity's `*` operator.* + + +```solidity +function mul96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`a`|`uint96`|First integer.| +|`b`|`uint96`|Second integer.| +|`errorMessage`|`string`|The revert message on overflow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The safe product a*b.| + + +### div96 + +Divides two unsigned integers, reverting on overflow. + +*Counterpart to Solidity's `/` operator.* + + +```solidity +function div96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`a`|`uint96`|First integer.| +|`b`|`uint96`|Second integer.| +|`errorMessage`|`string`|The revert message on overflow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The safe division a/b.| + + diff --git a/foundry/docs/src/contracts/governance/Staking/StakingProxy.sol/contract.StakingProxy.md b/foundry/docs/src/contracts/governance/Staking/StakingProxy.sol/contract.StakingProxy.md new file mode 100644 index 000000000..1af8686d6 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/StakingProxy.sol/contract.StakingProxy.md @@ -0,0 +1,28 @@ +# StakingProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/StakingProxy.sol) + +**Inherits:** +[StakingStorageShared](/contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md), [UpgradableProxy](/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + +*Staking contract should be upgradable, use UpgradableProxy. +StakingStorage is deployed with the upgradable functionality +by using this contract instead, that inherits from UpgradableProxy +the possibility of being enhanced and re-deployed.* + + +## Functions +### constructor + +Construct a new staking contract. + + +```solidity +constructor(address SOV) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`SOV`|`address`|The address of the SOV token address.| + + diff --git a/foundry/docs/src/contracts/governance/Staking/interfaces/IStaking.sol/interface.IStaking.md b/foundry/docs/src/contracts/governance/Staking/interfaces/IStaking.sol/interface.IStaking.md new file mode 100644 index 000000000..452c78fcf --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/interfaces/IStaking.sol/interface.IStaking.md @@ -0,0 +1,1379 @@ +# IStaking +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/interfaces/IStaking.sol) + + +## Functions +### addAdmin + +StakingAdminModule ************************** + +Add account to Admins ACL. + + +```solidity +function addAdmin(address _admin) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to grant permissions.| + + +### removeAdmin + +Remove account from Admins ACL. + + +```solidity +function removeAdmin(address _admin) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to revoke permissions.| + + +### addPauser + +Add account to pausers ACL. + + +```solidity +function addPauser(address _pauser) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_pauser`|`address`|The address to grant pauser permissions.| + + +### removePauser + +Remove account from pausers ACL. + + +```solidity +function removePauser(address _pauser) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_pauser`|`address`|The address to grant pauser permissions.| + + +### pauseUnpause + +Pause/unpause contract + + +```solidity +function pauseUnpause(bool _pause) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_pause`|`bool`|true when pausing, false when unpausing| + + +### freezeUnfreeze + +Freeze contract - disable all functions + +*When freezing, pause is always applied too. When unfreezing, the contract is left in paused stated.* + + +```solidity +function freezeUnfreeze(bool _freeze) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_freeze`|`bool`|true when freezing, false when unfreezing| + + +### setFeeSharing + +Allows the owner to set a fee sharing proxy contract. +We need it for unstaking with slashing. + + +```solidity +function setFeeSharing(address _feeSharing) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_feeSharing`|`address`|The address of FeeSharingCollectorProxy contract.| + + +### setWeightScaling + +Allow the owner to set weight scaling. +We need it for unstaking with slashing. + + +```solidity +function setWeightScaling(uint96 _weightScaling) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_weightScaling`|`uint96`|The weight scaling.| + + +### setNewStakingContract + +Allow the owner to set a new staking contract. +As a consequence it allows the stakers to migrate their positions +to the new contract. + +*Doesn't have any influence as long as migrateToNewStakingContract +is not implemented.* + + +```solidity +function setNewStakingContract(address _newStakingContract) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newStakingContract`|`address`|The address of the new staking contract.| + + +### migrateToNewStakingContract + +Allow a staker to migrate his positions to the new staking contract. + +*Staking contract needs to be set before by the owner. +Currently not implemented, just needed for the interface. +In case it's needed at some point in the future, +the implementation needs to be changed first.* + + +```solidity +function migrateToNewStakingContract() external; +``` + +### getPriorTotalVotingPower + +StakingGovernanceModule ************************** + +Compute the total voting power at a given time. + + +```solidity +function getPriorTotalVotingPower(uint32 blockNumber, uint256 time) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`blockNumber`|`uint32`|The block number, needed for checkpointing.| +|`time`|`uint256`|The timestamp for which to calculate the total voting power.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The total voting power at the given time.| + + +### getCurrentVotes + +Get the current votes balance for a user account. + +*This is a wrapper to simplify arguments. The actual computation is +performed on WeightedStaking parent contract.* + + +```solidity +function getCurrentVotes(address account) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address to get votes balance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of current votes for a user account.| + + +### getPriorVotes + +Determine the prior number of votes for a delegatee as of a block number. +Iterate through checkpoints adding up voting power. + +*Block number must be a finalized block or else this function will revert +to prevent misinformation. +Used for Voting, not for fee sharing.* + + +```solidity +function getPriorVotes(address account, uint256 blockNumber, uint256 date) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| +|`date`|`uint256`|The staking date to compute the power for.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the delegatee had as of the given block.| + + +### getPriorStakeByDateForDelegatee + +Determine the prior number of stake for an account as of a block number. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation.* + + +```solidity +function getPriorStakeByDateForDelegatee(address account, uint256 date, uint256 blockNumber) + external + view + returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`date`|`uint256`|The staking date to compute the power for.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### getPriorTotalStakesForDate + +Determine the prior number of stake for an unlocking date as of a block number. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation. +TODO: WeightedStaking::getPriorTotalStakesForDate should probably better +be internal instead of a public function.* + + +```solidity +function getPriorTotalStakesForDate(uint256 date, uint256 blockNumber) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The date to check the stakes for.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### delegate + +Delegate votes from `msg.sender` which are locked until lockDate to `delegatee`. + + +```solidity +function delegate(address delegatee, uint256 lockDate) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`delegatee`|`address`|The address to delegate votes to.| +|`lockDate`|`uint256`|the date if the position to delegate.| + + +### stake + +Stake the given amount for the given duration of time. + + +```solidity +function stake(uint96 amount, uint256 until, address stakeFor, address delegatee) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to stake.| +|`until`|`uint256`|Timestamp indicating the date until which to stake.| +|`stakeFor`|`address`|The address to stake the tokens for or 0x0 if staking for oneself.| +|`delegatee`|`address`|The address of the delegatee or 0x0 if there is none.| + + +### stakeWithApproval + +Stake the given amount for the given duration of time. + +*This function will be invoked from receiveApproval* + +*SOV.approveAndCall -> this.receiveApproval -> this.stakeWithApproval* + + +```solidity +function stakeWithApproval(address sender, uint96 amount, uint256 until, address stakeFor, address delegatee) + external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sender`|`address`|The sender of SOV.approveAndCall| +|`amount`|`uint96`|The number of tokens to stake.| +|`until`|`uint256`|Timestamp indicating the date until which to stake.| +|`stakeFor`|`address`|The address to stake the tokens for or 0x0 if staking for oneself.| +|`delegatee`|`address`|The address of the delegatee or 0x0 if there is none.| + + +### receiveApproval + +Receives approval from SOV token. + + +```solidity +function receiveApproval(address _sender, uint256 _amount, address _token, bytes calldata _data) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|| +|`_amount`|`uint256`|| +|`_token`|`address`|| +|`_data`|`bytes`|The data will be used for low level call.| + + +### extendStakingDuration + +Extend the staking duration until the specified date. + + +```solidity +function extendStakingDuration(uint256 previousLock, uint256 until) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`previousLock`|`uint256`|The old unlocking timestamp.| +|`until`|`uint256`|The new unlocking timestamp in seconds.| + + +### stakesBySchedule + +*DO NOT USE this misspelled function. Use stakeBySchedule function instead. +This function cannot be deprecated while we have non-upgradeable vesting contracts.* + + +```solidity +function stakesBySchedule( + uint256 amount, + uint256 cliff, + uint256 duration, + uint256 intervalLength, + address stakeFor, + address delegatee +) external; +``` + +### stakeBySchedule + +Stake tokens according to the vesting schedule. + + +```solidity +function stakeBySchedule( + uint256 amount, + uint256 cliff, + uint256 duration, + uint256 intervalLength, + address stakeFor, + address delegatee +) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint256`|The amount of tokens to stake.| +|`cliff`|`uint256`|The time interval to the first withdraw.| +|`duration`|`uint256`|The staking duration.| +|`intervalLength`|`uint256`|The length of each staking interval when cliff passed.| +|`stakeFor`|`address`|The address to stake the tokens for or 0x0 if staking for oneself.| +|`delegatee`|`address`|The address of the delegatee or 0x0 if there is none.| + + +### balanceOf + +Get the number of staked tokens held by the user account. + +*Iterate checkpoints adding up stakes.* + + +```solidity +function balanceOf(address account) external view returns (uint96 balance); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to get the balance of.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`balance`|`uint96`|The number of tokens held.| + + +### getCurrentStakedUntil + +Get the current number of tokens staked for a day. + + +```solidity +function getCurrentStakedUntil(uint256 lockedTS) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The timestamp to get the staked tokens for.| + + +### getStakes + +Get list of stakes for a user account. + + +```solidity +function getStakes(address account) external view returns (uint256[] memory dates, uint96[] memory stakes); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address to get stakes.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`dates`|`uint256[]`|The arrays of dates and stakes.| +|`stakes`|`uint96[]`|| + + +### timestampToLockDate + +Unstaking is possible every 2 weeks only. This means, to +calculate the key value for the staking checkpoints, we need to +map the intended timestamp to the closest available date. + + +```solidity +function timestampToLockDate(uint256 timestamp) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`timestamp`|`uint256`|The unlocking timestamp.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The actual unlocking date (might be up to 2 weeks shorter than intended).| + + +### getStorageMaxDurationToStakeTokens + +StakingStorageModule ************************** + +The maximum duration to stake tokens + + +```solidity +function getStorageMaxDurationToStakeTokens() external pure returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|MAX_DURATION to stake tokens| + + +### getStorageMaxVotingWeight + +The maximum possible voting weight before adding +1 (actually 10, but need 9 for computation). + + +```solidity +function getStorageMaxVotingWeight() external pure returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|uint256(MAX_VOTING_WEIGHT);| + + +### getStorageWeightFactor + +weight is multiplied with this factor (for allowing decimals, like 1.2x). + +*MAX_VOTING_WEIGHT * WEIGHT_FACTOR needs to be < 792, because there are 100,000,000 SOV with 18 decimals* + + +```solidity +function getStorageWeightFactor() external pure returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|uint256(WEIGHT_FACTOR);| + + +### getStorageDefaultWeightScaling + + +```solidity +function getStorageDefaultWeightScaling() external pure returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|uint256(DEFAULT_WEIGHT_SCALING);| + + +### getStorageRangeForWeightScaling + +return (uint256(MIN_WEIGHT_SCALING), uint256(MAX_WEIGHT_SCALING)) + + +```solidity +function getStorageRangeForWeightScaling() external pure returns (uint256 minWeightScaling, uint256 maxWeightScaling); +``` + +### getStorageDomainTypehash + +The EIP-712 typehash for the contract's domain. + + +```solidity +function getStorageDomainTypehash() external pure returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|uint256(DOMAIN_TYPEHASH);| + + +### getStorageDelegationTypehash + +The EIP-712 typehash for the delegation struct used by the contract. + + +```solidity +function getStorageDelegationTypehash() external pure returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|uint256(DELEGATION_TYPEHASH);| + + +### getStorageName + + +```solidity +function getStorageName() external view returns (string memory); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`string`|name;| + + +### kickoffTS + +AUTOGENERATED FUNCTIONS FROM THE STAKING STORAGE PUBLIC VARIABLES /// + +The timestamp of contract creation. Base for the staking period calculation. + + +```solidity +function kickoffTS() external view returns (uint256); +``` + +### SOVToken + +The token to be staked + + +```solidity +function SOVToken() external view returns (address); +``` + +### delegates + +Stakers delegated voting power + + +```solidity +function delegates(address staker, uint256 until) external view returns (address _delegate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`staker`|`address`|- the delegating address| +|`until`|`uint256`|- delegated voting| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_delegate`|`address`|- voting power delegated to address| + + +### allUnlocked + +If this flag is set to true, all tokens are unlocked immediately +see function unlockAllTokens() for details + + +```solidity +function allUnlocked() external view returns (bool); +``` + +### newStakingContract + +Used for stake migrations to a new staking contract with a different storage structure + + +```solidity +function newStakingContract() external view returns (address); +``` + +### totalStakingCheckpoints + +A record of tokens to be unstaked at a given time in total. +For total voting power computation. Voting weights get adjusted bi-weekly. + +*totalStakingCheckpoints[date][index] is a checkpoint* + + +```solidity +function totalStakingCheckpoints(uint256 date, uint32 index) external view returns (Checkpoint memory); +``` + +### numTotalStakingCheckpoints + +The number of total staking checkpoints for each date. + +*numTotalStakingCheckpoints[date] is a number.* + + +```solidity +function numTotalStakingCheckpoints(uint256 date) external view returns (uint32 checkpointsQty); +``` + +### delegateStakingCheckpoints + +A record of tokens to be unstaked at a given time which were delegated to a certain address. +For delegatee voting power computation. Voting weights get adjusted bi-weekly. + +*delegateStakingCheckpoints[delegatee][date][index] is a checkpoint.* + + +```solidity +function delegateStakingCheckpoints(address delagatee, uint256 date, uint32 index) + external + view + returns (Checkpoint memory); +``` + +### numDelegateStakingCheckpoints + +The number of total staking checkpoints for each date per delegate. + +*numDelegateStakingCheckpoints[delegatee][date] is a number.* + + +```solidity +function numDelegateStakingCheckpoints(address delegatee, uint256 date) external view returns (uint32 checkpointsQty); +``` + +### userStakingCheckpoints + +A record of tokens to be unstaked at a given time which per user address (address -> lockDate -> stake checkpoint) + +*userStakingCheckpoints[user][date][index] is a checkpoint.* + + +```solidity +function userStakingCheckpoints(address user, uint256 date, uint32 index) external view returns (Checkpoint memory); +``` + +### numUserStakingCheckpoints + +The number of total staking checkpoints for each date per user. + +*numUserStakingCheckpoints[user][date] is a number* + + +```solidity +function numUserStakingCheckpoints(address user, uint256 date) external view returns (uint32 checkpointsQty); +``` + +### nonces + +A record of states for signing / validating signatures + +*nonces[user] is a number.* + + +```solidity +function nonces(address user) external view returns (uint256 nonce); +``` + +### feeSharing + +SLASHING /// + +the address of FeeSharingCollectorProxy contract, we need it for unstaking with slashing. + + +```solidity +function feeSharing() external view returns (address); +``` + +### weightScaling + +used for weight scaling when unstaking with slashing. + + +```solidity +function weightScaling() external view returns (uint96); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|uint96 DEFAULT_WEIGHT_SCALING| + + +### vestingWhitelist + +List of vesting contracts, tokens for these contracts won't be slashed if unstaked by governance. + +*vestingWhitelist[contract] is true/false.* + + +```solidity +function vestingWhitelist(address isWhitelisted) external view returns (bool); +``` + +### admins + +*user => flag whether user has admin role.* + +*multisig should be an admin, admin can invoke only governanceWithdrawVesting function, +this function works only with Team Vesting contracts* + + +```solidity +function admins(address isAdmin) external view returns (bool); +``` + +### vestingCodeHashes + +*vesting contract code hash => flag whether it's registered code hash* + + +```solidity +function vestingCodeHashes(bytes32 vestingLogicCodeHash) external view returns (bool); +``` + +### vestingCheckpoints + +A record of tokens to be unstaked from vesting contract at a given time (lockDate -> vest checkpoint) + +*vestingCheckpoints[date][index] is a checkpoint.* + + +```solidity +function vestingCheckpoints(uint256 date, uint32 index) external view returns (Checkpoint memory); +``` + +### numVestingCheckpoints + +The number of total vesting checkpoints for each date. + +*numVestingCheckpoints[date] is a number.* + + +```solidity +function numVestingCheckpoints(uint256 date) external view returns (uint32 checkpointsQty); +``` + +### vestingRegistryLogic + +vesting registry contract PROXY address + + +```solidity +function vestingRegistryLogic() external view returns (address); +``` + +### pausers + +*user => flag whether user has pauser role.* + + +```solidity +function pausers(address isPauser) external view returns (bool); +``` + +### paused + +*Staking contract is paused* + + +```solidity +function paused() external view returns (bool); +``` + +### frozen + +*Staking contract is frozen* + + +```solidity +function frozen() external view returns (bool); +``` + +### isVestingContract + +Return flag whether the given address is a registered vesting contract. + + +```solidity +function isVestingContract(address stakerAddress) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`stakerAddress`|`address`|the address to check| + + +### removeContractCodeHash + +Remove vesting contract's code hash to a map of code hashes. + +*We need it to use isVestingContract() function instead of isContract()* + + +```solidity +function removeContractCodeHash(address vesting) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The address of Vesting contract.| + + +### addContractCodeHash + +Add vesting contract's code hash to a map of code hashes. + +*We need it to use isVestingContract() function instead of isContract()* + + +```solidity +function addContractCodeHash(address vesting) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The address of Vesting contract.| + + +### getPriorVestingStakeByDate + +Determine the prior number of vested stake for an account until a +certain lock date as of a block number. + +*Block number must be a finalized block or else this function +will revert to prevent misinformation.* + + +```solidity +function getPriorVestingStakeByDate(uint256 date, uint256 blockNumber) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The lock date.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### weightedVestingStakeByDate + +Compute the voting power for a specific date. +Power = stake * weight + + +```solidity +function weightedVestingStakeByDate(uint256 date, uint256 startDate, uint256 blockNumber) + external + view + returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The staking date to compute the power for. Adjusted to the next valid lock date, if necessary.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The stacking power.| + + +### getPriorVestingWeightedStake + +Determine the prior weighted vested amount for an account as of a block number. +Iterate through checkpoints adding up voting power. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation. +Used for fee sharing, not voting. +TODO: WeightedStaking::getPriorVestingWeightedStake is using the variable name "votes" +to add up token stake, and that could be misleading.* + + +```solidity +function getPriorVestingWeightedStake(uint256 blockNumber, uint256 date) external view returns (uint96 votes); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| +|`date`|`uint256`|The staking date to compute the power for.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`votes`|`uint96`|The weighted stake the account had as of the given block.| + + +### getPriorUserStakeByDate + +Determine the prior number of stake for an account until a +certain lock date as of a block number. + +*Block number must be a finalized block or else this function +will revert to prevent misinformation.* + + +```solidity +function getPriorUserStakeByDate(address account, uint256 date, uint256 blockNumber) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`date`|`uint256`|The lock date.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### setVestingStakes + +Sets the users' vesting stakes for a giving lock dates and writes checkpoints. + + +```solidity +function setVestingStakes(uint256[] calldata lockedDates, uint96[] calldata values) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedDates`|`uint256[]`|The arrays of lock dates.| +|`values`|`uint96[]`|The array of values to add to the staked balance.| + + +### setVestingRegistry + +sets vesting registry + +*_vestingRegistryProxy can be set to 0 as this function can be reused by +various other functionalities without the necessity of linking it with Vesting Registry* + + +```solidity +function setVestingRegistry(address _vestingRegistryProxy) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingRegistryProxy`|`address`|the address of vesting registry proxy contract| + + +### withdraw + +StakingWithdrawModule ************************** + +Withdraw the given amount of tokens if they are unlocked. + + +```solidity +function withdraw(uint96 amount, uint256 until, address receiver) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender| + + +### governanceWithdraw + +Withdraw the given amount of tokens. + +*Can be invoked only by whitelisted contract passed to governanceWithdrawVesting* + +***WARNING** This function should not be no longer used by Sovryn Protocol. +Sovryn protocol will use the cancelTeamVesting function for the withdrawal moving forward.* + + +```solidity +function governanceWithdraw(uint96 amount, uint256 until, address receiver) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender| + + +### governanceWithdrawVesting + +Withdraw tokens for vesting contract. + +*Can be invoked only by whitelisted contract passed to governanceWithdrawVesting.* + + +```solidity +function governanceWithdrawVesting(address vesting, address receiver) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The address of Vesting contract.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender| + + +### getWithdrawAmounts + +Get available and punished amount for withdrawing. + + +```solidity +function getWithdrawAmounts(uint96 amount, uint256 until) external view returns (uint96, uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| + + +### unlockAllTokens + +Allow the owner to unlock all tokens in case the staking contract +is going to be replaced +Note: Not reversible on purpose. once unlocked, everything is unlocked. +The owner should not be able to just quickly unlock to withdraw his own +tokens and lock again. + +*Last resort.* + + +```solidity +function unlockAllTokens() external; +``` + +### getPriorWeightedStake + +WeightedStakingModule ************************** + +Determine the prior weighted stake for an account as of a block number. +Iterate through checkpoints adding up voting power. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation. +Used for fee sharing, not voting.* + + +```solidity +function getPriorWeightedStake(address account, uint256 blockNumber, uint256 date) + external + view + returns (uint96 priorWeightedStake); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| +|`date`|`uint256`|The date/timestamp of the unstaking time.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`priorWeightedStake`|`uint96`|The weighted stake the account had as of the given block.| + + +### weightedStakeByDate + +Compute the voting power for a specific date. +Power = stake * weight +TODO: WeightedStaking::weightedStakeByDate should probably better +be internal instead of a public function. + + +```solidity +function weightedStakeByDate(address account, uint256 date, uint256 startDate, uint256 blockNumber) + external + view + returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The user address.| +|`date`|`uint256`|The staking date to compute the power for.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The stacking power.| + + +### computeWeightByDate + +Compute the weight for a specific date. + + +```solidity +function computeWeightByDate(uint256 date, uint256 startDate) external pure returns (uint96 weight); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The unlocking date.| +|`startDate`|`uint256`|We compute the weight for the tokens staked until 'date' on 'startDate'.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`weight`|`uint96`|The weighted stake the account had as of the given block.| + + +### MAX_DURATION + +Returns public constant MAX_DURATION +preserved for backwards compatibility +Use getStorageMaxDurationToStakeTokens() + + +```solidity +function MAX_DURATION() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|uint96 MAX_DURATION for staking| + + +### owner + +*Returns the address of the current owner.* + + +```solidity +function owner() external view returns (address); +``` + +### isOwner + +*Returns true if the caller is the current owner.* + + +```solidity +function isOwner() external view returns (bool); +``` + +### transferOwnership + +*Transfers ownership of the contract to a new account (`newOwner`). +Can only be called by the current owner.* + + +```solidity +function transferOwnership(address newOwner) external; +``` + +### cancelTeamVesting + +Governance withdraw vesting directly through staking contract. +This direct withdraw vesting solves the out of gas issue when there are too many iterations when withdrawing. +This function only allows cancelling vesting contract of the TeamVesting type. + + +```solidity +function cancelTeamVesting(address vesting, address receiver, uint256 startFrom) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The vesting address.| +|`receiver`|`address`|The receiving address.| +|`startFrom`|`uint256`|The start value for the iterations.| + + +### getMaxVestingWithdrawIterations + +Max iteration for direct withdrawal from staking to prevent out of gas issue. + + +```solidity +function getMaxVestingWithdrawIterations() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|max iteration value.| + + +### setMaxVestingWithdrawIterations + +*set max withdraw iterations.* + + +```solidity +function setMaxVestingWithdrawIterations(uint256 maxIterations) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`maxIterations`|`uint256`|new max iterations value.| + + +## Events +### TokensStaked +StakingStakeModule ************************** + + +```solidity +event TokensStaked(address indexed staker, uint256 amount, uint256 lockedUntil, uint256 totalStaked); +``` + +### VestingStakeSet +StakingVestingModule ************************** + + +```solidity +event VestingStakeSet(uint256 lockedTS, uint96 value); +``` + +## Structs +### Checkpoint +CHECKPOINTS + + +```solidity +struct Checkpoint { + uint32 fromBlock; + uint96 stake; +} +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/interfaces/README.md b/foundry/docs/src/contracts/governance/Staking/interfaces/README.md new file mode 100644 index 000000000..6dabef2a9 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/interfaces/README.md @@ -0,0 +1,4 @@ + + +# Contents +- [IStaking](IStaking.sol/interface.IStaking.md) diff --git a/foundry/docs/src/contracts/governance/Staking/modules/README.md b/foundry/docs/src/contracts/governance/Staking/modules/README.md new file mode 100644 index 000000000..74a10d525 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/README.md @@ -0,0 +1,11 @@ + + +# Contents +- [shared](/contracts/governance/Staking/modules/shared) +- [StakingAdminModule](StakingAdminModule.sol/contract.StakingAdminModule.md) +- [StakingGovernanceModule](StakingGovernanceModule.sol/contract.StakingGovernanceModule.md) +- [StakingStakeModule](StakingStakeModule.sol/contract.StakingStakeModule.md) +- [StakingStorageModule](StakingStorageModule.sol/contract.StakingStorageModule.md) +- [StakingVestingModule](StakingVestingModule.sol/contract.StakingVestingModule.md) +- [StakingWithdrawModule](StakingWithdrawModule.sol/contract.StakingWithdrawModule.md) +- [WeightedStakingModule](WeightedStakingModule.sol/contract.WeightedStakingModule.md) diff --git a/foundry/docs/src/contracts/governance/Staking/modules/StakingAdminModule.sol/contract.StakingAdminModule.md b/foundry/docs/src/contracts/governance/Staking/modules/StakingAdminModule.sol/contract.StakingAdminModule.md new file mode 100644 index 000000000..d20dcaa90 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/StakingAdminModule.sol/contract.StakingAdminModule.md @@ -0,0 +1,238 @@ +# StakingAdminModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/StakingAdminModule.sol) + +**Inherits:** +[IFunctionsList](/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md), [StakingShared](/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md) + +Implements administrative functionality pause, freeze and setting addresses and parameters +related to staking + + +## Functions +### addAdmin + +Add account to Admins ACL. + + +```solidity +function addAdmin(address _admin) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to grant permissions.| + + +### removeAdmin + +Remove account from Admins ACL. + + +```solidity +function removeAdmin(address _admin) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to revoke permissions.| + + +### addPauser + +Add account to pausers ACL. + + +```solidity +function addPauser(address _pauser) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_pauser`|`address`|The address to grant pauser permissions.| + + +### removePauser + +Remove account from pausers ACL. + + +```solidity +function removePauser(address _pauser) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_pauser`|`address`|The address to grant pauser permissions.| + + +### pauseUnpause + +Pause/unpause contract + + +```solidity +function pauseUnpause(bool _pause) public onlyPauserOrOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_pause`|`bool`|true when pausing, false when unpausing| + + +### freezeUnfreeze + +Freeze contract - disable all functions + +*When freezing, pause is always applied too. When unfreezing, the contract is left in paused stated.* + + +```solidity +function freezeUnfreeze(bool _freeze) external onlyPauserOrOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_freeze`|`bool`|true when freezing, false when unfreezing| + + +### setFeeSharing + +Allow the owner to set a fee sharing proxy contract. +We need it for unstaking with slashing. + + +```solidity +function setFeeSharing(address _feeSharing) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_feeSharing`|`address`|The address of FeeSharingCollectorProxy contract.| + + +### setWeightScaling + +Allow the owner to set weight scaling. +We need it for unstaking with slashing. + + +```solidity +function setWeightScaling(uint96 _weightScaling) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_weightScaling`|`uint96`|The weight scaling.| + + +### setNewStakingContract + +Allow the owner to set a new staking contract. +As a consequence it allows the stakers to migrate their positions +to the new contract. + +*Doesn't have any influence as long as migrateToNewStakingContract +is not implemented.* + + +```solidity +function setNewStakingContract(address _newStakingContract) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newStakingContract`|`address`|The address of the new staking contract.| + + +### migrateToNewStakingContract + +Allow a staker to migrate his positions to the new staking contract. + +*Staking contract needs to be set before by the owner. +Currently not implemented, just needed for the interface. +In case it's needed at some point in the future, +the implementation needs to be changed first.* + + +```solidity +function migrateToNewStakingContract() external whenNotFrozen; +``` + +### getFunctionsList + +*implementation:* + +*Iterate over all possible lock dates from now until now + MAX_DURATION.* + +*Read the stake & delegate of the msg.sender* + +*If stake > 0, stake it at the new contract until the lock date with the current delegate.* + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory); +``` + +## Events +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + +### PauserAddedOrRemoved + +```solidity +event PauserAddedOrRemoved(address indexed pauser, bool indexed added); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`pauser`|`address`|address to grant power to pause the contract| +|`added`|`bool`|true - added, false - removed| + +### StakingPaused +An event emitted when a staking is paused or unpaused + + +```solidity +event StakingPaused(bool indexed setPaused); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`setPaused`|`bool`|true - pause, false - unpause| + +### StakingFrozen +An event emitted when a staking is frozen or unfrozen + + +```solidity +event StakingFrozen(bool indexed setFrozen); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`setFrozen`|`bool`|true - freeze, false - unfreeze| + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/StakingGovernanceModule.sol/contract.StakingGovernanceModule.md b/foundry/docs/src/contracts/governance/Staking/modules/StakingGovernanceModule.sol/contract.StakingGovernanceModule.md new file mode 100644 index 000000000..5241aa1fa --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/StakingGovernanceModule.sol/contract.StakingGovernanceModule.md @@ -0,0 +1,351 @@ +# StakingGovernanceModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/StakingGovernanceModule.sol) + +**Inherits:** +[IFunctionsList](/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md), [StakingShared](/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md), [CheckpointsShared](/contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md) + +Implements voting power and delegation functionality + + +## Functions +### getPriorTotalVotingPower + +TOTAL VOTING POWER COMPUTATION *********************** + +Compute the total voting power at a given time. + + +```solidity +function getPriorTotalVotingPower(uint32 blockNumber, uint256 time) public view returns (uint96 totalVotingPower); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`blockNumber`|`uint32`|The block number, needed for checkpointing.| +|`time`|`uint256`|The timestamp for which to calculate the total voting power.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`totalVotingPower`|`uint96`|The total voting power at the given time.| + + +### _totalPowerByDate + +Compute the voting power for a specific date. +Power = stake * weight + +*Start the computation with the exact or previous unlocking date (voting weight remians the same until the next break point).* + +*Max 78 iterations.* + + +```solidity +function _totalPowerByDate(uint256 date, uint256 startDate, uint256 blockNumber) internal view returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The staking date to compute the power for.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The stacking power.| + + +### getCurrentVotes + +Get the current votes balance for a user account. + +*weight is multiplied by some factor to allow decimals. +DELEGATED VOTING POWER COMPUTATION ************************ + +*This is a wrapper to simplify arguments. The actual computation is +performed on WeightedStaking parent contract.* + + +```solidity +function getCurrentVotes(address account) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address to get votes balance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of current votes for a user account.| + + +### getPriorVotes + +Determine the prior number of votes for a delegatee as of a block number. +Iterate through checkpoints adding up voting power. + +*Block number must be a finalized block or else this function will revert +to prevent misinformation. +Used for Voting, not for fee sharing.* + + +```solidity +function getPriorVotes(address account, uint256 blockNumber, uint256 date) public view returns (uint96 votes); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| +|`date`|`uint256`|The staking date to compute the power for.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`votes`|`uint96`|The number of votes the delegatee had as of the given block.| + + +### _totalPowerByDateForDelegatee + +Compute the voting power for a specific date. +Power = stake * weight + +*If date is not an exact break point, start weight computation from the previous break point (alternative would be the next).* + +*Max 78 iterations.* + + +```solidity +function _totalPowerByDateForDelegatee(address account, uint256 date, uint256 startDate, uint256 blockNumber) + internal + view + returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`date`|`uint256`|The staking date to compute the power for.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The stacking power.| + + +### getPriorStakeByDateForDelegatee + +Determine the prior number of stake for an account as of a block number. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation.* + + +```solidity +function getPriorStakeByDateForDelegatee(address account, uint256 date, uint256 blockNumber) + external + view + returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`date`|`uint256`|The staking date to compute the power for. Adjusted to the next valid lock date, if necessary.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### _getPriorStakeByDateForDelegatee + +Determine the prior number of stake for an account as of a block number. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation.* + + +```solidity +function _getPriorStakeByDateForDelegatee(address account, uint256 date, uint256 blockNumber) + internal + view + returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`date`|`uint256`|The staking date to compute the power for.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### getPriorTotalStakesForDate + +Determine the prior number of stake for an unlocking date as of a block number. + +*First check most recent balance.* + +*Next check implicit zero balance.* + +*ceil, avoiding overflow. +SHARED FUNCTIONS ********************* + +*Block number must be a finalized block or else this function will +revert to prevent misinformation.* + + +```solidity +function getPriorTotalStakesForDate(uint256 date, uint256 blockNumber) public view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The date to check the stakes for. Adjusted to the next valid lock date, as necessary| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The total number of votes as of the given block.| + + +### _getPriorTotalStakesForDate + +Determine the prior number of stake for an unlocking date as of a block number. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation.* + + +```solidity +function _getPriorTotalStakesForDate(uint256 date, uint256 blockNumber) internal view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The date to check the stakes for.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The total number of votes as of the given block.| + + +### _delegate + +Set new delegatee. Move from user's current delegate to a new +delegatee the stake balance. + +*Reverts if delegator balance or delegatee is not valid, unless the sender is a vesting contract.* + + +```solidity +function _delegate(address delegator, address delegatee, uint256 lockedTS) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`delegator`|`address`|The user address to move stake balance from its current delegatee.| +|`delegatee`|`address`|The new delegatee. The address to move stake balance to.| +|`lockedTS`|`uint256`|The lock date.| + + +### _delegateNext + + +```solidity +function _delegateNext(address delegator, address delegatee, uint256 lockedTS) internal; +``` + +### _moveDelegates + +Move an amount of delegate stake from a source address to a +destination address. + + +```solidity +function _moveDelegates(address srcRep, address dstRep, uint96 amount, uint256 lockedTS) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`srcRep`|`address`|The address to get the staked amount from.| +|`dstRep`|`address`|The address to send the staked amount to.| +|`amount`|`uint96`|The staked amount to move.| +|`lockedTS`|`uint256`|The lock date.| + + +### _getChainId + +Retrieve CHAIN_ID of the executing chain. +Chain identifier (chainID) introduced in EIP-155 protects transaction +included into one chain from being included into another chain. +Basically, chain identifier is an integer number being used in the +processes of signing transactions and verifying transaction signatures. + +*As of version 0.5.12, Solidity includes an assembly function +chainid() that provides access to the new CHAINID opcode. +TODO: chainId is included in block. So you can get chain id like +block timestamp or block number: block.chainid;* + + +```solidity +function _getChainId() internal pure returns (uint256); +``` + +### delegate + +Delegate votes from `msg.sender` which are locked until lockDate to `delegatee`. + + +```solidity +function delegate(address delegatee, uint256 lockDate) external whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`delegatee`|`address`|The address to delegate votes to.| +|`lockDate`|`uint256`|the date if the position to delegate.| + + +### getFunctionsList + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory); +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/StakingStakeModule.sol/contract.StakingStakeModule.md b/foundry/docs/src/contracts/governance/Staking/modules/StakingStakeModule.sol/contract.StakingStakeModule.md new file mode 100644 index 000000000..274fcc549 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/StakingStakeModule.sol/contract.StakingStakeModule.md @@ -0,0 +1,402 @@ +# StakingStakeModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/StakingStakeModule.sol) + +**Inherits:** +[IFunctionsList](/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md), [StakingShared](/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md), [CheckpointsShared](/contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md), [ApprovalReceiver](/contracts/governance/ApprovalReceiver.sol/contract.ApprovalReceiver.md) + +Implements staking functionality + + +## Functions +### stake + +Stake the given amount for the given duration of time. + + +```solidity +function stake(uint96 amount, uint256 until, address stakeFor, address delegatee) + external + whenNotPaused + whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to stake.| +|`until`|`uint256`|Timestamp indicating the date until which to stake.| +|`stakeFor`|`address`|The address to stake the tokens for or 0x0 if staking for oneself.| +|`delegatee`|`address`|The address of the delegatee or 0x0 if there is none.| + + +### stakeWithApproval + +Stake the given amount for the given duration of time. + +*This function will be invoked from receiveApproval* + +*SOV.approveAndCall -> this.receiveApproval -> this.stakeWithApproval* + + +```solidity +function stakeWithApproval(address sender, uint96 amount, uint256 until, address stakeFor, address delegatee) + external + onlyThisContract + whenNotPaused + whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sender`|`address`|The sender of SOV.approveAndCall| +|`amount`|`uint96`|The number of tokens to stake.| +|`until`|`uint256`|Timestamp indicating the date until which to stake.| +|`stakeFor`|`address`|The address to stake the tokens for or 0x0 if staking for oneself.| +|`delegatee`|`address`|The address of the delegatee or 0x0 if there is none.| + + +### _stake + +Send sender's tokens to this contract and update its staked balance. + + +```solidity +function _stake(address sender, uint96 amount, uint256 until, address stakeFor, address delegatee, bool timeAdjusted) + internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sender`|`address`|The sender of the tokens.| +|`amount`|`uint96`|The number of tokens to send.| +|`until`|`uint256`|The date until which the tokens will be staked.| +|`stakeFor`|`address`|The beneficiary whose stake will be increased.| +|`delegatee`|`address`|The address of the delegatee or stakeFor if default 0x0.| +|`timeAdjusted`|`bool`|Whether fixing date to stacking periods or not.| + + +### _stakeOptionalTokenTransfer + +Send sender's tokens to this contract and update its staked balance. + + +```solidity +function _stakeOptionalTokenTransfer( + address sender, + uint96 amount, + uint256 until, + address stakeFor, + address delegatee, + bool timeAdjusted, + bool transferToken +) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sender`|`address`|The sender of the tokens.| +|`amount`|`uint96`|The number of tokens to send.| +|`until`|`uint256`|The date until which the tokens will be staked.| +|`stakeFor`|`address`|The beneficiary whose stake will be increased.| +|`delegatee`|`address`|The address of the delegatee or stakeFor if default 0x0.| +|`timeAdjusted`|`bool`|Whether fixing date to stacking periods or not.| +|`transferToken`|`bool`|Should transfer SOV - false for multiple iterations like in stakeBySchedule| + + +### extendStakingDuration + +Extend the staking duration until the specified date. + +*Stake for the sender if not specified otherwise.* + +*Delegate for stakeFor if not specified otherwise.* + +*Do not stake longer than the max duration.* + +*Increase stake.* + +*Update delegatee.* + +*Decrease stake on previous balance for previous delegatee.* + +*Add previousBalance to amount.* + +*Increase stake.* + + +```solidity +function extendStakingDuration(uint256 previousLock, uint256 until) external whenNotPaused whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`previousLock`|`uint256`|The old unlocking timestamp.| +|`until`|`uint256`|The new unlocking timestamp in seconds.| + + +### _increaseStake + +Send sender's tokens to this contract and update its staked balance. + +*Do not exceed the max duration, no overflow possible.* + +*Update checkpoints.* + +*TODO James: Can reading stake at block.number -1 cause trouble with multiple tx in a block?* + +*Delegate might change: if there is already a delegate set for the until date, it will remain the delegate for this position* + + +```solidity +function _increaseStake(address sender, uint96 amount, address stakeFor, uint256 until, bool transferToken) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sender`|`address`|The sender of the tokens.| +|`amount`|`uint96`|The number of tokens to send.| +|`stakeFor`|`address`|The beneficiary whose stake will be increased.| +|`until`|`uint256`|The date until which the tokens will be staked.| +|`transferToken`|`bool`|if false - token transfer should be handled separately| + + +### stakesBySchedule + +*Retrieve the SOV tokens.* + +*Increase staked balance.* + +*Update checkpoints.* + +*DO NOT USE this misspelled function. Use stakeBySchedule function instead. +This function cannot be deprecated while we have non-upgradeable vesting contracts.* + + +```solidity +function stakesBySchedule( + uint256 amount, + uint256 cliff, + uint256 duration, + uint256 intervalLength, + address stakeFor, + address delegatee +) external whenNotPaused whenNotFrozen; +``` + +### stakeBySchedule + +Stake tokens according to the vesting schedule. + + +```solidity +function stakeBySchedule( + uint256 amount, + uint256 cliff, + uint256 duration, + uint256 intervalLength, + address stakeFor, + address delegatee +) external whenNotPaused whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint256`|The amount of tokens to stake.| +|`cliff`|`uint256`|The time interval to the first withdraw.| +|`duration`|`uint256`|The staking duration.| +|`intervalLength`|`uint256`|The length of each staking interval when cliff passed.| +|`stakeFor`|`address`|The address to stake the tokens for or 0x0 if staking for oneself.| +|`delegatee`|`address`|The address of the delegatee or 0x0 if there is none.| + + +### _stakeBySchedule + +Stake tokens according to the vesting schedule. + + +```solidity +function _stakeBySchedule( + uint256 amount, + uint256 cliff, + uint256 duration, + uint256 intervalLength, + address stakeFor, + address delegatee +) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint256`|The amount of tokens to stake.| +|`cliff`|`uint256`|The time interval to the first withdraw.| +|`duration`|`uint256`|The staking duration.| +|`intervalLength`|`uint256`|The length of each staking interval when cliff passed.| +|`stakeFor`|`address`|The address to stake the tokens for or 0x0 if staking for oneself.| +|`delegatee`|`address`|The address of the delegatee or 0x0 if there is none.| + + +### balanceOf + +Get the number of staked tokens held by the user account. + +*Stake them until lock dates according to the vesting schedule. +Note: because staking is only possible in periods of 2 weeks, +the total duration might end up a bit shorter than specified +depending on the date of staking.* + +*transferring total SOV amount before staking* + +*stakedPerInterval might lose some dust on rounding. Add it to the first staking date.* + +*Stake the rest in 4 week intervals.* + +*Stakes for itself, delegates to the owner.* + +*Iterate checkpoints adding up stakes.* + + +```solidity +function balanceOf(address account) external view returns (uint96 balance); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to get the balance of.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`balance`|`uint96`|The number of tokens held.| + + +### getCurrentStakedUntil + +Get the current number of tokens staked for a day. + + +```solidity +function getCurrentStakedUntil(uint256 lockedTS) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The timestamp to get the staked tokens for.| + + +### getStakes + +Get list of stakes for a user account. + + +```solidity +function getStakes(address account) external view returns (uint256[] memory dates, uint96[] memory stakes); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address to get stakes.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`dates`|`uint256[]`|The arrays of dates and stakes.| +|`stakes`|`uint96[]`|| + + +### _getToken + +Overrides default ApprovalReceiver._getToken function to +register SOV token on this contract. + +*Calculate stakes.* + +*We need to iterate from first possible stake date after deployment to the latest from current time.* + +*We need to iterate from first possible stake date after deployment to the latest from current time.* + + +```solidity +function _getToken() internal view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The address of SOV token.| + + +### _getSelectors + +Overrides default ApprovalReceiver._getSelectors function to +register stakeWithApproval selector on this contract. + + +```solidity +function _getSelectors() internal pure returns (bytes4[] memory); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes4[]`|The array of registered selectors on this contract.| + + +### timestampToLockDate + +Unstaking is possible every 2 weeks only. This means, to +calculate the key value for the staking checkpoints, we need to +map the intended timestamp to the closest available date. + + +```solidity +function timestampToLockDate(uint256 timestamp) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`timestamp`|`uint256`|The unlocking timestamp.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The actual unlocking date (might be up to 2 weeks shorter than intended).| + + +### getFunctionsList + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory); +``` + +## Events +### TokensStaked +An event emitted when tokens get staked. + + +```solidity +event TokensStaked(address indexed staker, uint256 amount, uint256 lockedUntil, uint256 totalStaked); +``` + +### ExtendedStakingDuration +An event emitted when a staking period gets extended. + + +```solidity +event ExtendedStakingDuration(address indexed staker, uint256 previousDate, uint256 newDate, uint256 amountStaked); +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/StakingStorageModule.sol/contract.StakingStorageModule.md b/foundry/docs/src/contracts/governance/Staking/modules/StakingStorageModule.sol/contract.StakingStorageModule.md new file mode 100644 index 000000000..7132ac3c1 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/StakingStorageModule.sol/contract.StakingStorageModule.md @@ -0,0 +1,115 @@ +# StakingStorageModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/StakingStorageModule.sol) + +**Inherits:** +[IFunctionsList](/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md), [StakingStorageShared](/contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md) + +Provides getters for public storage variables + + +## Functions +### getStorageDefaultWeightScaling + + +```solidity +function getStorageDefaultWeightScaling() external pure returns (uint256); +``` + +### getStorageMaxDurationToStakeTokens + +The maximum duration to stake tokens + + +```solidity +function getStorageMaxDurationToStakeTokens() external pure returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|MAX_DURATION to stake tokens| + + +### getStorageMaxVotingWeight + +The maximum possible voting weight before adding +1 (actually 10, but need 9 for computation). + + +```solidity +function getStorageMaxVotingWeight() external pure returns (uint256); +``` + +### getStorageWeightFactor + +weight is multiplied with this factor (for allowing decimals, like 1.2x). + +*MAX_VOTING_WEIGHT * WEIGHT_FACTOR needs to be < 792, because there are 100,000,000 SOV with 18 decimals* + + +```solidity +function getStorageWeightFactor() external pure returns (uint256); +``` + +### getStorageDefaulWeightScaling + +Default weight scaling. + + +```solidity +function getStorageDefaulWeightScaling() external pure returns (uint256); +``` + +### getStorageRangeForWeightScaling + + +```solidity +function getStorageRangeForWeightScaling() external pure returns (uint256 minWeightScaling, uint256 maxWeightScaling); +``` + +### getStorageDomainTypehash + +The EIP-712 typehash for the contract's domain. + + +```solidity +function getStorageDomainTypehash() external pure returns (uint256); +``` + +### getStorageDelegationTypehash + +The EIP-712 typehash for the delegation struct used by the contract. + + +```solidity +function getStorageDelegationTypehash() external pure returns (uint256); +``` + +### getStorageName + + +```solidity +function getStorageName() external view returns (string memory); +``` + +### getMaxVestingWithdrawIterations + +Max iteration for direct withdrawal from staking to prevent out of gas issue. + + +```solidity +function getMaxVestingWithdrawIterations() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|max iteration value.| + + +### getFunctionsList + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory); +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/StakingVestingModule.sol/contract.StakingVestingModule.md b/foundry/docs/src/contracts/governance/Staking/modules/StakingVestingModule.sol/contract.StakingVestingModule.md new file mode 100644 index 000000000..bbf272be3 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/StakingVestingModule.sol/contract.StakingVestingModule.md @@ -0,0 +1,322 @@ +# StakingVestingModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/StakingVestingModule.sol) + +**Inherits:** +[IFunctionsList](/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md), [StakingShared](/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md) + +Implements interaction with Vesting functionality: vesting registry, vesting staking + + +## Functions +### setVestingRegistry + +sets vesting registry + +*_vestingRegistryProxy can be set to 0 as this function can be reused by +various other functionalities without the necessity of linking it with Vesting Registry* + + +```solidity +function setVestingRegistry(address _vestingRegistryProxy) external onlyOwner whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingRegistryProxy`|`address`|the address of vesting registry proxy contract| + + +### setVestingStakes + +Sets the users' vesting stakes for a giving lock dates and writes checkpoints. + + +```solidity +function setVestingStakes(uint256[] calldata lockedDates, uint96[] calldata values) + external + onlyAuthorized + whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedDates`|`uint256[]`|The arrays of lock dates.| +|`values`|`uint96[]`|The array of values to add to the staked balance. TODO: remove - it was designed as a disposable function to initialize vesting checkpoints| + + +### _setVestingStake + +Sets the users' vesting stake for a giving lock date and writes a checkpoint. + + +```solidity +function _setVestingStake(uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to be set. TODO: remove - it was designed as a disposable function to initialize vesting checkpoints| + + +### getPriorUserStakeByDate + +Determine the prior number of stake for an account until a +certain lock date as of a block number. + +*Block number must be a finalized block or else this function +will revert to prevent misinformation.* + + +```solidity +function getPriorUserStakeByDate(address account, uint256 date, uint256 blockNumber) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`date`|`uint256`|The lock date. Adjusted to the next valid lock date, if necessary.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### getPriorVestingWeightedStake + +Weighted Vesting Stake computation for fee sharing ****************************** + +Determine the prior weighted vested amount for an account as of a block number. +Iterate through checkpoints adding up voting power. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation. +Used for fee sharing, not voting. +TODO: WeightedStaking::getPriorVestingWeightedStake is using the variable name "votes" +to add up token stake, and that could be misleading.* + + +```solidity +function getPriorVestingWeightedStake(uint256 blockNumber, uint256 date) external view returns (uint96 votes); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| +|`date`|`uint256`|The staking date to compute the power for.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`votes`|`uint96`|The weighted stake the account had as of the given block.| + + +### weightedVestingStakeByDate + +Compute the voting power for a specific date. +Power = stake * weight + +*If date is not an exact break point, start weight computation from the previous break point (alternative would be the next).* + +*Max 78 iterations.* + + +```solidity +function weightedVestingStakeByDate(uint256 date, uint256 startDate, uint256 blockNumber) + external + view + returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The staking date to compute the power for. Adjusted to the previous valid lock date, if necessary.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake. Adjusted to the previous valid lock date, if necessary.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The stacking power.| + + +### _weightedVestingStakeByDate + +Compute the voting power for a specific date. +Power = stake * weight + + +```solidity +function _weightedVestingStakeByDate(uint256 date, uint256 startDate, uint256 blockNumber) + internal + view + returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The staking date to compute the power for.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The stacking power.| + + +### getPriorVestingStakeByDate + +Determine the prior number of vested stake for an account until a +certain lock date as of a block number. + +*Block number must be a finalized block or else this function +will revert to prevent misinformation.* + + +```solidity +function getPriorVestingStakeByDate(uint256 date, uint256 blockNumber) external view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The lock date. Adjusted to the next valid lock date, if necessary.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### _getPriorVestingStakeByDate + +Determine the prior number of vested stake for an account until a +certain lock date as of a block number. + +*All functions of Staking contract use this internal version, +we need to modify public function in order to workaround issue with Vesting.withdrawTokens: +return 1 instead of 0 if message sender is a contract.* + + +```solidity +function _getPriorVestingStakeByDate(uint256 date, uint256 blockNumber) internal view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The lock date.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### addContractCodeHash + +Add vesting contract's code hash to a map of code hashes. + +*First check most recent balance.* + +*Next check implicit zero balance.* + +*ceil, avoiding overflow.* + +*We need it to use isVestingContract() function instead of isContract()* + + +```solidity +function addContractCodeHash(address vesting) external onlyAuthorized whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The address of Vesting contract.| + + +### removeContractCodeHash + +Remove vesting contract's code hash to a map of code hashes. + +*We need it to use isVestingContract() function instead of isContract()* + + +```solidity +function removeContractCodeHash(address vesting) external onlyAuthorized whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The address of Vesting contract.| + + +### isVestingContract + +Return flag whether the given address is a registered vesting contract. + + +```solidity +function isVestingContract(address stakerAddress) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`stakerAddress`|`address`|the address to check| + + +### _getCodeHash + +Return hash of contract code + + +```solidity +function _getCodeHash(address _contract) internal view returns (bytes32); +``` + +### getFunctionsList + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory); +``` + +## Events +### ContractCodeHashAdded + +```solidity +event ContractCodeHashAdded(bytes32 hash); +``` + +### ContractCodeHashRemoved + +```solidity +event ContractCodeHashRemoved(bytes32 hash); +``` + +### VestingStakeSet + +```solidity +event VestingStakeSet(uint256 lockedTS, uint96 value); +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/StakingWithdrawModule.sol/contract.StakingWithdrawModule.md b/foundry/docs/src/contracts/governance/Staking/modules/StakingWithdrawModule.sol/contract.StakingWithdrawModule.md new file mode 100644 index 000000000..6e43a55be --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/StakingWithdrawModule.sol/contract.StakingWithdrawModule.md @@ -0,0 +1,355 @@ +# StakingWithdrawModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/StakingWithdrawModule.sol) + +**Inherits:** +[IFunctionsList](/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md), [StakingShared](/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md), [CheckpointsShared](/contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md) + + +## Functions +### withdraw + +Withdraw the given amount of tokens if they are unlocked. + +*If until is not a valid lock date, the next lock date after until is used.* + + +```solidity +function withdraw(uint96 amount, uint256 until, address receiver) external whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender| + + +### cancelTeamVesting + +Governance withdraw vesting directly through staking contract. +This direct withdraw vesting solves the out of gas issue when there are too many iterations when withdrawing. +This function only allows cancelling vesting contract of the TeamVesting type. + + +```solidity +function cancelTeamVesting(address vesting, address receiver, uint256 startFrom) + external + onlyAuthorized + whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The vesting address.| +|`receiver`|`address`|The receiving address.| +|`startFrom`|`uint256`|The start value for the iterations.| + + +### _cancelTeamVesting + +require the caller only for team vesting contract. + +Withdraws tokens from the staking contract and forwards them +to an address specified by the token owner. Low level function. + +*Once here the caller permission is taken for granted.* + + +```solidity +function _cancelTeamVesting(address _vesting, address _receiver, uint256 _startFrom) + private + returns (uint256 nextStartFrom, bool notCompleted); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vesting`|`address`|The vesting address.| +|`_receiver`|`address`|The receiving address.| +|`_startFrom`|`uint256`|The start value for the iterations. or just unlocked tokens (false).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`nextStartFrom`|`uint256`|is a timestamp to be used for next withdrawal.| +|`notCompleted`|`bool`|flag that indicates that the cancel team vesting is not completely done.| + + +### _withdraw + +Send user' staked tokens to a receiver taking into account punishments. +Sovryn encourages long-term commitment and thinking. When/if you unstake before +the end of the staking period, a percentage of the original staking amount will +be slashed. This amount is also added to the reward pool and is distributed +between all other stakers. + +*In the unlikely case that all tokens have been unlocked early, +allow to withdraw all of them, as long as the itrations less than maxVestingWithdrawIterations.* + +*max iterations need to be decreased by 1, otherwise the iteration will always be surplus by 1* + +*Withdraw for each unlocked position.* + +*Read amount to withdraw.* + +*do governance direct withdraw for team vesting* + + +```solidity +function _withdraw(uint96 amount, uint256 until, address receiver, bool isGovernance) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked. Needs to be adjusted to the next valid lock date before calling this function.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender| +|`isGovernance`|`bool`|Whether all tokens (true) or just unlocked tokens (false).| + + +### _withdrawFromTeamVesting + +Send user' staked tokens to a receiver. +This function is dedicated only for direct withdrawal from staking contract. +Currently only being used by cancelTeamVesting() + +*Determine the receiver.* + +*Update the checkpoints.* + +*Early unstaking should be punished.* + +*punishedAmount can be 0 if block.timestamp are very close to 'until'* + +*Move punished amount to fee sharing.* + +*Approve transfer here and let feeSharing do transfer and write checkpoint.* + +*transferFrom* + +*VestingConfig struct intended to avoid stack too deep issue, and it contains this properties: +address vestingAddress; // vesting contract address +uint256 startDate; //start date of vesting +uint256 endDate; // end date of vesting +uint256 cliff; // after this time period the tokens begin to unlock +uint256 duration; // after this period all the tokens will be unlocked +address tokenOwner; // owner of the vested tokens* + + +```solidity +function _withdrawFromTeamVesting(uint96 amount, uint256 until, address receiver, VestingConfig memory vestingConfig) + internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender.| +|`vestingConfig`|`VestingConfig`|The vesting config.| + + +### _withdrawNext + +*Update the checkpoints.* + +*transferFrom* + + +```solidity +function _withdrawNext(uint256 until, address receiver, bool isGovernance) internal; +``` + +### getWithdrawAmounts + +Get available and punished amount for withdrawing. + + +```solidity +function getWithdrawAmounts(uint96 amount, uint256 until) external view returns (uint96, uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked. Adjusted to the next valid lock date, if necessary.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|Amount to withraw and penalty amount| +|``|`uint96`|| + + +### _getPunishedAmount + +Get punished amount for withdrawing. + + +```solidity +function _getPunishedAmount(uint96 amount, uint256 until) internal view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| + + +### _validateWithdrawParams + +Validate withdraw parameters. + +*(10 - 1) * WEIGHT_FACTOR* + + +```solidity +function _validateWithdrawParams(address account, uint96 amount, uint256 until) internal view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|Address to be validated.| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| + + +### unlockAllTokens + +Allow the owner to unlock all tokens in case the staking contract +is going to be replaced +Note: Not reversible on purpose. once unlocked, everything is unlocked. +The owner should not be able to just quickly unlock to withdraw his own +tokens and lock again. + +*Last resort.* + + +```solidity +function unlockAllTokens() external onlyOwner whenNotFrozen; +``` + +### setMaxVestingWithdrawIterations + +*set max withdraw iterations.* + + +```solidity +function setMaxVestingWithdrawIterations(uint256 newMaxIterations) external onlyAuthorized whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newMaxIterations`|`uint256`|new max iterations value.| + + +### governanceWithdrawVesting + +Withdraw tokens for vesting contract. + +*This function is dedicated only to support backward compatibility for sovryn ecosystem that has been implementing this staking contract.* + +*Sovryn protocol will use the cancelTeamVesting function for the withdrawal moving forward. +https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/4bbfe5bd0311ca71e4ef0e3af810d3791d8e4061/contracts/governance/Staking/modules/StakingWithdrawModule.sol#L78* + + +```solidity +function governanceWithdrawVesting(address vesting, address receiver) public onlyAuthorized whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vesting`|`address`|The address of Vesting contract.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender| + + +### governanceWithdraw + +The withdrawal is limited to certain iterations (set in maxVestingWithdrawIterations), so in order to withdraw all, we need to iterate until it is fully withdrawn. +notCompleted is the flag whether the withdrawal is fully withdrawn or not. +As long as the notCompleted is true, we will keep the iteration using the nextStartFrom. + +Withdraw the given amount of tokens. + +*Can be invoked only by whitelisted contract passed to governanceWithdrawVesting* + + +```solidity +function governanceWithdraw(uint96 amount, uint256 until, address receiver) external whenNotFrozen; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint96`|The number of tokens to withdraw.| +|`until`|`uint256`|The date until which the tokens were staked.| +|`receiver`|`address`|The receiver of the tokens. If not specified, send to the msg.sender| + + +### getFunctionsList + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory); +``` + +## Events +### MaxVestingWithdrawIterationsUpdated + +```solidity +event MaxVestingWithdrawIterationsUpdated(uint256 oldMaxIterations, uint256 newMaxIterations); +``` + +### StakingWithdrawn +An event emitted when staked tokens get withdrawn. + + +```solidity +event StakingWithdrawn( + address indexed staker, uint256 amount, uint256 until, address indexed receiver, bool isGovernance +); +``` + +### VestingTokensWithdrawn +An event emitted when vesting tokens get withdrawn. + + +```solidity +event VestingTokensWithdrawn(address vesting, address receiver); +``` + +### TokensUnlocked +An event emitted when the owner unlocks all tokens. + + +```solidity +event TokensUnlocked(uint256 amount); +``` + +## Structs +### VestingConfig +*Struct for direct withdraw function -- to avoid stack too deep issue* + + +```solidity +struct VestingConfig { + address vestingAddress; + uint256 startDate; + uint256 endDate; + uint256 cliff; + uint256 duration; + address tokenOwner; +} +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/WeightedStakingModule.sol/contract.WeightedStakingModule.md b/foundry/docs/src/contracts/governance/Staking/modules/WeightedStakingModule.sol/contract.WeightedStakingModule.md new file mode 100644 index 000000000..d98cacc7f --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/WeightedStakingModule.sol/contract.WeightedStakingModule.md @@ -0,0 +1,142 @@ +# WeightedStakingModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/WeightedStakingModule.sol) + +**Inherits:** +[IFunctionsList](/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md), [StakingShared](/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md), [CheckpointsShared](/contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md) + +Implements getters for weighted staking functionality + + +## Functions +### getPriorWeightedStake + +User Weighted Stake computation for fee sharing ****************************** + +Determine the prior weighted stake for an account as of a block number. +Iterate through checkpoints adding up voting power. + +*Block number must be a finalized block or else this function will +revert to prevent misinformation. +Used for fee sharing, not voting.* + + +```solidity +function getPriorWeightedStake(address account, uint256 blockNumber, uint256 date) + external + view + returns (uint96 priorWeightedStake); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| +|`date`|`uint256`|The start date/timestamp from which to calculate the weighted stake.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`priorWeightedStake`|`uint96`|The weighted stake the account had as of the given block.| + + +### _getPriorWeightedStake + + +```solidity +function _getPriorWeightedStake(address account, uint256 blockNumber, uint256 date) + internal + view + returns (uint96 priorWeightedStake); +``` + +### weightedStakeByDate + +Compute the voting power for a specific date. +Power = stake * weight + +*If date is not an exact break point, start weight computation from the previous break point (alternative would be the next).* + +*Max 78 iterations.* + + +```solidity +function weightedStakeByDate(address account, uint256 date, uint256 startDate, uint256 blockNumber) + external + view + returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The user address.| +|`date`|`uint256`|The staking date to compute the power for. Adjusted to the previous valid lock date, if necessary.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake. Adjusted to the previous valid lock date, if necessary.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The staking power.| + + +### _weightedStakeByDate + +Compute the voting power for a specific date. +Power = stake * weight + + +```solidity +function _weightedStakeByDate(address account, uint256 date, uint256 startDate, uint256 blockNumber) + internal + view + returns (uint96 power); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The user address.| +|`date`|`uint256`|The staking date to compute the power for.| +|`startDate`|`uint256`|The date for which we need to know the power of the stake.| +|`blockNumber`|`uint256`|The block number, needed for checkpointing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`power`|`uint96`|The staking power.| + + +### computeWeightByDate + +Compute the weight for a specific date. + + +```solidity +function computeWeightByDate(uint256 date, uint256 startDate) external pure returns (uint96 weight); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The unlocking date.| +|`startDate`|`uint256`|We compute the weight for the tokens staked until 'date' on 'startDate'.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`weight`|`uint96`|The weighted stake the account had as of the given block.| + + +### getFunctionsList + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory); +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md b/foundry/docs/src/contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md new file mode 100644 index 000000000..5b9f7a514 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/shared/CheckpointsShared.sol/contract.CheckpointsShared.md @@ -0,0 +1,386 @@ +# CheckpointsShared +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/shared/CheckpointsShared.sol) + +**Inherits:** +[StakingStorageShared](/contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md), [SafeMath96](/contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md) + +Increases and decreases storage values for users, delegatees and +total daily stake. + + +## Functions +### constructor + + +```solidity +constructor() internal; +``` + +### _increaseVestingStake + +Increases the user's vesting stake for a giving lock date and writes a checkpoint. + + +```solidity +function _increaseVestingStake(uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to add to the staked balance.| + + +### _decreaseVestingStake + +Decreases the user's vesting stake for a giving lock date and writes a checkpoint. + + +```solidity +function _decreaseVestingStake(uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to substract to the staked balance.| + + +### _writeVestingCheckpoint + +Writes on storage the user vested amount. + + +```solidity +function _writeVestingCheckpoint(uint256 lockedTS, uint32 nCheckpoints, uint96 newVest) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The lock date.| +|`nCheckpoints`|`uint32`|The number of checkpoints, to find out the last one index.| +|`newVest`|`uint96`|The new vest balance.| + + +### _increaseUserStake + +Increases the user's stake for a giving lock date and writes a checkpoint. + + +```solidity +function _increaseUserStake(address account, uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The user address.| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to add to the staked balance.| + + +### _decreaseUserStake + +Decreases the user's stake for a giving lock date and writes a checkpoint. + + +```solidity +function _decreaseUserStake(address account, uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The user address.| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to substract to the staked balance.| + + +### _writeUserCheckpoint + +Writes on storage the user stake. + + +```solidity +function _writeUserCheckpoint(address account, uint256 lockedTS, uint32 nCheckpoints, uint96 newStake) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The user address.| +|`lockedTS`|`uint256`|The lock date.| +|`nCheckpoints`|`uint32`|The number of checkpoints, to find out the last one index.| +|`newStake`|`uint96`|The new staked balance.| + + +### _increaseDelegateStake + +Increases the delegatee's stake for a giving lock date and writes a checkpoint. + + +```solidity +function _increaseDelegateStake(address delegatee, uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`delegatee`|`address`|The delegatee address.| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to add to the staked balance.| + + +### _decreaseDelegateStake + +Decreases the delegatee's stake for a giving lock date and writes a checkpoint. + + +```solidity +function _decreaseDelegateStake(address delegatee, uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`delegatee`|`address`|The delegatee address.| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to substract to the staked balance.| + + +### _writeDelegateCheckpoint + +Writes on storage the delegate stake. + + +```solidity +function _writeDelegateCheckpoint(address delegatee, uint256 lockedTS, uint32 nCheckpoints, uint96 newStake) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`delegatee`|`address`|The delegate address.| +|`lockedTS`|`uint256`|The lock date.| +|`nCheckpoints`|`uint32`|The number of checkpoints, to find out the last one index.| +|`newStake`|`uint96`|The new staked balance.| + + +### _increaseDailyStake + +Increases the total stake for a giving lock date and writes a checkpoint. + + +```solidity +function _increaseDailyStake(uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to add to the staked balance.| + + +### _decreaseDailyStake + +Decreases the total stake for a giving lock date and writes a checkpoint. + + +```solidity +function _decreaseDailyStake(uint256 lockedTS, uint96 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The lock date.| +|`value`|`uint96`|The value to substract to the staked balance.| + + +### _writeStakingCheckpoint + +Writes on storage the total stake. + + +```solidity +function _writeStakingCheckpoint(uint256 lockedTS, uint32 nCheckpoints, uint96 newStake) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lockedTS`|`uint256`|The lock date.| +|`nCheckpoints`|`uint32`|The number of checkpoints, to find out the last one index.| +|`newStake`|`uint96`|The new staked balance.| + + +### _currentBalance + +Get the current balance of an account locked until a certain date. + + +```solidity +function _currentBalance(address account, uint256 lockDate) internal view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The user address.| +|`lockDate`|`uint256`|The lock date.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The stake amount.| + + +## Events +### DelegateChanged +An event emitted when an account changes its delegate. + + +```solidity +event DelegateChanged( + address indexed delegator, uint256 lockedUntil, address indexed fromDelegate, address indexed toDelegate +); +``` + +### DelegateStakeChanged +An event emitted when a delegate account's stake balance changes. + + +```solidity +event DelegateStakeChanged(address indexed delegate, uint256 lockedUntil, uint256 previousBalance, uint256 newBalance); +``` + +### TokensStaked +An event emitted when tokens get staked. + + +```solidity +event TokensStaked(address indexed staker, uint256 amount, uint256 lockedUntil, uint256 totalStaked); +``` + +### StakingWithdrawn +An event emitted when staked tokens get withdrawn. + + +```solidity +event StakingWithdrawn( + address indexed staker, uint256 amount, uint256 until, address indexed receiver, bool isGovernance +); +``` + +### VestingTokensWithdrawn +An event emitted when vesting tokens get withdrawn. + + +```solidity +event VestingTokensWithdrawn(address vesting, address receiver); +``` + +### TokensUnlocked +An event emitted when the owner unlocks all tokens. + + +```solidity +event TokensUnlocked(uint256 amount); +``` + +### ExtendedStakingDuration +An event emitted when a staking period gets extended. + + +```solidity +event ExtendedStakingDuration(address indexed staker, uint256 previousDate, uint256 newDate, uint256 amountStaked); +``` + +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + +### PauserAddedOrRemoved + +```solidity +event PauserAddedOrRemoved(address indexed pauser, bool indexed added); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`pauser`|`address`|address to grant power to pause the contract| +|`added`|`bool`|true - added, false - removed| + +### StakingPaused +An event emitted when a staking is paused or unpaused + + +```solidity +event StakingPaused(bool indexed setPaused); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`setPaused`|`bool`|true - pause, false - unpause| + +### StakingFrozen +An event emitted when a staking is frozen or unfrozen + + +```solidity +event StakingFrozen(bool indexed setFrozen); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`setFrozen`|`bool`|true - freeze, false - unfreeze| + +### ContractCodeHashAdded + +```solidity +event ContractCodeHashAdded(bytes32 hash); +``` + +### ContractCodeHashRemoved + +```solidity +event ContractCodeHashRemoved(bytes32 hash); +``` + +### VestingStakeSet + +```solidity +event VestingStakeSet(uint256 lockedTS, uint96 value); +``` + +### TeamVestingCancelled + +```solidity +event TeamVestingCancelled(address indexed caller, address receiver); +``` + +### TeamVestingPartiallyCancelled + +```solidity +event TeamVestingPartiallyCancelled(address indexed caller, address receiver, uint256 nextStartFrom); +``` + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/shared/README.md b/foundry/docs/src/contracts/governance/Staking/modules/shared/README.md new file mode 100644 index 000000000..118b8ce23 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/shared/README.md @@ -0,0 +1,6 @@ + + +# Contents +- [CheckpointsShared](CheckpointsShared.sol/contract.CheckpointsShared.md) +- [StakingShared](StakingShared.sol/contract.StakingShared.md) +- [StakingStorageShared](StakingStorageShared.sol/contract.StakingStorageShared.md) diff --git a/foundry/docs/src/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md b/foundry/docs/src/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md new file mode 100644 index 000000000..7fb985606 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/shared/StakingShared.sol/contract.StakingShared.md @@ -0,0 +1,212 @@ +# StakingShared +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/shared/StakingShared.sol) + +**Inherits:** +[StakingStorageShared](/contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md), [SafeMath96](/contracts/governance/Staking/SafeMath96.sol/contract.SafeMath96.md) + + +## State Variables +### FOUR_WEEKS + +```solidity +uint256 internal constant FOUR_WEEKS = 4 weeks; +``` + + +## Functions +### whenNotPaused + +*Throws if paused.* + + +```solidity +modifier whenNotPaused(); +``` + +### onlyAuthorized + +*Throws if called by any account other than the owner or admin.* + + +```solidity +modifier onlyAuthorized(); +``` + +### onlyPauserOrOwner + +*Throws if called by any account other than the owner or admin or pauser. +modifier onlyAuthorizedOrPauser() { +require(isOwner() || admins[msg.sender] || pausers[msg.sender], "unauthorized"); // WS02 +_; +}* + +*Throws if called by any account other than the owner or pauser.* + + +```solidity +modifier onlyPauserOrOwner(); +``` + +### whenNotFrozen + +Uncomment when needed + +*Throws if called by any account other than pauser.* + +*Throws if frozen.* + + +```solidity +modifier whenNotFrozen(); +``` + +### constructor + + +```solidity +constructor() internal; +``` + +### _notSameBlockAsStakingCheckpoint + + +```solidity +function _notSameBlockAsStakingCheckpoint(uint256 lockDate, address stakeFor) internal view; +``` + +### _timestampToLockDate + +Unstaking is possible every 2 weeks only. This means, to +calculate the key value for the staking checkpoints, we need to +map the intended timestamp to the closest available date. + + +```solidity +function _timestampToLockDate(uint256 timestamp) internal view returns (uint256 lockDate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`timestamp`|`uint256`|The unlocking timestamp.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`lockDate`|`uint256`|The actual unlocking date (might be up to 2 weeks shorter than intended).| + + +### _getCurrentBlockNumber + +Determine the current Block Number + +*If staking timestamp does not match any of the unstaking dates +, set the lockDate to the closest one before the timestamp. +E.g. Passed timestamps lies 7 weeks after kickoff -> only stake for 6 weeks.* + +*This is segregated from the _getPriorUserStakeByDate function to better test +advancing blocks functionality using Mock Contracts* + + +```solidity +function _getCurrentBlockNumber() internal view returns (uint256); +``` + +### _getPriorUserStakeByDate + +Determine the prior number of stake for an account until a +certain lock date as of a block number. + +*All functions of Staking contract use this internal version, +we need to modify public function in order to workaround issue with Vesting.withdrawTokens: +return 1 instead of 0 if message sender is a contract.* + + +```solidity +function _getPriorUserStakeByDate(address account, uint256 date, uint256 blockNumber) internal view returns (uint96); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`account`|`address`|The address of the account to check.| +|`date`|`uint256`|The lock date. Adjusted to the next valid lock date, if necessary.| +|`blockNumber`|`uint256`|The block number to get the vote balance at.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint96`|The number of votes the account had as of the given block.| + + +### _adjustDateForOrigin + +*First check most recent balance.* + +*Next check implicit zero balance.* + +*ceil, avoiding overflow.* + +*origin vesting contracts have different dates +we need to add 2 weeks to get end of period (by default, it's start)* + + +```solidity +function _adjustDateForOrigin(uint256 date) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The staking date to compute the power for.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|unlocking date.| + + +### _computeWeightByDate + +Compute the weight for a specific date. + + +```solidity +function _computeWeightByDate(uint256 date, uint256 startDate) internal pure returns (uint96 weight); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`date`|`uint256`|The unlocking date.| +|`startDate`|`uint256`|We compute the weight for the tokens staked until 'date' on 'startDate'.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`weight`|`uint96`|The weighted stake the account had as of the given block.| + + +### _isVestingContract + +Return flag whether the given address is a registered vesting contract. + +*x = max days - remaining days* + +*w = (m^2 - x^2)/m^2 +1 (multiplied by the weight factor)* + + +```solidity +function _isVestingContract(address stakerAddress) internal view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`stakerAddress`|`address`|the address to check| + + diff --git a/foundry/docs/src/contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md b/foundry/docs/src/contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md new file mode 100644 index 000000000..1f8bebf96 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Staking/modules/shared/StakingStorageShared.sol/contract.StakingStorageShared.md @@ -0,0 +1,384 @@ +# StakingStorageShared +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Staking/modules/shared/StakingStorageShared.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +Just the storage part of stacking contract, no functions, +only constant, variables and required structures (mappings). +Used by StackingProxy and Checkpoints contracts. +What is SOV staking? +The purpose of the SOV token is to provide a pseudonymous, +censorship-resistant mechanism for governing the parameters of the Sovryn +protocol, while aligning the incentives of protocol governors with the +long-term success of the protocol. Any SOV token holder can choose to +stake (lock up) their tokens for a fixed period of time in return for +voting rights in the Bitocracy. Stakers are further incentivised through +fee and slashing rewards. + + +## State Variables +### TWO_WEEKS +2 weeks in seconds. + + +```solidity +uint256 constant TWO_WEEKS = 1209600; +``` + + +### MAX_VOTING_WEIGHT +The maximum possible voting weight before adding +1 (actually 10, but need 9 for computation). + + +```solidity +uint96 public constant MAX_VOTING_WEIGHT = 9; +``` + + +### WEIGHT_FACTOR +weight is multiplied with this factor (for allowing decimals, like 1.2x). + +*MAX_VOTING_WEIGHT * WEIGHT_FACTOR needs to be < 792, because there are 100,000,000 SOV with 18 decimals* + + +```solidity +uint96 public constant WEIGHT_FACTOR = 10; +``` + + +### MAX_DURATION +The maximum duration to stake tokens for. + + +```solidity +uint256 public constant MAX_DURATION = 1092 days; +``` + + +### MAX_DURATION_POW_2 +The maximum duration ^2 + + +```solidity +uint96 constant MAX_DURATION_POW_2 = 1092 * 1092; +``` + + +### DEFAULT_WEIGHT_SCALING +Default weight scaling. + + +```solidity +uint96 constant DEFAULT_WEIGHT_SCALING = 3; +``` + + +### MIN_WEIGHT_SCALING +Range for weight scaling. + + +```solidity +uint96 constant MIN_WEIGHT_SCALING = 1; +``` + + +### MAX_WEIGHT_SCALING + +```solidity +uint96 constant MAX_WEIGHT_SCALING = 9; +``` + + +### kickoffTS +The timestamp of contract creation. Base for the staking period calculation. + + +```solidity +uint256 public kickoffTS; +``` + + +### name + +```solidity +string name = "SOVStaking"; +``` + + +### SOVToken +The token to be staked. + + +```solidity +IERC20 public SOVToken; +``` + + +### delegates +A record of each accounts delegate. + + +```solidity +mapping(address => mapping(uint256 => address)) public delegates; +``` + + +### allUnlocked +If this flag is set to true, all tokens are unlocked immediately. + + +```solidity +bool public allUnlocked = false; +``` + + +### DOMAIN_TYPEHASH +The EIP-712 typehash for the contract's domain. + + +```solidity +bytes32 public constant DOMAIN_TYPEHASH = + keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); +``` + + +### DELEGATION_TYPEHASH +The EIP-712 typehash for the delegation struct used by the contract. + + +```solidity +bytes32 public constant DELEGATION_TYPEHASH = + keccak256("Delegation(address delegatee,uint256 lockDate,uint256 nonce,uint256 expiry)"); +``` + + +### newStakingContract +Used for stake migrations to a new staking contract with a different storage structure. + + +```solidity +address public newStakingContract; +``` + + +### totalStakingCheckpoints +A record of tokens to be unstaked at a given time in total. +For total voting power computation. Voting weights get adjusted bi-weekly. + +*totalStakingCheckpoints[date][index] is a checkpoint.* + + +```solidity +mapping(uint256 => mapping(uint32 => Checkpoint)) public totalStakingCheckpoints; +``` + + +### numTotalStakingCheckpoints +The number of total staking checkpoints for each date. + +*numTotalStakingCheckpoints[date] is a number.* + + +```solidity +mapping(uint256 => uint32) public numTotalStakingCheckpoints; +``` + + +### delegateStakingCheckpoints +A record of tokens to be unstaked at a given time which were delegated to a certain address. +For delegatee voting power computation. Voting weights get adjusted bi-weekly. + +*delegateStakingCheckpoints[delegatee][date][index] is a checkpoint.* + + +```solidity +mapping(address => mapping(uint256 => mapping(uint32 => Checkpoint))) public delegateStakingCheckpoints; +``` + + +### numDelegateStakingCheckpoints +The number of total staking checkpoints for each date per delegate. + +*numDelegateStakingCheckpoints[delegatee][date] is a number.* + + +```solidity +mapping(address => mapping(uint256 => uint32)) public numDelegateStakingCheckpoints; +``` + + +### userStakingCheckpoints +A record of tokens to be unstaked at a given time which per user address (address -> lockDate -> stake checkpoint) + +*userStakingCheckpoints[user][date][index] is a checkpoint.* + + +```solidity +mapping(address => mapping(uint256 => mapping(uint32 => Checkpoint))) public userStakingCheckpoints; +``` + + +### numUserStakingCheckpoints +The number of total staking checkpoints for each date per user. + +*numUserStakingCheckpoints[user][date] is a number.* + + +```solidity +mapping(address => mapping(uint256 => uint32)) public numUserStakingCheckpoints; +``` + + +### nonces +A record of states for signing / validating signatures + +*nonces[user] is a number.* + + +```solidity +mapping(address => uint256) public nonces; +``` + + +### feeSharing +Slashing ****************************** + +the address of FeeSharingCollectorProxy contract, we need it for unstaking with slashing. + + +```solidity +IFeeSharingCollector public feeSharing; +``` + + +### weightScaling +used for weight scaling when unstaking with slashing. + + +```solidity +uint96 public weightScaling = DEFAULT_WEIGHT_SCALING; +``` + + +### vestingWhitelist +List of vesting contracts, tokens for these contracts won't be slashed if unstaked by governance. + +*vestingWhitelist[contract] is true/false.* + + +```solidity +mapping(address => bool) public vestingWhitelist; +``` + + +### admins +*user => flag whether user has admin role.* + +*multisig should be an admin, admin can invoke only governanceWithdrawVesting function, +this function works only with Team Vesting contracts* + + +```solidity +mapping(address => bool) public admins; +``` + + +### vestingCodeHashes +*vesting contract code hash => flag whether it's registered code hash* + + +```solidity +mapping(bytes32 => bool) public vestingCodeHashes; +``` + + +### vestingCheckpoints +A record of tokens to be unstaked from vesting contract at a given time (lockDate -> vest checkpoint) + +*vestingCheckpoints[date][index] is a checkpoint.* + + +```solidity +mapping(uint256 => mapping(uint32 => Checkpoint)) public vestingCheckpoints; +``` + + +### numVestingCheckpoints +The number of total vesting checkpoints for each date. + +*numVestingCheckpoints[date] is a number.* + + +```solidity +mapping(uint256 => uint32) public numVestingCheckpoints; +``` + + +### vestingRegistryLogic +vesting registry contract + + +```solidity +IVestingRegistry public vestingRegistryLogic; +``` + + +### pausers +*user => flag whether user has pauser role.* + + +```solidity +mapping(address => bool) public pausers; +``` + + +### paused +*Staking contract is paused* + + +```solidity +bool public paused; +``` + + +### frozen +*Staking contract is frozen* + + +```solidity +bool public frozen; +``` + + +### maxVestingWithdrawIterations +*max iterations that can be supported in 1 tx for the withdrawal* + + +```solidity +uint256 internal maxVestingWithdrawIterations; +``` + + +## Functions +### constructor + + +```solidity +constructor() internal; +``` + +## Structs +### Checkpoint +Checkpoints ****************************** + +A checkpoint for marking the stakes from a given block + + +```solidity +struct Checkpoint { + uint32 fromBlock; + uint96 stake; +} +``` + diff --git a/foundry/docs/src/contracts/governance/StakingRewards/README.md b/foundry/docs/src/contracts/governance/StakingRewards/README.md new file mode 100644 index 000000000..ba166b73d --- /dev/null +++ b/foundry/docs/src/contracts/governance/StakingRewards/README.md @@ -0,0 +1,9 @@ + + +# Contents +- [StakingRewards](StakingRewards.sol/contract.StakingRewards.md) +- [StakingRewardsOs](StakingRewardsOs.sol/contract.StakingRewardsOs.md) +- [StakingRewardsOsProxy](StakingRewardsOsProxy.sol/contract.StakingRewardsOsProxy.md) +- [StakingRewardsOsStorage](StakingRewardsOsStorage.sol/contract.StakingRewardsOsStorage.md) +- [StakingRewardsProxy](StakingRewardsProxy.sol/contract.StakingRewardsProxy.md) +- [StakingRewardsStorage](StakingRewardsStorage.sol/contract.StakingRewardsStorage.md) diff --git a/foundry/docs/src/contracts/governance/StakingRewards/StakingRewards.sol/contract.StakingRewards.md b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewards.sol/contract.StakingRewards.md new file mode 100644 index 000000000..3b2aaad15 --- /dev/null +++ b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewards.sol/contract.StakingRewards.md @@ -0,0 +1,269 @@ +# StakingRewards +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/StakingRewards/StakingRewards.sol) + +**Inherits:** +[StakingRewardsStorage](/contracts/governance/StakingRewards/StakingRewardsStorage.sol/contract.StakingRewardsStorage.md) + +This is a trial incentive program. +In this, the SOV emitted and becoming liquid from the Adoption Fund could be utilized +to offset the higher APY's offered for Liquidity Mining events. +Vesting contract stakes are excluded from these rewards. +Only wallets which have staked previously liquid SOV are eligible for these rewards. +Tokenholders who stake their SOV receive staking rewards, a pro-rata share +of the revenue that the platform generates from various transaction fees +plus revenues from stakers who have a portion of their SOV slashed for +early unstaking. + + +## Functions +### initialize + +Replacement of constructor by initialize function for Upgradable Contracts +This function will be called only once by the owner. + + +```solidity +function initialize(address _SOV, IStaking _staking) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`address`|SOV token address| +|`_staking`|`IStaking`|StakingProxy address should be passed| + + +### stop + +Stops the current rewards program. + +*All stakes existing on the contract at the point in time of +cancellation continue accruing rewards until the end of the staking +period being rewarded* + + +```solidity +function stop() external onlyOwner; +``` + +### collectReward + +Collect rewards + +*User calls this function to collect SOV staking rewards as per the SIP-0024 program. +The weighted stake is calculated using getPriorWeightedStake. Block number sent to the functon +must be a finalised block, hence we deduct 1 from the current block. User is only allowed to withdraw +after intervals of 14 days.* + + +```solidity +function collectReward(uint256 restartTime) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`restartTime`|`uint256`|The time from which the staking rewards calculation shall restart. The issue is that we can only run for a max duration and if someone stakes for the first time after the max duration is over, the reward will always return 0. Thus, we need to restart from the duration that elapsed without generating rewards.| + + +### withdrawTokensByOwner + +Withdraws all token from the contract by Multisig. + + +```solidity +function withdrawTokensByOwner(address _receiverAddress) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiverAddress`|`address`|The address where the tokens has to be transferred.| + + +### setAverageBlockTime + +Changes average block time - based on blockchain + +*If average block time significantly changes, we can update it here and use for block number calculation* + + +```solidity +function setAverageBlockTime(uint256 _averageBlockTime) external onlyOwner; +``` + +### setBlock + +This function computes the last staking checkpoint and calculates the corresponding +block number using the average block time which is then added to the mapping `checkpointBlockDetails`. + + +```solidity +function setBlock() external; +``` + +### setHistoricalBlock + +This function computes the block number using the average block time for a given historical +checkpoint which is added to the mapping `checkpointBlockDetails`. + + +```solidity +function setHistoricalBlock(uint256 _time) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_time`|`uint256`|Exact staking checkpoint time| + + +### setMaxDuration + +Sets the max duration + +*Rewards can be collected for a maximum duration at a time. This +is to avoid Block Gas Limit failures. Setting it zero would mean that it will loop +through the entire duration since the start of rewards program. +It should ideally be set to a value, for which the rewards can be easily processed.* + + +```solidity +function setMaxDuration(uint256 _duration) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_duration`|`uint256`|Max duration for which rewards can be collected at a go (in seconds)| + + +### _computeRewardForDate + +Internal function to calculate weighted stake + +*If the rewards program is stopped, the user will still continue to +earn till the end of staking period based on the stop block.* + + +```solidity +function _computeRewardForDate(address _staker, uint256 _block, uint256 _date) + internal + view + returns (uint256 weightedStake); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_staker`|`address`|Staker address| +|`_block`|`uint256`|Last finalised block| +|`_date`|`uint256`|The date to compute prior weighted stakes| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`weightedStake`|`uint256`|The weighted stake| + + +### _payReward + +Internal function to pay rewards + +*Base rate is annual, but we pay interest for 14 days, +which is 1/26 of one staking year (1092 days)* + + +```solidity +function _payReward(address _staker, uint256 amount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_staker`|`address`|User address| +|`amount`|`uint256`|the reward amount| + + +### _transferSOV + +transfers SOV tokens to given address + + +```solidity +function _transferSOV(address _receiver, uint256 _amount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|the address of the SOV receiver| +|`_amount`|`uint256`|the amount to be transferred| + + +### _getCurrentBlockNumber + +Determine the current Block Number + +*This is segregated from the _getPriorUserStakeByDate function to better test +advancing blocks functionality using Mock Contracts* + + +```solidity +function _getCurrentBlockNumber() internal view returns (uint256); +``` + +### _setBlock + +Internal function to calculate and set block + + +```solidity +function _setBlock(uint256 _checkpointTime) internal; +``` + +### getStakerCurrentReward + +Get staker's current accumulated reward + +*The collectReward() function internally calls this function to calculate reward amount* + + +```solidity +function getStakerCurrentReward(bool considerMaxDuration, uint256 restartTime) + public + view + returns (uint256 lastWithdrawalInterval, uint256 amount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`considerMaxDuration`|`bool`|True: Runs for the maximum duration - used in tx not to run out of gas False - to query total rewards| +|`restartTime`|`uint256`|The time from which the staking rewards calculation shall restart.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`lastWithdrawalInterval`|`uint256`|The timestamp of last withdrawal| +|`amount`|`uint256`|The accumulated reward| + + +## Events +### RewardWithdrawn +Emitted when SOV is withdrawn + + +```solidity +event RewardWithdrawn(address indexed receiver, uint256 amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The address which recieves the SOV| +|`amount`|`uint256`|The amount withdrawn from the Smart Contract| + diff --git a/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOs.sol/contract.StakingRewardsOs.md b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOs.sol/contract.StakingRewardsOs.md new file mode 100644 index 000000000..9df99e07f --- /dev/null +++ b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOs.sol/contract.StakingRewardsOs.md @@ -0,0 +1,294 @@ +# StakingRewardsOs +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/StakingRewards/StakingRewardsOs.sol) + +**Inherits:** +[StakingRewardsOsStorage](/contracts/governance/StakingRewards/StakingRewardsOsStorage.sol/contract.StakingRewardsOsStorage.md), [Initializable](/contracts/openzeppelin/Initializable.sol/contract.Initializable.md) + +This is a trial incentive program. +In this, the osSOV minted to voluntary stakers and is locked until transferred to BitcoinOS + + +## Functions +### initialize + +Replacement of constructor by initialize function for Upgradable Contracts +This function will be called only once by the owner. + + +```solidity +function initialize(address _osSOV, IStaking _staking, uint256 _averageBlockTime) external onlyOwner initializer; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_osSOV`|`address`|osSOV token address| +|`_staking`|`IStaking`|StakingProxy address should be passed| +|`_averageBlockTime`|`uint256`|average block time used for calculating rewards| + + +### stop + +Stops the current rewards program. + +*Users will only get rewards up to the stop block* + + +```solidity +function stop() external onlyOwner; +``` + +### collectReward + +Collect rewards + +*User calls this function to collect osSOV staking rewards accrued by this contract +The weighted stake is calculated using getPriorWeightedStake. Block number sent to the functon +must be a finalised block, hence we deduct 1 from the current block. User is only allowed to withdraw +after intervals of 14 days.* + + +```solidity +function collectReward(uint256 _startTime) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_startTime`|`uint256`|The time from which to start the staking rewards calculation The issue is that we can only run for a max duration and if someone stakes for the first time after the max duration is over, the reward will always return 0. Thus, we need to restart from the duration that elapsed without generating rewards.| + + +### setAverageBlockTime + +Changes average block time - based on blockchain + +*If average block time significantly changes, we can update it here and use for block number calculation* + + +```solidity +function setAverageBlockTime(uint256 _averageBlockTime) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_averageBlockTime`|`uint256`|- average block time used for calculating checkpoint blocks| + + +### setBlock + +This function computes the last staking checkpoint and calculates the corresponding +block number using the average block time which is then added to the mapping `checkpointBlockNumber`. + + +```solidity +function setBlock() external; +``` + +### setHistoricalBlock + +This function computes the block number using the average block time for a given historical +checkpoint which is added to the mapping `checkpointBlockNumber`. + + +```solidity +function setHistoricalBlock(uint256 _time) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_time`|`uint256`|Exact staking checkpoint time| + + +### setMaxDuration + +Sets the max duration + +*Rewards can be collected for a maximum duration at a time. This +is to avoid Block Gas Limit failures. Setting it zero would mean that it will loop +through the entire duration since the start of rewards program. +It should ideally be set to a value, for which the rewards can be easily processed.* + + +```solidity +function setMaxDuration(uint256 _duration) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_duration`|`uint256`|Max duration for which rewards can be collected at a go (in seconds)| + + +### _computeWeightedStakeForDate + +Internal function to calculate weighted stake + +*Users will receive rewards uo till the stop block* + + +```solidity +function _computeWeightedStakeForDate(address _staker, uint256 _block, uint256 _date) + internal + view + returns (uint256 weightedStake); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_staker`|`address`|Staker address| +|`_block`|`uint256`|Last finalised block| +|`_date`|`uint256`|The date to compute prior weighted stakes| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`weightedStake`|`uint256`|The weighted stake| + + +### _payReward + +Internal function to pay rewards + +*Base rate is annual, but we pay interest for 14 days, +which is 1/26 of one staking year (1092 days)* + + +```solidity +function _payReward(address _staker, uint256 _amount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_staker`|`address`|Staker address| +|`_amount`|`uint256`|the reward amount| + + +### _getCurrentBlockNumber + +Determine the current Block Number + +*This is segregated from the _getPriorUserStakeByDate function to better test +advancing blocks functionality using Mock Contracts* + + +```solidity +function _getCurrentBlockNumber() internal view returns (uint256); +``` + +### _setBlock + +Internal function to calculate and set block + + +```solidity +function _setBlock(uint256 _checkpointTime) internal; +``` + +### getStakerCurrentReward + +Get staker's current accumulated reward + +*getStakerCurrentReward function internally calls this function to calculate reward amount of msg.sender* + + +```solidity +function getStakerCurrentReward(bool _considerMaxDuration, uint256 _startTime) + external + view + returns (uint256 nextWithdrawTimestamp, uint256 amount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_considerMaxDuration`|`bool`|True: Runs for the maximum duration - used in tx not to run out of gas False - to query total rewards| +|`_startTime`|`uint256`|The time from which the staking rewards calculation shall restart.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`nextWithdrawTimestamp`|`uint256`|The timestamp of last withdrawal| +|`amount`|`uint256`|The accumulated reward| + + +### getArbitraryStakerCurrentReward + +Get any staker's current accumulated reward + +*getArbitraryStakerCurrentReward function internally calls this function to calculate reward amount* + + +```solidity +function getArbitraryStakerCurrentReward(bool _considerMaxDuration, uint256 _startTime, address _staker) + external + view + returns (uint256 nextWithdrawTimestamp, uint256 amount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_considerMaxDuration`|`bool`|True: Runs for the maximum duration - used in tx not to run out of gas False - to query total rewards| +|`_startTime`|`uint256`|The time from which the staking rewards calculation shall restart.| +|`_staker`|`address`|The staker address to calculate rewards for| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`nextWithdrawTimestamp`|`uint256`|The timestamp of last withdrawal| +|`amount`|`uint256`|The accumulated reward| + + +### _getStakerCurrentReward + +Internal function to calculate staker's current reward + +*Normally the start time is 0. If this function returns a valid withdraw timestamp +and zero amount - that means there were no valid rewards for that period. So the new period must start +from the end of the last interval or till the time no rewards are accumulated i.e. _startTime* + + +```solidity +function _getStakerCurrentReward(address _staker, bool _considerMaxDuration, uint256 _startTime) + internal + view + returns (uint256 nextWithdrawTimestamp, uint256 amount); +``` + +## Events +### RewardWithdrawn +Emitted when osSOV is withdrawn + + +```solidity +event RewardWithdrawn(address indexed receiver, uint256 amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The address which recieves the osSOV| +|`amount`|`uint256`|The amount withdrawn from the Smart Contract| + +## Structs +### RewardsInterval +fromTimestamp - left boundary of the rewards interval + +toTimestamp - right boundary of the rewards interval + + +```solidity +struct RewardsInterval { + uint256 fromTimestamp; + uint256 toTimestamp; +} +``` + diff --git a/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOsProxy.sol/contract.StakingRewardsOsProxy.md b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOsProxy.sol/contract.StakingRewardsOsProxy.md new file mode 100644 index 000000000..a0c53f9df --- /dev/null +++ b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOsProxy.sol/contract.StakingRewardsOsProxy.md @@ -0,0 +1,12 @@ +# StakingRewardsOsProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/StakingRewards/StakingRewardsOsProxy.sol) + +**Inherits:** +[StakingRewardsOsStorage](/contracts/governance/StakingRewards/StakingRewardsOsStorage.sol/contract.StakingRewardsOsStorage.md), [UpgradableProxy](/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + +*StakingRewardsOs contract should be upgradable. Used UpgradableProxy. +StakingRewardsOsStorage is deployed with the upgradable functionality +by using this contract instead, that inherits from UpgradableProxy with +the possibility of being enhanced and re-deployed.* + + diff --git a/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOsStorage.sol/contract.StakingRewardsOsStorage.md b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOsStorage.sol/contract.StakingRewardsOsStorage.md new file mode 100644 index 000000000..a413b9c13 --- /dev/null +++ b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsOsStorage.sol/contract.StakingRewardsOsStorage.md @@ -0,0 +1,228 @@ +# StakingRewardsOsStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/StakingRewards/StakingRewardsOsStorage.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +Just the storage part of staking rewards contract, no functions, +only constant, variables and required structures (mappings). +Used by StackingRewardsProxy. +What is SOV staking rewards ? +The purpose of the SOV staking rewards program is to reward, +"marginal stakers" (ie, stakers by choice, not currently vesting) with liquid SOV +at the beginning of each new staking interval. + + +## State Variables +### TWO_WEEKS +2 weeks in seconds. + + +```solidity +uint256 public constant TWO_WEEKS = 1209600; +``` + + +### BASE_RATE +Annual Base Rate - it is the maximum interest rate(APY) + + +```solidity +uint256 public constant BASE_RATE = 900; +``` + + +### DIVISOR +DIVISOR is set as 2600000 = 26 (num periods per year) * 10 (max voting weight) * 10000 (900 -> 0.09) + + +```solidity +uint256 public constant DIVISOR = 2600000; +``` + + +### osSOV +The SOV token contract. + + +```solidity +IERC20Mintable internal osSOV; +``` + + +### staking +the staking proxy contract address + + +```solidity +IStaking internal staking; +``` + + +### maxDuration +Maximum duration to collect rewards at one go + + +```solidity +uint256 internal maxDuration; +``` + + +### rewardsProgramStartTime +Represents the time when the contract is deployed + + +```solidity +uint256 internal rewardsProgramStartTime; +``` + + +### stopBlock +Represents the block when the Staking Rewards pogram is stopped + + +```solidity +uint256 internal stopBlock; +``` + + +### stopRewardsTimestamp +Timestamp of the stopBlock adjusted to the staking lock timestamp + + +```solidity +uint256 internal stopRewardsTimestamp; +``` + + +### stakerNextWithdrawTimestamp +User Address -> Next Withdrawn Timestamp + + +```solidity +mapping(address => uint256) internal stakerNextWithdrawTimestamp; +``` + + +### claimedBalances +User Address -> Claimed Balance + + +```solidity +mapping(address => uint256) internal claimedBalances; +``` + + +### deploymentBlock +Represents the block when the StakingRwards Program is started + + +```solidity +uint256 internal deploymentBlock; +``` + + +### checkpointBlockNumber +BlockTime -> BlockNumber for a Staking Checkpoint + + +```solidity +mapping(uint256 => uint256) internal checkpointBlockNumber; +``` + + +### averageBlockTime +Average Block Time - making it flexible + + +```solidity +uint256 internal averageBlockTime; +``` + + +## Functions +### getCheckpointBlockNumber + +GETTERS + + +```solidity +function getCheckpointBlockNumber(uint256 _checkpointTimestamp) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_checkpointTimestamp`|`uint256`|Checkpoint timestamp| + + +### getOsSOV + + +```solidity +function getOsSOV() external view returns (IERC20Mintable); +``` + +### getStaking + + +```solidity +function getStaking() external view returns (IStaking); +``` + +### getMaxDuration + + +```solidity +function getMaxDuration() external view returns (uint256); +``` + +### getRewardsProgramStartTime + + +```solidity +function getRewardsProgramStartTime() external view returns (uint256); +``` + +### getStopBlock + + +```solidity +function getStopBlock() external view returns (uint256); +``` + +### getStopRewardsTimestamp + + +```solidity +function getStopRewardsTimestamp() external view returns (uint256); +``` + +### getStakerNextWithdrawTimestamp + + +```solidity +function getStakerNextWithdrawTimestamp(address _staker) external view returns (uint256); +``` + +### getDeploymentBlock + + +```solidity +function getDeploymentBlock() external view returns (uint256); +``` + +### getAverageBlockTime + + +```solidity +function getAverageBlockTime() external view returns (uint256); +``` + +### getClaimedBalances + + +```solidity +function getClaimedBalances(address _staker) external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsProxy.sol/contract.StakingRewardsProxy.md b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsProxy.sol/contract.StakingRewardsProxy.md new file mode 100644 index 000000000..6d4c12f27 --- /dev/null +++ b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsProxy.sol/contract.StakingRewardsProxy.md @@ -0,0 +1,12 @@ +# StakingRewardsProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/StakingRewards/StakingRewardsProxy.sol) + +**Inherits:** +[StakingRewardsStorage](/contracts/governance/StakingRewards/StakingRewardsStorage.sol/contract.StakingRewardsStorage.md), [UpgradableProxy](/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + +*StakingRewards contract should be upgradable. Used UpgradableProxy. +StakingRewardsStorage is deployed with the upgradable functionality +by using this contract instead, that inherits from UpgradableProxy with +the possibility of being enhanced and re-deployed.* + + diff --git a/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsStorage.sol/contract.StakingRewardsStorage.md b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsStorage.sol/contract.StakingRewardsStorage.md new file mode 100644 index 000000000..1862b0e8c --- /dev/null +++ b/foundry/docs/src/contracts/governance/StakingRewards/StakingRewardsStorage.sol/contract.StakingRewardsStorage.md @@ -0,0 +1,153 @@ +# StakingRewardsStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/StakingRewards/StakingRewardsStorage.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +Just the storage part of staking rewards contract, no functions, +only constant, variables and required structures (mappings). +Used by StackingRewardsProxy. +What is SOV staking rewards - SIP-0024? +The purpose of the SOV staking rewards - SIP-0024 is to reward, +"marginal stakers" (ie, stakers by choice, not currently vesting) with liquid SOV +at the beginning of each new staking interval. + + +## State Variables +### SOV +The SOV token contract. + + +```solidity +IERC20 public SOV; +``` + + +### staking +the staking proxy contract address + + +```solidity +IStaking public staking; +``` + + +### TWO_WEEKS +2 weeks in seconds. + + +```solidity +uint256 public constant TWO_WEEKS = 1209600; +``` + + +### BASE_RATE +Annual Base Rate - it is the maximum interest rate(APY) + + +```solidity +uint256 public constant BASE_RATE = 2975; +``` + + +### DIVISOR +DIVISOR is set as 2600000 = 26 (num periods per year) * 10 (max voting weight) * 10000 (2975 -> 0.2975) + + +```solidity +uint256 public constant DIVISOR = 2600000; +``` + + +### maxDuration +Maximum duration to collect rewards at one go + + +```solidity +uint256 public maxDuration; +``` + + +### startTime +Represents the time when the contract is deployed + + +```solidity +uint256 public startTime; +``` + + +### stopBlock +Represents the block when the Staking Rewards pogram is stopped + + +```solidity +uint256 public stopBlock; +``` + + +### withdrawals +User Address -> Last Withdrawn Timestamp + + +```solidity +mapping(address => uint256) public withdrawals; +``` + + +### claimedBalances +User Address -> Claimed Balance + + +```solidity +mapping(address => uint256) public claimedBalances; +``` + + +### deploymentBlock +Represents the block when the StakingRwards Program is started + + +```solidity +uint256 public deploymentBlock; +``` + + +### _initialized +Moved the variables from Initializable contract to resolve issue caused by incorrect Inheritance Order + +*Indicates that the contract has been initialized.* + + +```solidity +bool private _initialized; +``` + + +### _initializing +*Indicates that the contract is in the process of being initialized.* + + +```solidity +bool private _initializing; +``` + + +### checkpointBlockDetails +BlockTime -> BlockNumber for a Staking Checkpoint + + +```solidity +mapping(uint256 => uint256) public checkpointBlockDetails; +``` + + +### averageBlockTime +Average Block Time - making it flexible + + +```solidity +uint256 public averageBlockTime; +``` + + diff --git a/foundry/docs/src/contracts/governance/Timelock.sol/contract.Timelock.md b/foundry/docs/src/contracts/governance/Timelock.sol/contract.Timelock.md new file mode 100644 index 000000000..cc302d4a6 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Timelock.sol/contract.Timelock.md @@ -0,0 +1,264 @@ +# Timelock +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Timelock.sol) + +**Inherits:** +[ErrorDecoder](/contracts/governance/ErrorDecoder.sol/contract.ErrorDecoder.md), [ITimelock](/contracts/governance/Timelock.sol/interface.ITimelock.md) + +This contract lets Sovryn governance system set up its +own Time Lock instance to execute transactions proposed through the +GovernorAlpha contract instance. +The Timelock contract allows its admin (Sovryn governance on +GovernorAlpha contract) to add arbitrary function calls to a +queue. This contract can only execute a function call if the +function call has been in the queue for at least 3 hours. +Anytime the Timelock contract makes a function call, it must be the +case that the function call was first made public by having been publicly +added to the queue at least 3 hours prior. +The intention is to provide GovernorAlpha contract the functionality to +queue proposal actions. This would mean that any changes made by Sovryn +governance of any contract would necessarily come with at least an +advanced warning. This makes the Sovryn system follow a “time-delayed, +opt-out” upgrade pattern (rather than an “instant, forced” upgrade pattern). +Time-delaying admin actions gives users a chance to exit system if its +admins become malicious or compromised (or make a change that the users +do not like). Downside is that honest admins would be unable +to lock down functionality to protect users if a critical bug was found. +Delayed transactions reduce the amount of trust required by users of Sovryn +and the overall risk for contracts building on top of it, as GovernorAlpha. + + +## State Variables +### GRACE_PERIOD + +```solidity +uint256 public constant GRACE_PERIOD = 14 days; +``` + + +### MINIMUM_DELAY + +```solidity +uint256 public constant MINIMUM_DELAY = 3 hours; +``` + + +### MAXIMUM_DELAY + +```solidity +uint256 public constant MAXIMUM_DELAY = 30 days; +``` + + +### admin + +```solidity +address public admin; +``` + + +### pendingAdmin + +```solidity +address public pendingAdmin; +``` + + +### delay + +```solidity +uint256 public delay; +``` + + +### queuedTransactions + +```solidity +mapping(bytes32 => bool) public queuedTransactions; +``` + + +## Functions +### constructor + +Function called on instance deployment of the contract. + + +```solidity +constructor(address admin_, uint256 delay_) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`admin_`|`address`|Governance contract address.| +|`delay_`|`uint256`|Time to wait for queued transactions to be executed.| + + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external payable; +``` + +### setDelay + +Set a new delay when executing the contract calls. + + +```solidity +function setDelay(uint256 delay_) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`delay_`|`uint256`|The amount of time to wait until execution.| + + +### acceptAdmin + +Accept a new admin for the timelock. + + +```solidity +function acceptAdmin() public; +``` + +### setPendingAdmin + +Set a new pending admin for the timelock. + + +```solidity +function setPendingAdmin(address pendingAdmin_) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`pendingAdmin_`|`address`|The new pending admin address.| + + +### queueTransaction + +Queue a new transaction from the governance contract. + + +```solidity +function queueTransaction(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) + public + returns (bytes32); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The contract to call.| +|`value`|`uint256`|The amount to send in the transaction.| +|`signature`|`string`|The stanndard representation of the function called.| +|`data`|`bytes`|The ethereum transaction input data payload.| +|`eta`|`uint256`|Estimated Time of Accomplishment. The timestamp that the proposal will be available for execution, set once the vote succeeds.| + + +### cancelTransaction + +Cancel a transaction. + + +```solidity +function cancelTransaction(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) + public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The contract to call.| +|`value`|`uint256`|The amount to send in the transaction.| +|`signature`|`string`|The stanndard representation of the function called.| +|`data`|`bytes`|The ethereum transaction input data payload.| +|`eta`|`uint256`|Estimated Time of Accomplishment. The timestamp that the proposal will be available for execution, set once the vote succeeds.| + + +### executeTransaction + +Executes a previously queued transaction from the governance. + + +```solidity +function executeTransaction(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) + public + payable + returns (bytes memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The contract to call.| +|`value`|`uint256`|The amount to send in the transaction.| +|`signature`|`string`|The stanndard representation of the function called.| +|`data`|`bytes`|The ethereum transaction input data payload.| +|`eta`|`uint256`|Estimated Time of Accomplishment. The timestamp that the proposal will be available for execution, set once the vote succeeds.| + + +### getBlockTimestamp + +A function used to get the current Block Timestamp. + +*Timestamp of the current block in seconds since the epoch. +It is a Unix time stamp. So, it has the complete information about +the date, hours, minutes, and seconds (in UTC) when the block was +created.* + + +```solidity +function getBlockTimestamp() internal view returns (uint256); +``` + +## Events +### NewAdmin + +```solidity +event NewAdmin(address indexed newAdmin); +``` + +### NewPendingAdmin + +```solidity +event NewPendingAdmin(address indexed newPendingAdmin); +``` + +### NewDelay + +```solidity +event NewDelay(uint256 indexed newDelay); +``` + +### CancelTransaction + +```solidity +event CancelTransaction( + bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta +); +``` + +### ExecuteTransaction + +```solidity +event ExecuteTransaction( + bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta +); +``` + +### QueueTransaction + +```solidity +event QueueTransaction( + bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta +); +``` + diff --git a/foundry/docs/src/contracts/governance/Timelock.sol/interface.ITimelock.md b/foundry/docs/src/contracts/governance/Timelock.sol/interface.ITimelock.md new file mode 100644 index 000000000..bb72cdbb6 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Timelock.sol/interface.ITimelock.md @@ -0,0 +1,60 @@ +# ITimelock +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Timelock.sol) + + +## Functions +### delay + + +```solidity +function delay() external view returns (uint256); +``` + +### GRACE_PERIOD + + +```solidity +function GRACE_PERIOD() external view returns (uint256); +``` + +### acceptAdmin + + +```solidity +function acceptAdmin() external; +``` + +### queuedTransactions + + +```solidity +function queuedTransactions(bytes32 hash) external view returns (bool); +``` + +### queueTransaction + + +```solidity +function queueTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) + external + returns (bytes32); +``` + +### cancelTransaction + + +```solidity +function cancelTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) + external; +``` + +### executeTransaction + + +```solidity +function executeTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) + external + payable + returns (bytes memory); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/DevelopmentFund.sol/contract.DevelopmentFund.md b/foundry/docs/src/contracts/governance/Vesting/DevelopmentFund.sol/contract.DevelopmentFund.md new file mode 100644 index 000000000..a7e567e1d --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/DevelopmentFund.sol/contract.DevelopmentFund.md @@ -0,0 +1,504 @@ +# DevelopmentFund +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/DevelopmentFund.sol) + +**Author:** +Franklin Richards + +You can use this contract for timed token release from Dev Fund. + + +## State Variables +### SOV +The SOV token contract. + + +```solidity +IERC20 public SOV; +``` + + +### status + +```solidity +Status public status; +``` + + +### lockedTokenOwner +The owner of the locked tokens (usually Governance). + + +```solidity +address public lockedTokenOwner; +``` + + +### unlockedTokenOwner +The owner of the unlocked tokens (usually MultiSig). + + +```solidity +address public unlockedTokenOwner; +``` + + +### safeVault +The emergency transfer wallet/contract. + + +```solidity +address public safeVault; +``` + + +### newLockedTokenOwner +The new locked token owner waiting to be approved. + + +```solidity +address public newLockedTokenOwner; +``` + + +### lastReleaseTime +The last token release timestamp or the time of contract creation. + + +```solidity +uint256 public lastReleaseTime; +``` + + +### releaseDuration +The release duration array in seconds. + + +```solidity +uint256[] public releaseDuration; +``` + + +### releaseTokenAmount +The release token amount. + + +```solidity +uint256[] public releaseTokenAmount; +``` + + +## Functions +### onlyLockedTokenOwner + + +```solidity +modifier onlyLockedTokenOwner(); +``` + +### onlyUnlockedTokenOwner + + +```solidity +modifier onlyUnlockedTokenOwner(); +``` + +### checkStatus + + +```solidity +modifier checkStatus(Status s); +``` + +### constructor + +Setup the required parameters. + +*Initial release schedule should be verified, error will result in either redeployment or calling changeTokenReleaseSchedule() after init() along with token transfer.* + + +```solidity +constructor( + address _SOV, + address _lockedTokenOwner, + address _safeVault, + address _unlockedTokenOwner, + uint256 _lastReleaseTime, + uint256[] memory _releaseDuration, + uint256[] memory _releaseTokenAmount +) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`address`|The SOV token address.| +|`_lockedTokenOwner`|`address`|The owner of the locked tokens & contract.| +|`_safeVault`|`address`|The emergency wallet/contract to transfer token.| +|`_unlockedTokenOwner`|`address`|The owner of the unlocked tokens.| +|`_lastReleaseTime`|`uint256`|If the last release time is to be changed, zero if no change required.| +|`_releaseDuration`|`uint256[]`|The time duration between each release calculated from `lastReleaseTime` in seconds.| +|`_releaseTokenAmount`|`uint256[]`|The amount of token to be released in each duration/interval.| + + +### init + +If last release time passed is zero, then current time stamp will be used as the last release time. +Checking if the schedule duration and token allocation length matches. +Finally we update the token release schedule. + +This function is called once after deployment for token transfer based on schedule. + +*Without calling this function, the contract will not work.* + + +```solidity +function init() public checkStatus(Status.Deployed); +``` + +### updateLockedTokenOwner + +Getting the current release schedule total token amount. + +Update Locked Token Owner. + + +```solidity +function updateLockedTokenOwner(address _newLockedTokenOwner) public onlyLockedTokenOwner checkStatus(Status.Active); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newLockedTokenOwner`|`address`|The owner of the locked tokens & contract.| + + +### approveLockedTokenOwner + +Approve Locked Token Owner. + +*This approval is an added security to avoid development fund takeover by a compromised locked token owner.* + + +```solidity +function approveLockedTokenOwner() public onlyUnlockedTokenOwner checkStatus(Status.Active); +``` + +### updateUnlockedTokenOwner + +Update Unlocked Token Owner. + + +```solidity +function updateUnlockedTokenOwner(address _newUnlockedTokenOwner) + public + onlyLockedTokenOwner + checkStatus(Status.Active); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newUnlockedTokenOwner`|`address`|The new unlocked token owner.| + + +### depositTokens + +Deposit tokens to this contract. + +*These tokens can be withdrawn/transferred any time by the lockedTokenOwner.* + + +```solidity +function depositTokens(uint256 _amount) public checkStatus(Status.Active); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|the amount of tokens deposited.| + + +### changeTokenReleaseSchedule + +Change the Token release schedule. It creates a completely new schedule, and does not append on the previous one. + +*_releaseDuration and _releaseTokenAmount should be specified in reverse order of release.* + + +```solidity +function changeTokenReleaseSchedule( + uint256 _newLastReleaseTime, + uint256[] memory _releaseDuration, + uint256[] memory _releaseTokenAmount +) public onlyLockedTokenOwner checkStatus(Status.Active); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newLastReleaseTime`|`uint256`|If the last release time is to be changed, zero if no change required.| +|`_releaseDuration`|`uint256[]`|The time duration between each release calculated from `lastReleaseTime` in seconds.| +|`_releaseTokenAmount`|`uint256[]`|The amount of token to be released in each duration/interval.| + + +### transferTokensByUnlockedTokenOwner + +Checking if the schedule duration and token allocation length matches. +If the last release time has to be changed, then you can pass a new one here. +Or else, the duration of release will be calculated based on this timestamp. +Even a future timestamp can be mentioned here. +Checking if the contract have enough token balance for the release. +Getting the current token balance of the contract. +If the token balance is not sufficient, then we transfer the change to contract. +If there are more tokens than required, send the extra tokens back. +Finally we update the token release schedule. + +Transfers all of the remaining tokens in an emergency situation. + +*This could be called when governance or development fund might be compromised.* + + +```solidity +function transferTokensByUnlockedTokenOwner() public onlyUnlockedTokenOwner checkStatus(Status.Active); +``` + +### withdrawTokensByUnlockedTokenOwner + +Withdraws all unlocked/released token. + + +```solidity +function withdrawTokensByUnlockedTokenOwner(uint256 _amount) public onlyUnlockedTokenOwner checkStatus(Status.Active); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|The amount to be withdrawn.| + + +### transferTokensByLockedTokenOwner + +To know how many elements to be removed from the release schedule. +To know the total amount to be transferred. +Better to use memory than storage. +Also checks if there are any elements in the release schedule. +Getting the amount of tokens, the number of releases and calculating the total duration. +This will be the last case, if correct amount is passed. +Checking to see if atleast a single schedule was reached or not. +If locked token owner tries to send a higher amount that schedule +Now clearing up the release schedule. +Updating the last release time. +Sending the amount to unlocked token owner. + +Transfers all of the remaining tokens by the owner maybe for an upgrade. + +*This could be called when the current development fund has to be upgraded.* + + +```solidity +function transferTokensByLockedTokenOwner(address _receiver) public onlyLockedTokenOwner checkStatus(Status.Active); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|The address which receives this token transfer.| + + +### getReleaseDuration + +Function to read the current token release duration. + + +```solidity +function getReleaseDuration() public view returns (uint256[] memory _releaseTokenDuration); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_releaseTokenDuration`|`uint256[]`|_currentReleaseDuration The current release duration.| + + +### getReleaseTokenAmount + +Function to read the current token release amount. + + +```solidity +function getReleaseTokenAmount() public view returns (uint256[] memory _currentReleaseTokenAmount); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_currentReleaseTokenAmount`|`uint256[]`|The current release token amount.| + + +## Events +### DevelopmentFundActivated +Emitted when the contract is activated. + + +```solidity +event DevelopmentFundActivated(); +``` + +### DevelopmentFundExpired +Emitted when the contract is expired due to total token transfer. + + +```solidity +event DevelopmentFundExpired(); +``` + +### NewLockedOwnerAdded +Emitted when a new locked owner is added to the contract. + +*Can only be initiated by the current locked owner.* + + +```solidity +event NewLockedOwnerAdded(address indexed _initiator, address indexed _newLockedOwner); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_newLockedOwner`|`address`|The address which is added as the new locked owner.| + +### NewLockedOwnerApproved +Emitted when a new locked owner is approved to the contract. + +*Can only be initiated by the current unlocked owner.* + + +```solidity +event NewLockedOwnerApproved( + address indexed _initiator, address indexed _oldLockedOwner, address indexed _newLockedOwner +); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_oldLockedOwner`|`address`|The address of the previous locked owner.| +|`_newLockedOwner`|`address`|The address which is added as the new locked owner.| + +### UnlockedOwnerUpdated +Emitted when a new unlocked owner is updated in the contract. + +*Can only be initiated by the current locked owner.* + + +```solidity +event UnlockedOwnerUpdated(address indexed _initiator, address indexed _newUnlockedOwner); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_newUnlockedOwner`|`address`|The address which is updated as the new unlocked owner.| + +### TokenDeposit +Emitted when a new token deposit is done. + + +```solidity +event TokenDeposit(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The total amount of token deposited.| + +### TokenReleaseChanged +Emitted when a new release schedule is created. + + +```solidity +event TokenReleaseChanged(address indexed _initiator, uint256 _releaseCount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_releaseCount`|`uint256`|The number of releases planned in the schedule.| + +### LockedTokenTransferByUnlockedOwner +Emitted when a unlocked owner transfers all the tokens to a safe vault. + +*This is done in an emergency situation only to a predetermined wallet by locked token owner.* + + +```solidity +event LockedTokenTransferByUnlockedOwner(address indexed _initiator, address indexed _receiver, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_receiver`|`address`|The address which receives this token withdrawn.| +|`_amount`|`uint256`|The total amount of token transferred.| + +### UnlockedTokenWithdrawalByUnlockedOwner +Emitted when a unlocked owner withdraws the released tokens. + + +```solidity +event UnlockedTokenWithdrawalByUnlockedOwner(address indexed _initiator, uint256 _amount, uint256 _releaseCount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The total amount of token withdrawn.| +|`_releaseCount`|`uint256`|The total number of releases done based on duration.| + +### LockedTokenTransferByLockedOwner +Emitted when a locked owner transfers all the tokens to a receiver. + +*This is done only by locked token owner.* + + +```solidity +event LockedTokenTransferByLockedOwner(address indexed _initiator, address indexed _receiver, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_receiver`|`address`|The address which receives this token transfer.| +|`_amount`|`uint256`|The total amount of token transferred.| + +## Enums +### Status +The current contract status. + + +```solidity +enum Status { + Deployed, + Active, + Expired +} +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/GenericTokenSender.sol/contract.GenericTokenSender.md b/foundry/docs/src/contracts/governance/Vesting/GenericTokenSender.sol/contract.GenericTokenSender.md new file mode 100644 index 000000000..dfdb331b1 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/GenericTokenSender.sol/contract.GenericTokenSender.md @@ -0,0 +1,69 @@ +# GenericTokenSender +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/GenericTokenSender.sol) + +**Inherits:** +[AdminRole](/contracts/utils/AdminRole.sol/contract.AdminRole.md) + +This contract includes functions to transfer tokens +to a recipient or to several recipients in a list. There is +an ACL control check by modifier. + + +## Functions +### transferTokensUsingList + +Transfer given amounts of tokens to the given addresses. + + +```solidity +function transferTokensUsingList(address _token, address[] calldata _receivers, uint256[] calldata _amounts) + external + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|The address of the token.| +|`_receivers`|`address[]`|The addresses of the receivers.| +|`_amounts`|`uint256[]`|The amounts to be transferred.| + + +### function + + +```solidity +function() external payable; +``` + +### transferTokens + +Transfer tokens to given address. + + +```solidity +function transferTokens(address _token, address _receiver, uint256 _amount) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_token`|`address`|The address of the token.| +|`_receiver`|`address`|The address of the token receiver.| +|`_amount`|`uint256`|The amount to be transferred.| + + +### _transferTokens + + +```solidity +function _transferTokens(address _token, address _receiver, uint256 _amount) internal; +``` + +## Events +### TokensTransferred + +```solidity +event TokensTransferred(address indexed token, address indexed receiver, uint256 amount); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/ITeamVesting.sol/interface.ITeamVesting.md b/foundry/docs/src/contracts/governance/Vesting/ITeamVesting.sol/interface.ITeamVesting.md new file mode 100644 index 000000000..0dc18b394 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/ITeamVesting.sol/interface.ITeamVesting.md @@ -0,0 +1,51 @@ +# ITeamVesting +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/ITeamVesting.sol) + +*Interfaces are used to cast a contract address into a callable instance. +This interface is used by Staking contract to cancel the team vesting +function having the vesting contract instance address.* + + +## Functions +### startDate + + +```solidity +function startDate() external view returns (uint256); +``` + +### cliff + + +```solidity +function cliff() external view returns (uint256); +``` + +### endDate + + +```solidity +function endDate() external view returns (uint256); +``` + +### duration + + +```solidity +function duration() external view returns (uint256); +``` + +### tokenOwner + + +```solidity +function tokenOwner() external view returns (address); +``` + +### governanceWithdrawTokens + + +```solidity +function governanceWithdrawTokens(address receiver) external; +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/IVesting.sol/interface.IVesting.md b/foundry/docs/src/contracts/governance/Vesting/IVesting.sol/interface.IVesting.md new file mode 100644 index 000000000..0707820bc --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/IVesting.sol/interface.IVesting.md @@ -0,0 +1,38 @@ +# IVesting +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/IVesting.sol) + +*Interfaces are used to cast a contract address into a callable instance. +This interface is used by VestingLogic contract to implement stakeTokens function +and on VestingRegistry contract to call IVesting(vesting).stakeTokens function +at a vesting instance.* + + +## Functions +### duration + + +```solidity +function duration() external returns (uint256); +``` + +### endDate + + +```solidity +function endDate() external returns (uint256); +``` + +### stakeTokens + + +```solidity +function stakeTokens(uint256 amount) external; +``` + +### tokenOwner + + +```solidity +function tokenOwner() external view returns (address); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/IVestingFactory.sol/interface.IVestingFactory.md b/foundry/docs/src/contracts/governance/Vesting/IVestingFactory.sol/interface.IVestingFactory.md new file mode 100644 index 000000000..a9905273d --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/IVestingFactory.sol/interface.IVestingFactory.md @@ -0,0 +1,40 @@ +# IVestingFactory +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/IVestingFactory.sol) + +*Interfaces are used to cast a contract address into a callable instance. +This interface is used by VestingFactory contract to override empty +implemention of deployVesting and deployTeamVesting functions +and on VestingRegistry contract to use an instance of VestingFactory.* + + +## Functions +### deployVesting + + +```solidity +function deployVesting( + address _SOV, + address _staking, + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + address _feeSharing, + address _owner +) external returns (address); +``` + +### deployTeamVesting + + +```solidity +function deployTeamVesting( + address _SOV, + address _staking, + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + address _feeSharing, + address _owner +) external returns (address); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/IVestingRegistry.sol/interface.IVestingRegistry.md b/foundry/docs/src/contracts/governance/Vesting/IVestingRegistry.sol/interface.IVestingRegistry.md new file mode 100644 index 000000000..86365995a --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/IVestingRegistry.sol/interface.IVestingRegistry.md @@ -0,0 +1,42 @@ +# IVestingRegistry +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/IVestingRegistry.sol) + +*Interfaces are used to cast a contract address into a callable instance.* + + +## Functions +### getVesting + + +```solidity +function getVesting(address _tokenOwner) external view returns (address); +``` + +### getTeamVesting + + +```solidity +function getTeamVesting(address _tokenOwner) external view returns (address); +``` + +### setVestingRegistry + + +```solidity +function setVestingRegistry(address _vestingRegistryProxy) external; +``` + +### isVestingAddress + + +```solidity +function isVestingAddress(address _vestingAddress) external view returns (bool); +``` + +### isTeamVesting + + +```solidity +function isTeamVesting(address _vestingAddress) external view returns (bool); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/OriginInvestorsClaim.sol/contract.OriginInvestorsClaim.md b/foundry/docs/src/contracts/governance/Vesting/OriginInvestorsClaim.sol/contract.OriginInvestorsClaim.md new file mode 100644 index 000000000..1cb1bfce1 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/OriginInvestorsClaim.sol/contract.OriginInvestorsClaim.md @@ -0,0 +1,294 @@ +# OriginInvestorsClaim +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/OriginInvestorsClaim.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +// TODO: fund this contract with a total amount of SOV needed to distribute. + + +## State Variables +### totalAmount +VestingRegistry public constant vestingRegistry = VestingRegistry(0x80B036ae59B3e38B573837c01BB1DB95515b7E6B); + + +```solidity +uint256 public totalAmount; +``` + + +### SOV_VESTING_CLIFF +Constant used for computing the vesting dates. + + +```solidity +uint256 public constant SOV_VESTING_CLIFF = 6 weeks; +``` + + +### kickoffTS + +```solidity +uint256 public kickoffTS; +``` + + +### vestingTerm + +```solidity +uint256 public vestingTerm; +``` + + +### investorsQty + +```solidity +uint256 public investorsQty; +``` + + +### investorsListInitialized + +```solidity +bool public investorsListInitialized; +``` + + +### vestingRegistry + +```solidity +VestingRegistry public vestingRegistry; +``` + + +### staking + +```solidity +IStaking public staking; +``` + + +### SOVToken + +```solidity +IERC20 public SOVToken; +``` + + +### admins +*user => flag : Whether user has admin role.* + + +```solidity +mapping(address => bool) public admins; +``` + + +### investorsAmountsList +*investor => Amount : Origin investors entitled to claim SOV.* + + +```solidity +mapping(address => uint256) public investorsAmountsList; +``` + + +## Functions +### onlyAuthorized + +*Throws if called by any account other than the owner or admin.* + + +```solidity +modifier onlyAuthorized(); +``` + +### onlyWhitelisted + +*Throws if called by any account not whitelisted.* + + +```solidity +modifier onlyWhitelisted(); +``` + +### notInitialized + +*Throws if called w/ an initialized investors list.* + + +```solidity +modifier notInitialized(); +``` + +### initialized + +*Throws if called w/ an uninitialized investors list.* + + +```solidity +modifier initialized(); +``` + +### constructor + +Contract deployment requires one parameter: + + +```solidity +constructor(address vestingRegistryAddress) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`vestingRegistryAddress`|`address`|The vestingRegistry contract instance address.| + + +### addAdmin + +Add account to ACL. + + +```solidity +function addAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to grant permissions.| + + +### removeAdmin + +Remove account from ACL. + + +```solidity +function removeAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to revoke permissions.| + + +### authorizedBalanceWithdraw + +In case we have unclaimed tokens or in emergency case +this function transfers all SOV tokens to a given address. + + +```solidity +function authorizedBalanceWithdraw(address toAddress) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`toAddress`|`address`|The recipient address of all this contract tokens.| + + +### setInvestorsAmountsListInitialized + +Should be called after the investors list setup completed. +This function checks whether the SOV token balance of the contract is +enough and sets status list to initialized. + + +```solidity +function setInvestorsAmountsListInitialized() public onlyAuthorized notInitialized; +``` + +### appendInvestorsAmountsList + +The contract should be approved or transferred necessary +amount of SOV prior to calling the function. + + +```solidity +function appendInvestorsAmountsList(address[] calldata investors, uint256[] calldata claimAmounts) + external + onlyAuthorized + notInitialized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`investors`|`address[]`|The list of investors addresses to add to the list. Duplicates will be skipped.| +|`claimAmounts`|`uint256[]`|The list of amounts for investors investors[i] will receive claimAmounts[i] of SOV.| + + +### claim + +Claim tokens from this contract. +If vestingTerm is not yet achieved a vesting is created. +Otherwise tokens are tranferred. + + +```solidity +function claim() external onlyWhitelisted initialized; +``` + +### createVesting + +Transfer tokens from this contract to a vestingRegistry contract. +Sender is removed from investor list and all its unvested tokens +are sent to vesting contract. + + +```solidity +function createVesting() internal; +``` + +### transfer + +Transfer tokens from this contract to the sender. +Sender is removed from investor list and all its unvested tokens +are sent to its account. + + +```solidity +function transfer() internal; +``` + +## Events +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + +### InvestorsAmountsListAppended + +```solidity +event InvestorsAmountsListAppended(uint256 qty, uint256 amount); +``` + +### ClaimVested + +```solidity +event ClaimVested(address indexed investor, uint256 amount); +``` + +### ClaimTransferred + +```solidity +event ClaimTransferred(address indexed investor, uint256 amount); +``` + +### InvestorsAmountsListInitialized + +```solidity +event InvestorsAmountsListInitialized(uint256 qty, uint256 totalAmount); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/OrigingVestingCreator.sol/contract.OrigingVestingCreator.md b/foundry/docs/src/contracts/governance/Vesting/OrigingVestingCreator.sol/contract.OrigingVestingCreator.md new file mode 100644 index 000000000..2f76002c4 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/OrigingVestingCreator.sol/contract.OrigingVestingCreator.md @@ -0,0 +1,51 @@ +# OrigingVestingCreator +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/OrigingVestingCreator.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +It casts an instance of vestingRegistry and by using createVesting +function it creates a vesting, gets it and stakes some tokens w/ this vesting. + + +## State Variables +### vestingRegistry + +```solidity +VestingRegistry public vestingRegistry; +``` + + +### processedList + +```solidity +mapping(address => bool) processedList; +``` + + +## Functions +### constructor + + +```solidity +constructor(address _vestingRegistry) public; +``` + +### createVesting + +Create a vesting, get it and stake some tokens w/ this vesting. + + +```solidity +function createVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_amount`|`uint256`|The amount of tokens to be vested.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + + diff --git a/foundry/docs/src/contracts/governance/Vesting/README.md b/foundry/docs/src/contracts/governance/Vesting/README.md new file mode 100644 index 000000000..39af81dbc --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/README.md @@ -0,0 +1,25 @@ + + +# Contents +- [fouryear](/contracts/governance/Vesting/fouryear) +- [DevelopmentFund](DevelopmentFund.sol/contract.DevelopmentFund.md) +- [GenericTokenSender](GenericTokenSender.sol/contract.GenericTokenSender.md) +- [ITeamVesting](ITeamVesting.sol/interface.ITeamVesting.md) +- [IVesting](IVesting.sol/interface.IVesting.md) +- [IVestingFactory](IVestingFactory.sol/interface.IVestingFactory.md) +- [IVestingRegistry](IVestingRegistry.sol/interface.IVestingRegistry.md) +- [OriginInvestorsClaim](OriginInvestorsClaim.sol/contract.OriginInvestorsClaim.md) +- [OrigingVestingCreator](OrigingVestingCreator.sol/contract.OrigingVestingCreator.md) +- [TeamVesting](TeamVesting.sol/contract.TeamVesting.md) +- [TokenSender](TokenSender.sol/contract.TokenSender.md) +- [Vesting](Vesting.sol/contract.Vesting.md) +- [VestingCreator](VestingCreator.sol/contract.VestingCreator.md) +- [VestingFactory](VestingFactory.sol/contract.VestingFactory.md) +- [VestingLogic](VestingLogic.sol/contract.VestingLogic.md) +- [VestingRegistry](VestingRegistry.sol/contract.VestingRegistry.md) +- [VestingRegistry2](VestingRegistry2.sol/contract.VestingRegistry2.md) +- [VestingRegistry3](VestingRegistry3.sol/contract.VestingRegistry3.md) +- [VestingRegistryLogic](VestingRegistryLogic.sol/contract.VestingRegistryLogic.md) +- [VestingRegistryProxy](VestingRegistryProxy.sol/contract.VestingRegistryProxy.md) +- [VestingRegistryStorage](VestingRegistryStorage.sol/contract.VestingRegistryStorage.md) +- [VestingStorage](VestingStorage.sol/contract.VestingStorage.md) diff --git a/foundry/docs/src/contracts/governance/Vesting/TeamVesting.sol/contract.TeamVesting.md b/foundry/docs/src/contracts/governance/Vesting/TeamVesting.sol/contract.TeamVesting.md new file mode 100644 index 000000000..16dc46f71 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/TeamVesting.sol/contract.TeamVesting.md @@ -0,0 +1,43 @@ +# TeamVesting +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/TeamVesting.sol) + +**Inherits:** +[VestingStorage](/contracts/governance/Vesting/VestingStorage.sol/contract.VestingStorage.md), [Proxy](/contracts/proxy/Proxy.sol/contract.Proxy.md) + +A regular vesting contract, but the owner (governance) is able to +withdraw earlier without a slashing. + +*Vesting contracts shouldn't be upgradable, +use Proxy instead of UpgradableProxy.* + + +## Functions +### constructor + +Setup the vesting schedule. + + +```solidity +constructor( + address _logic, + address _SOV, + address _stakingAddress, + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + address _feeSharingCollector +) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_logic`|`address`|The address of logic contract.| +|`_SOV`|`address`|The SOV token address.| +|`_stakingAddress`|`address`|| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| +|`_feeSharingCollector`|`address`|| + + diff --git a/foundry/docs/src/contracts/governance/Vesting/TokenSender.sol/contract.TokenSender.md b/foundry/docs/src/contracts/governance/Vesting/TokenSender.sol/contract.TokenSender.md new file mode 100644 index 000000000..598c3ce5c --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/TokenSender.sol/contract.TokenSender.md @@ -0,0 +1,135 @@ +# TokenSender +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/TokenSender.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +This contract includes functions to transfer SOV tokens +to a recipient or to several recipients in a list. There is +an ACL control check by modifier. + + +## State Variables +### SOV +The SOV token contract. + + +```solidity +address public SOV; +``` + + +### admins +*user => flag whether user has admin role* + + +```solidity +mapping(address => bool) public admins; +``` + + +## Functions +### constructor + + +```solidity +constructor(address _SOV) public; +``` + +### onlyAuthorized + +*Throws if called by any account other than the owner or admin.* + + +```solidity +modifier onlyAuthorized(); +``` + +### addAdmin + +Add account to ACL. + + +```solidity +function addAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to grant permissions.| + + +### removeAdmin + +Remove account from ACL. + + +```solidity +function removeAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to revoke permissions.| + + +### transferSOVusingList + +Transfer given amounts of SOV to the given addresses. + + +```solidity +function transferSOVusingList(address[] memory _receivers, uint256[] memory _amounts) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receivers`|`address[]`|The addresses of the SOV receivers.| +|`_amounts`|`uint256[]`|The amounts to be transferred.| + + +### transferSOV + +Transfer SOV tokens to given address. + + +```solidity +function transferSOV(address _receiver, uint256 _amount) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|The address of the SOV receiver.| +|`_amount`|`uint256`|The amount to be transferred.| + + +### _transferSOV + + +```solidity +function _transferSOV(address _receiver, uint256 _amount) internal; +``` + +## Events +### SOVTransferred + +```solidity +event SOVTransferred(address indexed receiver, uint256 amount); +``` + +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/Vesting.sol/contract.Vesting.md b/foundry/docs/src/contracts/governance/Vesting/Vesting.sol/contract.Vesting.md new file mode 100644 index 000000000..b80822639 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/Vesting.sol/contract.Vesting.md @@ -0,0 +1,55 @@ +# Vesting +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/Vesting.sol) + +**Inherits:** +[TeamVesting](/contracts/governance/Vesting/TeamVesting.sol/contract.TeamVesting.md) + +Team tokens and investor tokens are vested. Therefore, a smart +contract needs to be developed to enforce the vesting schedule. + + +## Functions +### constructor + +Setup the vesting schedule. + + +```solidity +constructor( + address _logic, + address _SOV, + address _stakingAddress, + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + address _feeSharingCollectorProxy +) public TeamVesting(_logic, _SOV, _stakingAddress, _tokenOwner, _cliff, _duration, _feeSharingCollectorProxy); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_logic`|`address`|The address of logic contract.| +|`_SOV`|`address`|The SOV token address.| +|`_stakingAddress`|`address`|| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| +|`_feeSharingCollectorProxy`|`address`|| + + +### governanceWithdrawTokens + +*We need to add this implementation to prevent proxy call VestingLogic.governanceWithdrawTokens* + + +```solidity +function governanceWithdrawTokens(address receiver) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The receiver of the token withdrawal.| + + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingCreator.sol/contract.VestingCreator.md b/foundry/docs/src/contracts/governance/Vesting/VestingCreator.sol/contract.VestingCreator.md new file mode 100644 index 000000000..5a90f3193 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingCreator.sol/contract.VestingCreator.md @@ -0,0 +1,272 @@ +# VestingCreator +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingCreator.sol) + +**Inherits:** +[AdminRole](/contracts/utils/AdminRole.sol/contract.AdminRole.md) + + +## State Variables +### vestingCreated +Boolean to check both vesting creation and staking is completed for a record + + +```solidity +bool vestingCreated; +``` + + +### TWO_WEEKS +2 weeks in seconds. + + +```solidity +uint256 public constant TWO_WEEKS = 2 weeks; +``` + + +### SOV +the SOV token contract + + +```solidity +IERC20 public SOV; +``` + + +### vestingRegistryLogic +the vesting registry contract + + +```solidity +VestingRegistryLogic public vestingRegistryLogic; +``` + + +### vestingDataList +list of vesting to be processed + + +```solidity +VestingData[] public vestingDataList; +``` + + +## Functions +### constructor + + +```solidity +constructor(address _SOV, address _vestingRegistryProxy) public; +``` + +### transferSOV + +transfers SOV tokens to given address + + +```solidity +function transferSOV(address _receiver, uint256 _amount) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|the address of the SOV receiver| +|`_amount`|`uint256`|the amount to be transferred| + + +### addVestings + +adds vestings to be processed to the list + + +```solidity +function addVestings( + address[] calldata _tokenOwners, + uint256[] calldata _amounts, + uint256[] calldata _cliffs, + uint256[] calldata _durations, + bool[] calldata _governanceControls, + uint256[] calldata _vestingCreationTypes +) external onlyAuthorized; +``` + +### processNextVesting + +Creates vesting contract and stakes tokens + +*Vesting and Staking are merged for calls that fits the gas limit* + + +```solidity +function processNextVesting() external; +``` + +### processVestingCreation + +Creates vesting contract without staking any tokens + +*Separating the Vesting and Staking to tackle Block Gas Limit* + + +```solidity +function processVestingCreation() public; +``` + +### processStaking + +Staking vested tokens + +*it can be the case when vesting creation and tokens staking can't be done in one transaction because of block gas limit* + + +```solidity +function processStaking() public; +``` + +### removeNextVesting + +removes next vesting data from the list + +*we process inverted list* + +*we should be able to remove incorrect vesting data that can't be processed* + + +```solidity +function removeNextVesting() external onlyAuthorized; +``` + +### clearVestingDataList + +removes all data about unprocessed vestings to be processed + + +```solidity +function clearVestingDataList() public onlyAuthorized; +``` + +### getVestingAddress + +returns address after vesting creation + + +```solidity +function getVestingAddress() external view returns (address); +``` + +### getVestingPeriod + +returns period i.e. ((duration - cliff) / 4 WEEKS) + +*will be used for deciding if vesting and staking needs to be processed +in a single transaction or separate transactions* + + +```solidity +function getVestingPeriod() external view returns (uint256); +``` + +### getUnprocessedCount + +returns count of vestings to be processed + + +```solidity +function getUnprocessedCount() external view returns (uint256); +``` + +### getUnprocessedAmount + +returns total amount of vestings to be processed + + +```solidity +function getUnprocessedAmount() public view returns (uint256); +``` + +### isEnoughBalance + +checks if contract balance is enough to process all vestings + + +```solidity +function isEnoughBalance() public view returns (bool); +``` + +### getMissingBalance + +returns missed balance to process all vestings + + +```solidity +function getMissingBalance() external view returns (uint256); +``` + +### _createAndGetVesting + +creates TeamVesting or Vesting contract + +*new contract won't be created if account already has contract of the same type* + + +```solidity +function _createAndGetVesting(VestingData memory vestingData) internal returns (address vesting); +``` + +### _getVesting + +returns an address of TeamVesting or Vesting contract (depends on a governance control) + + +```solidity +function _getVesting( + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + bool _governanceControl, + uint256 _vestingCreationType +) internal view returns (address vestingAddress); +``` + +## Events +### SOVTransferred + +```solidity +event SOVTransferred(address indexed receiver, uint256 amount); +``` + +### TokensStaked + +```solidity +event TokensStaked(address indexed vesting, address indexed tokenOwner, uint256 amount); +``` + +### VestingDataRemoved + +```solidity +event VestingDataRemoved(address indexed caller, address indexed tokenOwner); +``` + +### DataCleared + +```solidity +event DataCleared(address indexed caller); +``` + +## Structs +### VestingData +Holds Vesting Data + + +```solidity +struct VestingData { + uint256 amount; + uint256 cliff; + uint256 duration; + bool governanceControl; + address tokenOwner; + uint256 vestingCreationType; +} +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingFactory.sol/contract.VestingFactory.md b/foundry/docs/src/contracts/governance/Vesting/VestingFactory.sol/contract.VestingFactory.md new file mode 100644 index 000000000..c8db91ae5 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingFactory.sol/contract.VestingFactory.md @@ -0,0 +1,96 @@ +# VestingFactory +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingFactory.sol) + +**Inherits:** +[IVestingFactory](/contracts/governance/Vesting/IVestingFactory.sol/interface.IVestingFactory.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +Factory pattern allows to create multiple instances +of the same contract and keep track of them easier. + + +## State Variables +### vestingLogic + +```solidity +address public vestingLogic; +``` + + +## Functions +### constructor + + +```solidity +constructor(address _vestingLogic) public; +``` + +### deployVesting + +Deploys Vesting contract. + + +```solidity +function deployVesting( + address _SOV, + address _staking, + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + address _feeSharing, + address _vestingOwner +) external onlyOwner returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`address`|the address of SOV token.| +|`_staking`|`address`|The address of staking contract.| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| +|`_feeSharing`|`address`|The address of fee sharing contract.| +|`_vestingOwner`|`address`|The address of an owner of vesting contract.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The vesting contract address.| + + +### deployTeamVesting + +Deploys Team Vesting contract. + + +```solidity +function deployTeamVesting( + address _SOV, + address _staking, + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + address _feeSharing, + address _vestingOwner +) external onlyOwner returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`address`|The address of SOV token.| +|`_staking`|`address`|The address of staking contract.| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| +|`_feeSharing`|`address`|The address of fee sharing contract.| +|`_vestingOwner`|`address`|The address of an owner of vesting contract.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The vesting contract address.| + + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingLogic.sol/contract.VestingLogic.md b/foundry/docs/src/contracts/governance/Vesting/VestingLogic.sol/contract.VestingLogic.md new file mode 100644 index 000000000..5062f036e --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingLogic.sol/contract.VestingLogic.md @@ -0,0 +1,276 @@ +# VestingLogic +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingLogic.sol) + +**Inherits:** +[IVesting](/contracts/governance/Vesting/IVesting.sol/interface.IVesting.md), [VestingStorage](/contracts/governance/Vesting/VestingStorage.sol/contract.VestingStorage.md), [ApprovalReceiver](/contracts/governance/ApprovalReceiver.sol/contract.ApprovalReceiver.md) + +Staking, delegating and withdrawal functionality. + +*Deployed by a VestingFactory contract.* + + +## Functions +### onlyOwners + +*Throws if called by any account other than the token owner or the contract owner.* + + +```solidity +modifier onlyOwners(); +``` + +### onlyTokenOwner + +*Throws if called by any account other than the token owner.* + + +```solidity +modifier onlyTokenOwner(); +``` + +### stakeTokens + +Stakes tokens according to the vesting schedule. + + +```solidity +function stakeTokens(uint256 _amount) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|The amount of tokens to stake.| + + +### stakeTokensWithApproval + +Stakes tokens according to the vesting schedule. + +*This function will be invoked from receiveApproval.* + +*SOV.approveAndCall -> this.receiveApproval -> this.stakeTokensWithApproval* + + +```solidity +function stakeTokensWithApproval(address _sender, uint256 _amount) public onlyThisContract; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|The sender of SOV.approveAndCall| +|`_amount`|`uint256`|The amount of tokens to stake.| + + +### _stakeTokens + +Stakes tokens according to the vesting schedule. Low level function. + +*Once here the allowance of tokens is taken for granted.* + + +```solidity +function _stakeTokens(address _sender, uint256 _amount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|The sender of tokens to stake.| +|`_amount`|`uint256`|The amount of tokens to stake.| + + +### delegate + +Delegate votes from `msg.sender` which are locked until lockDate +to `delegatee`. + +*Maybe better to allow staking unil the cliff was reached.* + +*Transfer the tokens to this contract.* + +*Allow the staking contract to access them.* + + +```solidity +function delegate(address _delegatee) public onlyTokenOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_delegatee`|`address`|The address to delegate votes to.| + + +### withdrawTokens + +Withdraws unlocked tokens from the staking contract and +forwards them to an address specified by the token owner. + +*Withdraw for each unlocked position.* + +*Don't change FOUR_WEEKS to TWO_WEEKS, a lot of vestings already deployed with FOUR_WEEKS +workaround found, but it doesn't work with TWO_WEEKS* + + +```solidity +function withdrawTokens(address receiver) public onlyOwners; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The receiving address.| + + +### withdrawTokensStartingFrom + +Withdraws unlocked tokens partially (based on the max withdraw iteration that has been set) from the staking contract and +forwards them to an address specified by the token owner. + + +```solidity +function withdrawTokensStartingFrom(address receiver, uint256 startFrom, uint256 maxWithdrawIterations) + public + onlyOwners; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The receiving address.| +|`startFrom`|`uint256`|The start value for the iterations.| +|`maxWithdrawIterations`|`uint256`|max withdrawal iteration to work around block gas limit issue.| + + +### _withdrawTokens + +Withdraws tokens from the staking contract and forwards them +to an address specified by the token owner. Low level function. + +*Once here the caller permission is taken for granted.* + + +```solidity +function _withdrawTokens(address receiver, uint256 startFrom, uint256 endAt) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The receiving address.| +|`startFrom`|`uint256`|start withdrawal from date.| +|`endAt`|`uint256`|end time for regular withdrawal or just unlocked tokens (false).| + + +### collectDividends + +Collect dividends from fee sharing proxy. + +*Usually we just need to iterate over the possible dates until now.* + +*Withdraw for each unlocked position.* + +*Don't change FOUR_WEEKS to TWO_WEEKS, a lot of vestings already deployed with FOUR_WEEKS +workaround found, but it doesn't work with TWO_WEEKS* + +*Read amount to withdraw.* + +*Withdraw if > 0* + + +```solidity +function collectDividends(address _loanPoolToken, uint32 _maxCheckpoints, address _receiver) public onlyOwners; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_loanPoolToken`|`address`|The loan pool token address.| +|`_maxCheckpoints`|`uint32`|Maximum number of checkpoints to be processed.| +|`_receiver`|`address`|The receiver of tokens or msg.sender| + + +### migrateToNewStakingContract + +Allows the owners to migrate the positions +to a new staking contract. + +*Invokes the fee sharing proxy.* + + +```solidity +function migrateToNewStakingContract() public onlyOwners; +``` + +### _getToken + +Overrides default ApprovalReceiver._getToken function to +register SOV token on this contract. + + +```solidity +function _getToken() internal view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The address of SOV token.| + + +### _getSelectors + +Overrides default ApprovalReceiver._getSelectors function to +register stakeTokensWithApproval selector on this contract. + + +```solidity +function _getSelectors() internal pure returns (bytes4[] memory); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes4[]`|The array of registered selectors on this contract.| + + +### _timestampToLockDate + + +```solidity +function _timestampToLockDate(uint256 timestamp) internal view returns (uint256 lockDate); +``` + +## Events +### TokensStaked + +```solidity +event TokensStaked(address indexed caller, uint256 amount); +``` + +### VotesDelegated + +```solidity +event VotesDelegated(address indexed caller, address delegatee); +``` + +### TokensWithdrawn + +```solidity +event TokensWithdrawn(address indexed caller, address receiver, uint256 startFrom, uint256 end); +``` + +### DividendsCollected + +```solidity +event DividendsCollected(address indexed caller, address loanPoolToken, address receiver, uint32 maxCheckpoints); +``` + +### MigratedToNewStakingContract + +```solidity +event MigratedToNewStakingContract(address indexed caller, address newStakingContract); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingRegistry.sol/contract.VestingRegistry.md b/foundry/docs/src/contracts/governance/Vesting/VestingRegistry.sol/contract.VestingRegistry.md new file mode 100644 index 000000000..f58f6f06d --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingRegistry.sol/contract.VestingRegistry.md @@ -0,0 +1,663 @@ +# VestingRegistry +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingRegistry.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +On January 25, 2020, Sovryn launched the Genesis Reservation system. +Sovryn community members who controlled a special NFT were granted access to +stake BTC or rBTC for cSOV tokens at a rate of 2500 satoshis per cSOV. Per +SIP-0003, up to 2,000,000 cSOV were made available in the Genesis event, +which will be redeemable on a 1:1 basis for cSOV, subject to approval by +existing SOV holders. +On 15 Feb 2021 Sovryn is taking another step in its journey to decentralized +financial sovereignty with the vote on SIP 0005. This proposal will enable +participants of the Genesis Reservation system to redeem their reserved cSOV +tokens for SOV. They will also have the choice to redeem cSOV for rBTC if +they decide to exit the system. +This contract deals with the vesting and redemption of cSOV tokens. + + +## State Variables +### FOUR_WEEKS +Constant used for computing the vesting dates. + + +```solidity +uint256 public constant FOUR_WEEKS = 4 weeks; +``` + + +### CSOV_VESTING_CLIFF + +```solidity +uint256 public constant CSOV_VESTING_CLIFF = FOUR_WEEKS; +``` + + +### CSOV_VESTING_DURATION + +```solidity +uint256 public constant CSOV_VESTING_DURATION = 10 * FOUR_WEEKS; +``` + + +### vestingFactory + +```solidity +IVestingFactory public vestingFactory; +``` + + +### SOV +The SOV token contract. + + +```solidity +address public SOV; +``` + + +### CSOVtokens +The cSOV token contracts. + + +```solidity +address[] public CSOVtokens; +``` + + +### priceSats + +```solidity +uint256 public priceSats; +``` + + +### staking +The staking contract address. + + +```solidity +address public staking; +``` + + +### feeSharingCollector +Fee sharing proxy. + + +```solidity +address public feeSharingCollector; +``` + + +### vestingOwner +The vesting owner (e.g. governance timelock address). + + +```solidity +address public vestingOwner; +``` + + +### vestingContracts +*TODO: Add to the documentation: address can have only one vesting of each type.* + +*user => vesting type => vesting contract.* + + +```solidity +mapping(address => mapping(uint256 => address)) public vestingContracts; +``` + + +### processedList +*Struct can be created to save storage slots, but it doesn't make +sense. We don't have a lot of blacklisted accounts or account with +locked amount.* + +*user => flag whether user has already exchange cSOV or got a reimbursement.* + + +```solidity +mapping(address => bool) public processedList; +``` + + +### blacklist +*user => flag whether user shouldn't be able to exchange or reimburse.* + + +```solidity +mapping(address => bool) public blacklist; +``` + + +### lockedAmount +*user => amount of tokens should not be processed.* + + +```solidity +mapping(address => uint256) public lockedAmount; +``` + + +### admins +*user => flag whether user has admin role.* + + +```solidity +mapping(address => bool) public admins; +``` + + +## Functions +### constructor + +Contract deployment settings. + +*On Sovryn the vesting owner is Exchequer Multisig. +According to SIP-0007 The Exchequer Multisig is designated to hold +certain funds in the form of rBTC and SOV, in order to allow for +flexible deployment of such funds on: ++ facilitating rBTC redemptions for Genesis pre-sale participants. ++ deploying of SOV for the purposes of exchange listings, market +making, and partnerships with third parties.* + + +```solidity +constructor( + address _vestingFactory, + address _SOV, + address[] memory _CSOVtokens, + uint256 _priceSats, + address _staking, + address _feeSharingCollector, + address _vestingOwner +) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|The address of vesting factory contract.| +|`_SOV`|`address`|The SOV token address.| +|`_CSOVtokens`|`address[]`|The array of cSOV tokens.| +|`_priceSats`|`uint256`|The price of cSOV tokens in satoshis.| +|`_staking`|`address`|The address of staking contract.| +|`_feeSharingCollector`|`address`|The address of fee sharing collector proxy contract.| +|`_vestingOwner`|`address`|The address of an owner of vesting contract.| + + +### onlyAuthorized + +*Throws if called by any account other than the owner or admin. +TODO: This ACL logic should be available on OpenZeppeling Ownable.sol +or on our own overriding sovrynOwnable. This same logic is repeated +on OriginInvestorsClaim.sol, TokenSender.sol and VestingRegistry2.sol* + + +```solidity +modifier onlyAuthorized(); +``` + +### addAdmin + +Add account to ACL. + + +```solidity +function addAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to grant permissions.| + + +### removeAdmin + +Remove account from ACL. + + +```solidity +function removeAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to revoke permissions.| + + +### isNotProcessed + + +```solidity +modifier isNotProcessed(); +``` + +### isNotBlacklisted + + +```solidity +modifier isNotBlacklisted(); +``` + +### reImburse + +cSOV payout to sender with rBTC currency. +1.- Check holder cSOV balance by adding up every cSOV token balance. +2.- ReImburse rBTC if funds available. +3.- And store holder address in processedList. + + +```solidity +function reImburse() public isNotProcessed isNotBlacklisted; +``` + +### budget + +Get contract balance. + +*Found and fixed the SIP-0007 bug on VestingRegistry::reImburse formula. +More details at Documenting Code issues at point 11 in +https://docs.google.com/document/d/10idTD1K6JvoBmtPKGuJ2Ub_mMh6qTLLlTP693GQKMyU/ +Previous buggy code: uint256 reImburseAmount = (CSOVAmountWei.mul(priceSats)).div(10**10);* + + +```solidity +function budget() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The token balance of the contract.| + + +### deposit + +Deposit function to receiving value (rBTC). + + +```solidity +function deposit() public payable; +``` + +### withdrawAll + +Send all contract balance to an account. + + +```solidity +function withdrawAll(address payable to) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`to`|`address payable`|The account address to send the balance to.| + + +### setVestingFactory + +Sets vesting factory address. High level endpoint. + +*Splitting code on two functions: high level and low level +is a pattern that makes easy to extend functionality in a readable way, +without accidentally breaking the actual action being performed. +For example, checks should be done on high level endpoint, while core +functionality should be coded on the low level function.* + + +```solidity +function setVestingFactory(address _vestingFactory) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|The address of vesting factory contract.| + + +### _setVestingFactory + +Sets vesting factory address. Low level core function. + + +```solidity +function _setVestingFactory(address _vestingFactory) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|The address of vesting factory contract.| + + +### setCSOVtokens + +Sets cSOV tokens array. High level endpoint. + + +```solidity +function setCSOVtokens(address[] memory _CSOVtokens) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_CSOVtokens`|`address[]`|The array of cSOV tokens.| + + +### _setCSOVtokens + +Sets cSOV tokens array by looping through input. Low level function. + + +```solidity +function _setCSOVtokens(address[] memory _CSOVtokens) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_CSOVtokens`|`address[]`|The array of cSOV tokens.| + + +### setBlacklistFlag + +Set blacklist flag (true/false). + + +```solidity +function setBlacklistFlag(address _account, bool _blacklisted) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_account`|`address`|The address to be blacklisted.| +|`_blacklisted`|`bool`|The flag to add/remove to/from a blacklist.| + + +### setLockedAmount + +Set amount to be subtracted from user token balance. + + +```solidity +function setLockedAmount(address _account, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_account`|`address`|The address with locked amount.| +|`_amount`|`uint256`|The amount to be locked.| + + +### transferSOV + +Transfer SOV tokens to given address. + +*This is a wrapper for ERC-20 transfer function w/ +additional checks and triggering an event.* + + +```solidity +function transferSOV(address _receiver, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|The address of the SOV receiver.| +|`_amount`|`uint256`|The amount to be transferred.| + + +### exchangeAllCSOV + +Exchange cSOV to SOV with 1:1 rate + + +```solidity +function exchangeAllCSOV() public isNotProcessed isNotBlacklisted; +``` + +### _createVestingForCSOV + +cSOV tokens are moved and staked on Vesting contract. + + +```solidity +function _createVestingForCSOV(uint256 _amount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|The amount of tokens to be vested.| + + +### _validateCSOV + +Check a token address is among the cSOV token addresses. + + +```solidity +function _validateCSOV(address _CSOV) internal view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_CSOV`|`address`|The cSOV token address.| + + +### createVesting + +Create Vesting contract. + + +```solidity +function createVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_amount`|`uint256`|The amount to be staked.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + + +### createTeamVesting + +Create Team Vesting contract. + + +```solidity +function createTeamVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) + public + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_amount`|`uint256`|The amount to be staked.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + + +### stakeTokens + +Stake tokens according to the vesting schedule. + + +```solidity +function stakeTokens(address _vesting, uint256 _amount) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vesting`|`address`|The address of Vesting contract.| +|`_amount`|`uint256`|The amount of tokens to stake.| + + +### getVesting + +Query the vesting contract for an account. + + +```solidity +function getVesting(address _tokenOwner) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The vesting contract address for the given token owner.| + + +### getTeamVesting + +Query the team vesting contract for an account. + + +```solidity +function getTeamVesting(address _tokenOwner) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The team vesting contract address for the given token owner.| + + +### _getOrCreateVesting + +If not exists, deploy a vesting contract through factory. + + +```solidity +function _getOrCreateVesting(address _tokenOwner, uint256 _cliff, uint256 _duration) internal returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The vesting contract address for the given token owner whether it existed previously or not.| + + +### _getOrCreateTeamVesting + +If not exists, deploy a team vesting contract through factory. + +*TODO: Owner of OwnerVesting contracts - the same address as tokenOwner.* + + +```solidity +function _getOrCreateTeamVesting(address _tokenOwner, uint256 _cliff, uint256 _duration) internal returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The team vesting contract address for the given token owner whether it existed previously or not.| + + +## Events +### CSOVReImburse + +```solidity +event CSOVReImburse(address from, uint256 CSOVamount, uint256 reImburseAmount); +``` + +### CSOVTokensExchanged + +```solidity +event CSOVTokensExchanged(address indexed caller, uint256 amount); +``` + +### SOVTransferred + +```solidity +event SOVTransferred(address indexed receiver, uint256 amount); +``` + +### VestingCreated + +```solidity +event VestingCreated(address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount); +``` + +### TeamVestingCreated + +```solidity +event TeamVestingCreated(address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount); +``` + +### TokensStaked + +```solidity +event TokensStaked(address indexed vesting, uint256 amount); +``` + +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + +## Enums +### VestingType + +```solidity +enum VestingType { + TeamVesting, + Vesting +} +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingRegistry2.sol/contract.VestingRegistry2.md b/foundry/docs/src/contracts/governance/Vesting/VestingRegistry2.sol/contract.VestingRegistry2.md new file mode 100644 index 000000000..f86ff722d --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingRegistry2.sol/contract.VestingRegistry2.md @@ -0,0 +1,615 @@ +# VestingRegistry2 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingRegistry2.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +One time contract needed to distribute tokens to origin sales investors. + + +## State Variables +### FOUR_WEEKS +Constant used for computing the vesting dates. + + +```solidity +uint256 public constant FOUR_WEEKS = 4 weeks; +``` + + +### CSOV_VESTING_CLIFF + +```solidity +uint256 public constant CSOV_VESTING_CLIFF = FOUR_WEEKS; +``` + + +### CSOV_VESTING_DURATION + +```solidity +uint256 public constant CSOV_VESTING_DURATION = 10 * FOUR_WEEKS; +``` + + +### vestingFactory + +```solidity +IVestingFactory public vestingFactory; +``` + + +### SOV +The SOV token contract. + + +```solidity +address public SOV; +``` + + +### CSOVtokens +The CSOV token contracts. + + +```solidity +address[] public CSOVtokens; +``` + + +### priceSats + +```solidity +uint256 public priceSats; +``` + + +### staking +The staking contract address. + + +```solidity +address public staking; +``` + + +### feeSharingCollector +Fee sharing proxy. + + +```solidity +address public feeSharingCollector; +``` + + +### vestingOwner +The vesting owner (e.g. governance timelock address). + + +```solidity +address public vestingOwner; +``` + + +### vestingContracts +*TODO: Add to the documentation: address can have only one vesting of each type.* + +*user => vesting type => vesting contract* + + +```solidity +mapping(address => mapping(uint256 => address)) public vestingContracts; +``` + + +### processedList +*Struct can be created to save storage slots, but it doesn't make +sense. We don't have a lot of blacklisted accounts or account with +locked amount.* + +*user => flag whether user has already exchange cSOV or got a reimbursement.* + + +```solidity +mapping(address => bool) public processedList; +``` + + +### blacklist +*user => flag whether user shouldn't be able to exchange or reimburse.* + + +```solidity +mapping(address => bool) public blacklist; +``` + + +### lockedAmount +*user => amount of tokens should not be processed.* + + +```solidity +mapping(address => uint256) public lockedAmount; +``` + + +### admins +*user => flag whether user has admin role.* + + +```solidity +mapping(address => bool) public admins; +``` + + +## Functions +### constructor + +Contract deployment settings. + +*On Sovryn the vesting owner is Exchequer Multisig. +According to SIP-0007 The Exchequer Multisig is designated to hold +certain funds in the form of rBTC and SOV, in order to allow for +flexible deployment of such funds on: ++ facilitating rBTC redemptions for Genesis pre-sale participants. ++ deploying of SOV for the purposes of exchange listings, market +making, and partnerships with third parties.* + + +```solidity +constructor( + address _vestingFactory, + address _SOV, + address[] memory _CSOVtokens, + uint256 _priceSats, + address _staking, + address _feeSharingCollector, + address _vestingOwner +) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|The address of vesting factory contract.| +|`_SOV`|`address`|The SOV token address.| +|`_CSOVtokens`|`address[]`|The array of cSOV tokens.| +|`_priceSats`|`uint256`|The price of cSOV tokens in satoshis.| +|`_staking`|`address`|The address of staking contract.| +|`_feeSharingCollector`|`address`|The address of fee sharing proxy contract.| +|`_vestingOwner`|`address`|The address of an owner of vesting contract.| + + +### onlyAuthorized + +*Throws if called by any account other than the owner or admin.* + + +```solidity +modifier onlyAuthorized(); +``` + +### addAdmin + +Add account to ACL. + + +```solidity +function addAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to grant permissions.| + + +### removeAdmin + +Remove account from ACL. + + +```solidity +function removeAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to revoke permissions.| + + +### isNotProcessed + + +```solidity +modifier isNotProcessed(); +``` + +### isNotBlacklisted + + +```solidity +modifier isNotBlacklisted(); +``` + +### budget + +Get contract balance. + + +```solidity +function budget() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The token balance of the contract.| + + +### deposit + +Deposit function to receiving value (rBTC). + + +```solidity +function deposit() public payable; +``` + +### withdrawAll + +Send all contract balance to an account. + + +```solidity +function withdrawAll(address payable to) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`to`|`address payable`|The account address to send the balance to.| + + +### setVestingFactory + +Sets vesting factory address. High level endpoint. + +*Splitting code on two functions: high level and low level +is a pattern that makes easy to extend functionality in a readable way, +without accidentally breaking the actual action being performed. +For example, checks should be done on high level endpoint, while core +functionality should be coded on the low level function.* + + +```solidity +function setVestingFactory(address _vestingFactory) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|The address of vesting factory contract.| + + +### _setVestingFactory + +Sets vesting factory address. Low level core function. + + +```solidity +function _setVestingFactory(address _vestingFactory) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|The address of vesting factory contract.| + + +### setCSOVtokens + +Sets cSOV tokens array. High level endpoint. + + +```solidity +function setCSOVtokens(address[] memory _CSOVtokens) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_CSOVtokens`|`address[]`|The array of cSOV tokens.| + + +### _setCSOVtokens + +Sets cSOV tokens array by looping through input. Low level function. + + +```solidity +function _setCSOVtokens(address[] memory _CSOVtokens) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_CSOVtokens`|`address[]`|The array of cSOV tokens.| + + +### setBlacklistFlag + +Set blacklist flag (true/false). + + +```solidity +function setBlacklistFlag(address _account, bool _blacklisted) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_account`|`address`|The address to be blacklisted.| +|`_blacklisted`|`bool`|The flag to add/remove to/from a blacklist.| + + +### setLockedAmount + +Set amount to be subtracted from user token balance. + + +```solidity +function setLockedAmount(address _account, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_account`|`address`|The address with locked amount.| +|`_amount`|`uint256`|The amount to be locked.| + + +### transferSOV + +Transfer SOV tokens to given address. + +*This is a wrapper for ERC-20 transfer function w/ +additional checks and triggering an event.* + + +```solidity +function transferSOV(address _receiver, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|The address of the SOV receiver.| +|`_amount`|`uint256`|The amount to be transferred.| + + +### _createVestingForCSOV + +cSOV tokens are moved and staked on Vesting contract. + + +```solidity +function _createVestingForCSOV(uint256 _amount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|The amount of tokens to be vested.| + + +### _validateCSOV + +Check a token address is among the cSOV token addresses. + + +```solidity +function _validateCSOV(address _CSOV) internal view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_CSOV`|`address`|The cSOV token address.| + + +### createVesting + +Create Vesting contract. + + +```solidity +function createVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_amount`|`uint256`|The amount to be staked.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + + +### createTeamVesting + +Create Team Vesting contract. + + +```solidity +function createTeamVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) + public + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_amount`|`uint256`|The amount to be staked.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + + +### stakeTokens + +Stake tokens according to the vesting schedule + + +```solidity +function stakeTokens(address _vesting, uint256 _amount) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vesting`|`address`|the address of Vesting contract| +|`_amount`|`uint256`|the amount of tokens to stake| + + +### getVesting + +Query the vesting contract for an account. + + +```solidity +function getVesting(address _tokenOwner) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The vesting contract address for the given token owner.| + + +### getTeamVesting + +Query the team vesting contract for an account. + + +```solidity +function getTeamVesting(address _tokenOwner) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The team vesting contract address for the given token owner.| + + +### _getOrCreateVesting + +If not exists, deploy a vesting contract through factory. + + +```solidity +function _getOrCreateVesting(address _tokenOwner, uint256 _cliff, uint256 _duration) internal returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The vesting contract address for the given token owner whether it existed previously or not.| + + +### _getOrCreateTeamVesting + +If not exists, deploy a team vesting contract through factory. + + +```solidity +function _getOrCreateTeamVesting(address _tokenOwner, uint256 _cliff, uint256 _duration) internal returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_cliff`|`uint256`|The time interval to the first withdraw in seconds.| +|`_duration`|`uint256`|The total duration in seconds.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The team vesting contract address for the given token owner whether it existed previously or not.| + + +## Events +### CSOVTokensExchanged + +```solidity +event CSOVTokensExchanged(address indexed caller, uint256 amount); +``` + +### SOVTransferred + +```solidity +event SOVTransferred(address indexed receiver, uint256 amount); +``` + +### VestingCreated + +```solidity +event VestingCreated(address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount); +``` + +### TeamVestingCreated + +```solidity +event TeamVestingCreated(address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount); +``` + +### TokensStaked + +```solidity +event TokensStaked(address indexed vesting, uint256 amount); +``` + +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + +## Enums +### VestingType + +```solidity +enum VestingType { + TeamVesting, + Vesting +} +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingRegistry3.sol/contract.VestingRegistry3.md b/foundry/docs/src/contracts/governance/Vesting/VestingRegistry3.sol/contract.VestingRegistry3.md new file mode 100644 index 000000000..dfd496619 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingRegistry3.sol/contract.VestingRegistry3.md @@ -0,0 +1,281 @@ +# VestingRegistry3 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingRegistry3.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + + +## State Variables +### vestingFactory + +```solidity +IVestingFactory public vestingFactory; +``` + + +### SOV +the SOV token contract + + +```solidity +address public SOV; +``` + + +### staking +the staking contract address + + +```solidity +address public staking; +``` + + +### feeSharingCollector + +```solidity +address public feeSharingCollector; +``` + + +### vestingOwner + +```solidity +address public vestingOwner; +``` + + +### vestingContracts + +```solidity +mapping(address => mapping(uint256 => address)) public vestingContracts; +``` + + +### admins + +```solidity +mapping(address => bool) public admins; +``` + + +## Functions +### constructor + + +```solidity +constructor( + address _vestingFactory, + address _SOV, + address _staking, + address _feeSharingCollector, + address _vestingOwner +) public; +``` + +### onlyAuthorized + +*Throws if called by any account other than the owner or admin.* + + +```solidity +modifier onlyAuthorized(); +``` + +### addAdmin + + +```solidity +function addAdmin(address _admin) public onlyOwner; +``` + +### removeAdmin + + +```solidity +function removeAdmin(address _admin) public onlyOwner; +``` + +### setVestingFactory + +sets vesting factory address + + +```solidity +function setVestingFactory(address _vestingFactory) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|the address of vesting factory contract| + + +### _setVestingFactory + + +```solidity +function _setVestingFactory(address _vestingFactory) internal; +``` + +### transferSOV + +transfers SOV tokens to given address + + +```solidity +function transferSOV(address _receiver, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|the address of the SOV receiver| +|`_amount`|`uint256`|the amount to be transferred| + + +### createVesting + +creates Vesting contract + + +```solidity +function createVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| +|`_amount`|`uint256`|the amount to be staked| +|`_cliff`|`uint256`|the cliff in seconds| +|`_duration`|`uint256`|the total duration in seconds| + + +### createTeamVesting + +creates Team Vesting contract + + +```solidity +function createTeamVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) + public + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| +|`_amount`|`uint256`|the amount to be staked| +|`_cliff`|`uint256`|the cliff in seconds| +|`_duration`|`uint256`|the total duration in seconds| + + +### stakeTokens + +stakes tokens according to the vesting schedule + + +```solidity +function stakeTokens(address _vesting, uint256 _amount) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vesting`|`address`|the address of Vesting contract| +|`_amount`|`uint256`|the amount of tokens to stake| + + +### getVesting + +returns vesting contract address for the given token owner + + +```solidity +function getVesting(address _tokenOwner) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| + + +### getTeamVesting + +returns team vesting contract address for the given token owner + + +```solidity +function getTeamVesting(address _tokenOwner) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| + + +### _getOrCreateVesting + + +```solidity +function _getOrCreateVesting(address _tokenOwner, uint256 _cliff, uint256 _duration) internal returns (address); +``` + +### _getOrCreateTeamVesting + + +```solidity +function _getOrCreateTeamVesting(address _tokenOwner, uint256 _cliff, uint256 _duration) internal returns (address); +``` + +## Events +### SOVTransferred + +```solidity +event SOVTransferred(address indexed receiver, uint256 amount); +``` + +### VestingCreated + +```solidity +event VestingCreated(address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount); +``` + +### TeamVestingCreated + +```solidity +event TeamVestingCreated(address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount); +``` + +### TokensStaked + +```solidity +event TokensStaked(address indexed vesting, uint256 amount); +``` + +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + +## Enums +### VestingType + +```solidity +enum VestingType { + TeamVesting, + Vesting +} +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingRegistryLogic.sol/contract.VestingRegistryLogic.md b/foundry/docs/src/contracts/governance/Vesting/VestingRegistryLogic.sol/contract.VestingRegistryLogic.md new file mode 100644 index 000000000..a5355912f --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingRegistryLogic.sol/contract.VestingRegistryLogic.md @@ -0,0 +1,390 @@ +# VestingRegistryLogic +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingRegistryLogic.sol) + +**Inherits:** +[VestingRegistryStorage](/contracts/governance/Vesting/VestingRegistryStorage.sol/contract.VestingRegistryStorage.md) + + +## Functions +### initialize + +Replace constructor with initialize function for Upgradable Contracts +This function will be called only once by the owner + + +```solidity +function initialize( + address _vestingFactory, + address _SOV, + address _staking, + address _feeSharingCollector, + address _vestingOwner, + address _lockedSOV, + address[] calldata _vestingRegistries +) external onlyOwner initializer; +``` + +### setVestingFactory + +sets vesting factory address + + +```solidity +function setVestingFactory(address _vestingFactory) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|the address of vesting factory contract| + + +### _setVestingFactory + +Internal function that sets vesting factory address + + +```solidity +function _setVestingFactory(address _vestingFactory) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingFactory`|`address`|the address of vesting factory contract| + + +### transferSOV + +transfers SOV tokens to given address + + +```solidity +function transferSOV(address _receiver, uint256 _amount) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiver`|`address`|the address of the SOV receiver| +|`_amount`|`uint256`|the amount to be transferred| + + +### addDeployedVestings + +adds vestings that were deployed in previous vesting registries + +*migration of data from previous vesting registy contracts* + + +```solidity +function addDeployedVestings(address[] calldata _tokenOwners, uint256[] calldata _vestingCreationTypes) + external + onlyAuthorized; +``` + +### addFourYearVestings + +adds four year vestings to vesting registry logic + + +```solidity +function addFourYearVestings(address[] calldata _tokenOwners, address[] calldata _vestingAddresses) + external + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwners`|`address[]`|array of token owners| +|`_vestingAddresses`|`address[]`|array of vesting addresses| + + +### createVesting + +creates Vesting contract + +*Calls a public createVestingAddr function with vestingCreationType. This is to accomodate the existing logic for LockedSOV* + +*vestingCreationType 0 = LockedSOV* + + +```solidity +function createVesting(address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration) + external + onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| +|`_amount`|`uint256`|the amount to be staked| +|`_cliff`|`uint256`|the cliff in seconds| +|`_duration`|`uint256`|the total duration in seconds| + + +### createVestingAddr + +creates Vesting contract + + +```solidity +function createVestingAddr( + address _tokenOwner, + uint256 _amount, + uint256 _cliff, + uint256 _duration, + uint256 _vestingCreationType +) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| +|`_amount`|`uint256`|the amount to be staked| +|`_cliff`|`uint256`|the cliff in seconds| +|`_duration`|`uint256`|the total duration in seconds| +|`_vestingCreationType`|`uint256`|the type of vesting created(e.g. Origin, Bug Bounty etc.)| + + +### createTeamVesting + +creates Team Vesting contract + + +```solidity +function createTeamVesting( + address _tokenOwner, + uint256 _amount, + uint256 _cliff, + uint256 _duration, + uint256 _vestingCreationType +) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| +|`_amount`|`uint256`|the amount to be staked| +|`_cliff`|`uint256`|the cliff in seconds| +|`_duration`|`uint256`|the total duration in seconds| +|`_vestingCreationType`|`uint256`|the type of vesting created(e.g. Origin, Bug Bounty etc.)| + + +### stakeTokens + +stakes tokens according to the vesting schedule + + +```solidity +function stakeTokens(address _vesting, uint256 _amount) external onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vesting`|`address`|the address of Vesting contract| +|`_amount`|`uint256`|the amount of tokens to stake| + + +### getVesting + +returns vesting contract address for the given token owner + +*Calls a public getVestingAddr function with cliff and duration. This is to accomodate the existing logic for LockedSOV* + +*We need to use LockedSOV.changeRegistryCliffAndDuration function very judiciously* + +*vestingCreationType 0 - LockedSOV* + + +```solidity +function getVesting(address _tokenOwner) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| + + +### getVestingAddr + +public function that returns vesting contract address for the given token owner, cliff, duration + +*Important: Please use this instead of getVesting function* + + +```solidity +function getVestingAddr(address _tokenOwner, uint256 _cliff, uint256 _duration, uint256 _vestingCreationType) + public + view + returns (address); +``` + +### getTeamVesting + +returns team vesting contract address for the given token owner, cliff, duration + + +```solidity +function getTeamVesting(address _tokenOwner, uint256 _cliff, uint256 _duration, uint256 _vestingCreationType) + public + view + returns (address); +``` + +### isTeamVesting + +*check if the specific vesting address is team vesting or not* + +*read the vestingType from vestingCreationAndTypes storage* + + +```solidity +function isTeamVesting(address _vestingAddress) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingAddress`|`address`|address of vesting contract| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|true for teamVesting, false for normal vesting| + + +### registerVestingToVestingCreationAndTypes + +*setter function to register existing vesting contract to vestingCreationAndTypes storage* + +*need to set the function visilibty to public to support VestingCreationAndTypeDetails struct as parameter* + + +```solidity +function registerVestingToVestingCreationAndTypes( + address[] memory _vestingAddresses, + VestingCreationAndTypeDetails[] memory _vestingCreationAndTypes +) public onlyAuthorized; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingAddresses`|`address[]`|array of vesting address| +|`_vestingCreationAndTypes`|`VestingCreationAndTypeDetails[]`|array for VestingCreationAndTypeDetails struct| + + +### _getOrCreateVesting + +Internal function to deploy Vesting/Team Vesting contract + + +```solidity +function _getOrCreateVesting( + address _tokenOwner, + uint256 _cliff, + uint256 _duration, + uint256 _type, + uint256 _vestingCreationType +) internal returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|the owner of the tokens| +|`_cliff`|`uint256`|the cliff in seconds| +|`_duration`|`uint256`|the total duration in seconds| +|`_type`|`uint256`|the type of vesting| +|`_vestingCreationType`|`uint256`|the type of vesting created(e.g. Origin, Bug Bounty etc.)| + + +### _addDeployedVestings + +stores the addresses of Vesting contracts from all three previous versions of Vesting Registry + + +```solidity +function _addDeployedVestings(address _tokenOwner, uint256 _vestingCreationType) internal; +``` + +### getVestingsOf + +returns all vesting details for the given token owner + + +```solidity +function getVestingsOf(address _tokenOwner) external view returns (Vesting[] memory); +``` + +### getVestingDetails + +returns cliff and duration for Vesting & TeamVesting contracts + + +```solidity +function getVestingDetails(address _vestingAddress) external view returns (uint256 cliff, uint256 duration); +``` + +### isVestingAddress + +returns if the address is a vesting address + + +```solidity +function isVestingAddress(address _vestingAddress) external view returns (bool isVestingAddr); +``` + +## Events +### SOVTransferred + +```solidity +event SOVTransferred(address indexed receiver, uint256 amount); +``` + +### VestingCreated + +```solidity +event VestingCreated( + address indexed tokenOwner, + address vesting, + uint256 cliff, + uint256 duration, + uint256 amount, + uint256 vestingCreationType +); +``` + +### TeamVestingCreated + +```solidity +event TeamVestingCreated( + address indexed tokenOwner, + address vesting, + uint256 cliff, + uint256 duration, + uint256 amount, + uint256 vestingCreationType +); +``` + +### TokensStaked + +```solidity +event TokensStaked(address indexed vesting, uint256 amount); +``` + +### VestingCreationAndTypesSet + +```solidity +event VestingCreationAndTypesSet(address indexed vesting, VestingCreationAndTypeDetails vestingCreationAndType); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingRegistryProxy.sol/contract.VestingRegistryProxy.md b/foundry/docs/src/contracts/governance/Vesting/VestingRegistryProxy.sol/contract.VestingRegistryProxy.md new file mode 100644 index 000000000..ad481ecf3 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingRegistryProxy.sol/contract.VestingRegistryProxy.md @@ -0,0 +1,12 @@ +# VestingRegistryProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingRegistryProxy.sol) + +**Inherits:** +[VestingRegistryStorage](/contracts/governance/Vesting/VestingRegistryStorage.sol/contract.VestingRegistryStorage.md), [UpgradableProxy](/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + +*Vesting Registry contract should be upgradable, use UpgradableProxy. +VestingRegistryStorage is deployed with the upgradable functionality +by using this contract instead, that inherits from UpgradableProxy +the possibility of being enhanced and re-deployed.* + + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingRegistryStorage.sol/contract.VestingRegistryStorage.md b/foundry/docs/src/contracts/governance/Vesting/VestingRegistryStorage.sol/contract.VestingRegistryStorage.md new file mode 100644 index 000000000..12bd58707 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingRegistryStorage.sol/contract.VestingRegistryStorage.md @@ -0,0 +1,161 @@ +# VestingRegistryStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingRegistryStorage.sol) + +**Inherits:** +[Initializable](/contracts/openzeppelin/Initializable.sol/contract.Initializable.md), [AdminRole](/contracts/utils/AdminRole.sol/contract.AdminRole.md) + +This contract is just the storage required for vesting registry. +It is parent of VestingRegistryProxy and VestingRegistryLogic. + +*Use Ownable as a parent to align storage structure for Logic and Proxy contracts.* + + +## State Variables +### vestingFactory +the vesting factory contract + + +```solidity +IVestingFactory public vestingFactory; +``` + + +### lockedSOV +the Locked SOV contract + +*NOTES: No need to update lockedSOV in this contract, since it might break the vestingRegistry if the new lockedSOV does not have the same value of cliff & duration.* + + +```solidity +ILockedSOV public lockedSOV; +``` + + +### vestingRegistries +the list of vesting registries + + +```solidity +IVestingRegistry[] public vestingRegistries; +``` + + +### SOV +the SOV token contract + + +```solidity +address public SOV; +``` + + +### staking +the staking contract address + + +```solidity +address public staking; +``` + + +### feeSharingCollector +fee sharing proxy + + +```solidity +address public feeSharingCollector; +``` + + +### vestingOwner +the vesting owner (e.g. governance timelock address) + + +```solidity +address public vestingOwner; +``` + + +### vestings +A record of vesting details for a unique id + +*vestings[uid] returns vesting data* + + +```solidity +mapping(uint256 => Vesting) public vestings; +``` + + +### vestingsOf +A record of all unique ids for a particular token owner + +*vestingsOf[tokenOwner] returns array of unique ids* + + +```solidity +mapping(address => uint256[]) public vestingsOf; +``` + + +### isVesting +A record of all vesting addresses + +*isVesting[address] returns if the address is a vesting address* + + +```solidity +mapping(address => bool) public isVesting; +``` + + +### vestingCreationAndTypes +A record of all vesting addresses with the detail + +*vestingDetail[vestingAddress] returns Vesting struct data* + +*can be used to easily check the vesting type / creation type based on the vesting address itself* + + +```solidity +mapping(address => VestingCreationAndTypeDetails) public vestingCreationAndTypes; +``` + + +## Structs +### Vesting +Vesting details + + +```solidity +struct Vesting { + uint256 vestingType; + uint256 vestingCreationType; + address vestingAddress; +} +``` + +### VestingCreationAndTypeDetails +Store vesting creation type & vesting type information + +*it is packed into 1 single storage slot for cheaper gas usage* + + +```solidity +struct VestingCreationAndTypeDetails { + bool isSet; + uint32 vestingType; + uint128 vestingCreationType; +} +``` + +## Enums +### VestingType + +```solidity +enum VestingType { + TeamVesting, + Vesting +} +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/VestingStorage.sol/contract.VestingStorage.md b/foundry/docs/src/contracts/governance/Vesting/VestingStorage.sol/contract.VestingStorage.md new file mode 100644 index 000000000..259d48732 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/VestingStorage.sol/contract.VestingStorage.md @@ -0,0 +1,94 @@ +# VestingStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/VestingStorage.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +This contract is just the storage required for vesting. +It is parent of VestingLogic and TeamVesting. + +*Use Ownable as a parent to align storage structure for Logic and Proxy contracts.* + + +## State Variables +### SOV +The SOV token contract. + + +```solidity +IERC20 public SOV; +``` + + +### staking +The staking contract address. + + +```solidity +IStaking public staking; +``` + + +### tokenOwner +The owner of the vested tokens. + + +```solidity +address public tokenOwner; +``` + + +### feeSharingCollector +Fee sharing Proxy. + + +```solidity +IFeeSharingCollector public feeSharingCollector; +``` + + +### cliff +The cliff. After this time period the tokens begin to unlock. + + +```solidity +uint256 public cliff; +``` + + +### duration +The duration. After this period all tokens will have been unlocked. + + +```solidity +uint256 public duration; +``` + + +### startDate +The start date of the vesting. + + +```solidity +uint256 public startDate; +``` + + +### endDate +The end date of the vesting. + + +```solidity +uint256 public endDate; +``` + + +### FOUR_WEEKS +Constant used for computing the vesting dates. + + +```solidity +uint256 constant FOUR_WEEKS = 4 weeks; +``` + + diff --git a/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVesting.sol/contract.FourYearVesting.md b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVesting.sol/contract.FourYearVesting.md new file mode 100644 index 000000000..8d4196f38 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVesting.sol/contract.FourYearVesting.md @@ -0,0 +1,61 @@ +# FourYearVesting +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/fouryear/FourYearVesting.sol) + +**Inherits:** +[FourYearVestingStorage](/contracts/governance/Vesting/fouryear/FourYearVestingStorage.sol/contract.FourYearVestingStorage.md), [UpgradableProxy](/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md) + +A four year vesting contract. + +*Vesting contract is upgradable, +Make sure the vesting owner is multisig otherwise it will be +catastrophic.* + + +## Functions +### constructor + +Setup the vesting schedule. + + +```solidity +constructor( + address _logic, + address _SOV, + address _stakingAddress, + address _tokenOwner, + address _feeSharingCollector, + uint256 _extendDurationFor +) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_logic`|`address`|The address of logic contract.| +|`_SOV`|`address`|The SOV token address.| +|`_stakingAddress`|`address`|| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_feeSharingCollector`|`address`|Fee sharing proxy address.| +|`_extendDurationFor`|`uint256`|Duration till the unlocked tokens are extended.| + + +### setImplementation + +Set address of the implementation - vesting owner. + +*Overriding setImplementation function of UpgradableProxy. The logic can only be +modified when both token owner and veting owner approve. Since +setImplementation can only be called by vesting owner, we also need to check +if the new logic is already approved by the token owner.* + + +```solidity +function setImplementation(address _implementation) public onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementation`|`address`|Address of the implementation. Must match with what is set by token owner.| + + diff --git a/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingFactory.sol/contract.FourYearVestingFactory.md b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingFactory.sol/contract.FourYearVestingFactory.md new file mode 100644 index 000000000..a5af41e36 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingFactory.sol/contract.FourYearVestingFactory.md @@ -0,0 +1,57 @@ +# FourYearVestingFactory +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/fouryear/FourYearVestingFactory.sol) + +**Inherits:** +[IFourYearVestingFactory](/contracts/governance/Vesting/fouryear/IFourYearVestingFactory.sol/interface.IFourYearVestingFactory.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +Factory pattern allows to create multiple instances +of the same contract and keep track of them easier. + + +## Functions +### deployFourYearVesting + +Deploys four year vesting contract. + +*_vestingOwnerMultisig should ALWAYS be multisig.* + + +```solidity +function deployFourYearVesting( + address _SOV, + address _staking, + address _tokenOwner, + address _feeSharing, + address _vestingOwnerMultisig, + address _fourYearVestingLogic, + uint256 _extendDurationFor +) external onlyOwner returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`address`|the address of SOV token.| +|`_staking`|`address`|The address of staking contract.| +|`_tokenOwner`|`address`|The owner of the tokens.| +|`_feeSharing`|`address`|The address of fee sharing contract.| +|`_vestingOwnerMultisig`|`address`|The address of an owner of vesting contract.| +|`_fourYearVestingLogic`|`address`|The implementation contract.| +|`_extendDurationFor`|`uint256`|Duration till the unlocked tokens are extended.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The four year vesting contract address.| + + +## Events +### FourYearVestingCreated +*Added an event to keep track of the vesting contract created for a token owner* + + +```solidity +event FourYearVestingCreated(address indexed tokenOwner, address indexed vestingAddress); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingLogic.sol/contract.FourYearVestingLogic.md b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingLogic.sol/contract.FourYearVestingLogic.md new file mode 100644 index 000000000..7f0a74453 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingLogic.sol/contract.FourYearVestingLogic.md @@ -0,0 +1,368 @@ +# FourYearVestingLogic +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/fouryear/FourYearVestingLogic.sol) + +**Inherits:** +[IFourYearVesting](/contracts/governance/Vesting/fouryear/IFourYearVesting.sol/interface.IFourYearVesting.md), [FourYearVestingStorage](/contracts/governance/Vesting/fouryear/FourYearVestingStorage.sol/contract.FourYearVestingStorage.md), [ApprovalReceiver](/contracts/governance/ApprovalReceiver.sol/contract.ApprovalReceiver.md) + +Staking, delegating and withdrawal functionality. + +*Deployed by FourYearVestingFactory contract.* + + +## Functions +### onlyOwners + +*Throws if called by any account other than the token owner or the contract owner.* + + +```solidity +modifier onlyOwners(); +``` + +### onlyTokenOwner + +*Throws if called by any account other than the token owner.* + + +```solidity +modifier onlyTokenOwner(); +``` + +### setMaxInterval + +Sets the max interval. + + +```solidity +function setMaxInterval(uint256 _interval) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_interval`|`uint256`|Max interval for which tokens scheduled shall be staked.| + + +### stakeTokens + +Stakes tokens according to the vesting schedule. + + +```solidity +function stakeTokens(uint256 _amount, uint256 _restartStakeSchedule) + external + returns (uint256 lastSchedule, uint256 remainingAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_amount`|`uint256`|The amount of tokens to stake.| +|`_restartStakeSchedule`|`uint256`|The time from which staking schedule restarts. The issue is that we can only stake tokens for a max duration. Thus, we need to restart from the lastSchedule.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`lastSchedule`|`uint256`|The max duration for which tokens were staked.| +|`remainingAmount`|`uint256`|The amount outstanding - to be staked.| + + +### stakeTokensWithApproval + +Stakes tokens according to the vesting schedule. + +*This function will be invoked from receiveApproval.* + +*SOV.approveAndCall -> this.receiveApproval -> this.stakeTokensWithApproval* + + +```solidity +function stakeTokensWithApproval(address _sender, uint256 _amount, uint256 _restartStakeSchedule) + external + onlyThisContract + returns (uint256 lastSchedule, uint256 remainingAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|The sender of SOV.approveAndCall| +|`_amount`|`uint256`|The amount of tokens to stake.| +|`_restartStakeSchedule`|`uint256`|The time from which staking schedule restarts. The issue is that we can only stake tokens for a max duration. Thus, we need to restart from the lastSchedule.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`lastSchedule`|`uint256`|The max duration for which tokens were staked.| +|`remainingAmount`|`uint256`|The amount outstanding - to be staked.| + + +### delegate + +Delegate votes from `msg.sender` which are locked until lockDate +to `delegatee`. + + +```solidity +function delegate(address _delegatee) external onlyTokenOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_delegatee`|`address`|The address to delegate votes to.| + + +### withdrawTokens + +Withdraws unlocked tokens from the staking contract and +forwards them to an address specified by the token owner. + +*Withdraw for each unlocked position.* + +*Don't change FOUR_WEEKS to TWO_WEEKS, a lot of vestings already deployed with FOUR_WEEKS +workaround found, but it doesn't work with TWO_WEEKS* + + +```solidity +function withdrawTokens(address receiver) external onlyTokenOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The receiving address.| + + +### collectDividends + +Collect dividends from fee sharing proxy. + + +```solidity +function collectDividends(address _loanPoolToken, uint32 _maxCheckpoints, address _receiver) external onlyTokenOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_loanPoolToken`|`address`|The loan pool token address.| +|`_maxCheckpoints`|`uint32`|Maximum number of checkpoints to be processed.| +|`_receiver`|`address`|The receiver of tokens or msg.sender| + + +### changeTokenOwner + +Change token owner - only vesting owner is allowed to change. + +*Invokes the fee sharing proxy.* + +*Modifies token owner. This must be followed by approval +from token owner.* + + +```solidity +function changeTokenOwner(address _newTokenOwner) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newTokenOwner`|`address`|Address of new token owner.| + + +### approveOwnershipTransfer + +Approve token owner change - only token Owner. + +*Token owner can only be modified +when both vesting owner and token owner have approved. This +function ascertains the approval of token owner.* + + +```solidity +function approveOwnershipTransfer() public onlyTokenOwner; +``` + +### setImpl + +Set address of the implementation - only Token Owner. + +*This function sets the new implementation address. +It must also be approved by the Vesting owner.* + + +```solidity +function setImpl(address _newImplementation) public onlyTokenOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newImplementation`|`address`|Address of the new implementation.| + + +### migrateToNewStakingContract + +Allows the owners to migrate the positions +to a new staking contract. + + +```solidity +function migrateToNewStakingContract() external onlyOwners; +``` + +### extendStaking + +Extends stakes(unlocked till timeDuration) for four year vesting contracts. + +*Tokens are vested for 4 years. Since the max staking +period is 3 years and the tokens are unlocked only after the first year(timeDuration) is +passed, hence, we usually extend the duration of staking for all unlocked tokens for the first +year by 3 years. In some cases, the timeDuration can differ.* + + +```solidity +function extendStaking() external; +``` + +### _stakeTokens + +Stakes tokens according to the vesting schedule. Low level function. + +*Once here the allowance of tokens is taken for granted.* + + +```solidity +function _stakeTokens(address _sender, uint256 _amount, uint256 _restartStakeSchedule) + internal + returns (uint256 lastSchedule, uint256 remainingAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|The sender of tokens to stake.| +|`_amount`|`uint256`|The amount of tokens to stake.| +|`_restartStakeSchedule`|`uint256`|The time from which staking schedule restarts. The issue is that we can only stake tokens for a max duration. Thus, we need to restart from the lastSchedule.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`lastSchedule`|`uint256`|The max duration for which tokens were staked.| +|`remainingAmount`|`uint256`|The amount outstanding - to be staked.| + + +### _withdrawTokens + +Withdraws tokens from the staking contract and forwards them +to an address specified by the token owner. Low level function. + +*Transfer the tokens to this contract.* + +*Allow the staking contract to access them.* + +*Once here the caller permission is taken for granted.* + + +```solidity +function _withdrawTokens(address receiver, bool isGovernance) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The receiving address.| +|`isGovernance`|`bool`|Whether all tokens (true) or just unlocked tokens (false).| + + +### _getToken + +Overrides default ApprovalReceiver._getToken function to +register SOV token on this contract. + +*Usually we just need to iterate over the possible dates until now.* + +*In the unlikely case that all tokens have been unlocked early, +allow to withdraw all of them.* + +*Withdraw for each unlocked position.* + +*Don't change FOUR_WEEKS to TWO_WEEKS, a lot of vestings already deployed with FOUR_WEEKS +workaround found, but it doesn't work with TWO_WEEKS* + +*For four year vesting, withdrawal of stakes for the first year is not allowed. These +stakes are extended for three years. In some cases the withdrawal may be allowed at a different +time and hence we use extendDurationFor.* + +*Read amount to withdraw.* + +*Withdraw if > 0* + + +```solidity +function _getToken() internal view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The address of SOV token.| + + +### _getSelectors + +Overrides default ApprovalReceiver._getSelectors function to +register stakeTokensWithApproval selector on this contract. + + +```solidity +function _getSelectors() internal pure returns (bytes4[] memory); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes4[]`|The array of registered selectors on this contract.| + + +## Events +### TokensStaked + +```solidity +event TokensStaked(address indexed caller, uint256 amount); +``` + +### VotesDelegated + +```solidity +event VotesDelegated(address indexed caller, address delegatee); +``` + +### TokensWithdrawn + +```solidity +event TokensWithdrawn(address indexed caller, address receiver); +``` + +### DividendsCollected + +```solidity +event DividendsCollected(address indexed caller, address loanPoolToken, address receiver, uint32 maxCheckpoints); +``` + +### MigratedToNewStakingContract + +```solidity +event MigratedToNewStakingContract(address indexed caller, address newStakingContract); +``` + +### TokenOwnerChanged + +```solidity +event TokenOwnerChanged(address indexed newOwner, address indexed oldOwner); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingStorage.sol/contract.FourYearVestingStorage.md b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingStorage.sol/contract.FourYearVestingStorage.md new file mode 100644 index 000000000..4c48a3f90 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/fouryear/FourYearVestingStorage.sol/contract.FourYearVestingStorage.md @@ -0,0 +1,166 @@ +# FourYearVestingStorage +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/fouryear/FourYearVestingStorage.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +This contract is just the storage required for four year vesting. +It is parent of FourYearVestingLogic and FourYearVesting. + +*Use Ownable as a parent to align storage structure for Logic and Proxy contracts.* + + +## State Variables +### SOV +The SOV token contract. + + +```solidity +IERC20 public SOV; +``` + + +### staking +The staking contract address. + + +```solidity +IStaking public staking; +``` + + +### tokenOwner +The owner of the vested tokens. + + +```solidity +address public tokenOwner; +``` + + +### feeSharingCollector +Fee sharing Proxy. + + +```solidity +IFeeSharingCollector public feeSharingCollector; +``` + + +### cliff +The cliff. After this time period the tokens begin to unlock. + + +```solidity +uint256 public constant cliff = 4 weeks; +``` + + +### duration +The duration. After this period all tokens will have been unlocked. + + +```solidity +uint256 public constant duration = 156 weeks; +``` + + +### startDate +The start date of the vesting. + + +```solidity +uint256 public startDate; +``` + + +### endDate +The end date of the vesting. + + +```solidity +uint256 public endDate; +``` + + +### FOUR_WEEKS +Constant used for computing the vesting dates. + + +```solidity +uint256 public constant FOUR_WEEKS = 4 weeks; +``` + + +### maxInterval +Maximum interval to stake tokens at one go + + +```solidity +uint256 public maxInterval; +``` + + +### lastStakingSchedule +End of previous staking schedule. + + +```solidity +uint256 public lastStakingSchedule; +``` + + +### remainingStakeAmount +Amount of shares left to be staked. + + +```solidity +uint256 public remainingStakeAmount; +``` + + +### durationLeft +Durations left. + + +```solidity +uint256 public durationLeft; +``` + + +### cliffAdded +Cliffs added. + + +```solidity +uint256 public cliffAdded; +``` + + +### newTokenOwner +Address of new token owner. + + +```solidity +address public newTokenOwner; +``` + + +### newImplementation +Address of new implementation. + + +```solidity +address public newImplementation; +``` + + +### extendDurationFor +Duration(from start) till the time unlocked tokens are extended(for 3 years) + + +```solidity +uint256 public extendDurationFor; +``` + + diff --git a/foundry/docs/src/contracts/governance/Vesting/fouryear/IFourYearVesting.sol/interface.IFourYearVesting.md b/foundry/docs/src/contracts/governance/Vesting/fouryear/IFourYearVesting.sol/interface.IFourYearVesting.md new file mode 100644 index 000000000..89d710afe --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/fouryear/IFourYearVesting.sol/interface.IFourYearVesting.md @@ -0,0 +1,26 @@ +# IFourYearVesting +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/fouryear/IFourYearVesting.sol) + +*Interfaces are used to cast a contract address into a callable instance. +This interface is used by FourYearVestingLogic contract to implement stakeTokens function +and on VestingRegistry contract to call IFourYearVesting(vesting).stakeTokens function +at a vesting instance.* + + +## Functions +### endDate + + +```solidity +function endDate() external returns (uint256); +``` + +### stakeTokens + + +```solidity +function stakeTokens(uint256 _amount, uint256 _restartStakeSchedule) + external + returns (uint256 lastSchedule, uint256 remainingAmount); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/fouryear/IFourYearVestingFactory.sol/interface.IFourYearVestingFactory.md b/foundry/docs/src/contracts/governance/Vesting/fouryear/IFourYearVestingFactory.sol/interface.IFourYearVestingFactory.md new file mode 100644 index 000000000..7017bf884 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/fouryear/IFourYearVestingFactory.sol/interface.IFourYearVestingFactory.md @@ -0,0 +1,25 @@ +# IFourYearVestingFactory +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/governance/Vesting/fouryear/IFourYearVestingFactory.sol) + +*Interfaces are used to cast a contract address into a callable instance. +This interface is used by FourYearVestingFactory contract to override empty +implemention of deployFourYearVesting function +and use an instance of FourYearVestingFactory.* + + +## Functions +### deployFourYearVesting + + +```solidity +function deployFourYearVesting( + address _SOV, + address _staking, + address _tokenOwner, + address _feeSharing, + address _vestingOwnerMultisig, + address _fourYearVestingLogic, + uint256 _extendDurationFor +) external returns (address); +``` + diff --git a/foundry/docs/src/contracts/governance/Vesting/fouryear/README.md b/foundry/docs/src/contracts/governance/Vesting/fouryear/README.md new file mode 100644 index 000000000..5e6e6a621 --- /dev/null +++ b/foundry/docs/src/contracts/governance/Vesting/fouryear/README.md @@ -0,0 +1,9 @@ + + +# Contents +- [FourYearVesting](FourYearVesting.sol/contract.FourYearVesting.md) +- [FourYearVestingFactory](FourYearVestingFactory.sol/contract.FourYearVestingFactory.md) +- [FourYearVestingLogic](FourYearVestingLogic.sol/contract.FourYearVestingLogic.md) +- [FourYearVestingStorage](FourYearVestingStorage.sol/contract.FourYearVestingStorage.md) +- [IFourYearVesting](IFourYearVesting.sol/interface.IFourYearVesting.md) +- [IFourYearVestingFactory](IFourYearVestingFactory.sol/interface.IFourYearVestingFactory.md) diff --git a/foundry/docs/src/contracts/interfaces/IChai.sol/contract.IChai.md b/foundry/docs/src/contracts/interfaces/IChai.sol/contract.IChai.md new file mode 100644 index 000000000..228b8f969 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IChai.sol/contract.IChai.md @@ -0,0 +1,36 @@ +# IChai +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IChai.sol) + +**Inherits:** +[IERC20](/contracts/interfaces/IERC20.sol/contract.IERC20.md) + + +## Functions +### move + + +```solidity +function move(address src, address dst, uint256 wad) external returns (bool); +``` + +### join + + +```solidity +function join(address dst, uint256 wad) external; +``` + +### draw + + +```solidity +function draw(address src, uint256 wad) external; +``` + +### exit + + +```solidity +function exit(address src, uint256 wad) external; +``` + diff --git a/foundry/docs/src/contracts/interfaces/IChai.sol/interface.IPot.md b/foundry/docs/src/contracts/interfaces/IChai.sol/interface.IPot.md new file mode 100644 index 000000000..b1339aa72 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IChai.sol/interface.IPot.md @@ -0,0 +1,29 @@ +# IPot +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IChai.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### dsr + + +```solidity +function dsr() external view returns (uint256); +``` + +### chi + + +```solidity +function chi() external view returns (uint256); +``` + +### rho + + +```solidity +function rho() external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/interfaces/IConverterAMM.sol/interface.IConverterAMM.md b/foundry/docs/src/contracts/interfaces/IConverterAMM.sol/interface.IConverterAMM.md new file mode 100644 index 000000000..d4e74f9b4 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IConverterAMM.sol/interface.IConverterAMM.md @@ -0,0 +1,12 @@ +# IConverterAMM +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IConverterAMM.sol) + + +## Functions +### withdrawFees + + +```solidity +function withdrawFees(address receiver) external returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/interfaces/IERC20.sol/contract.IERC20.md b/foundry/docs/src/contracts/interfaces/IERC20.sol/contract.IERC20.md new file mode 100644 index 000000000..b4266a5d1 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IERC20.sol/contract.IERC20.md @@ -0,0 +1,85 @@ +# IERC20 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IERC20.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## State Variables +### name + +```solidity +string public name; +``` + + +### decimals + +```solidity +uint8 public decimals; +``` + + +### symbol + +```solidity +string public symbol; +``` + + +## Functions +### totalSupply + + +```solidity +function totalSupply() external view returns (uint256); +``` + +### balanceOf + + +```solidity +function balanceOf(address _who) external view returns (uint256); +``` + +### allowance + + +```solidity +function allowance(address _owner, address _spender) external view returns (uint256); +``` + +### approve + + +```solidity +function approve(address _spender, uint256 _value) external returns (bool); +``` + +### transfer + + +```solidity +function transfer(address _to, uint256 _value) external returns (bool); +``` + +### transferFrom + + +```solidity +function transferFrom(address _from, address _to, uint256 _value) external returns (bool); +``` + +## Events +### Transfer + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +### Approval + +```solidity +event Approval(address indexed owner, address indexed spender, uint256 value); +``` + diff --git a/foundry/docs/src/contracts/interfaces/IERC20Mintable.sol/contract.IERC20Mintable.md b/foundry/docs/src/contracts/interfaces/IERC20Mintable.sol/contract.IERC20Mintable.md new file mode 100644 index 000000000..6064baebd --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IERC20Mintable.sol/contract.IERC20Mintable.md @@ -0,0 +1,92 @@ +# IERC20Mintable +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IERC20Mintable.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## State Variables +### name + +```solidity +string public name; +``` + + +### decimals + +```solidity +uint8 public decimals; +``` + + +### symbol + +```solidity +string public symbol; +``` + + +## Functions +### totalSupply + + +```solidity +function totalSupply() external view returns (uint256); +``` + +### balanceOf + + +```solidity +function balanceOf(address _who) external view returns (uint256); +``` + +### allowance + + +```solidity +function allowance(address _owner, address _spender) external view returns (uint256); +``` + +### approve + + +```solidity +function approve(address _spender, uint256 _value) external returns (bool); +``` + +### transfer + + +```solidity +function transfer(address _to, uint256 _value) external returns (bool); +``` + +### transferFrom + + +```solidity +function transferFrom(address _from, address _to, uint256 _value) external returns (bool); +``` + +### mint + + +```solidity +function mint(address _to, uint256 _value) external; +``` + +## Events +### Transfer + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +### Approval + +```solidity +event Approval(address indexed owner, address indexed spender, uint256 value); +``` + diff --git a/foundry/docs/src/contracts/interfaces/IERC777.sol/interface.IERC777.md b/foundry/docs/src/contracts/interfaces/IERC777.sol/interface.IERC777.md new file mode 100644 index 000000000..b8ef0ba62 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IERC777.sol/interface.IERC777.md @@ -0,0 +1,222 @@ +# IERC777 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IERC777.sol) + +*Interface of the ERC777Token standard as defined in the EIP. +This contract uses the +https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let +token holders and recipients react to token movements by using setting implementers +for the associated interfaces in said registry. See {IERC1820Registry} and +{ERC1820Implementer}.* + + +## Functions +### name + +*Returns the name of the token.* + + +```solidity +function name() external view returns (string memory); +``` + +### symbol + +*Returns the symbol of the token, usually a shorter version of the +name.* + + +```solidity +function symbol() external view returns (string memory); +``` + +### granularity + +*Returns the smallest part of the token that is not divisible. This +means all token operations (creation, movement and destruction) must have +amounts that are a multiple of this number. +For most token contracts, this value will equal 1.* + + +```solidity +function granularity() external view returns (uint256); +``` + +### totalSupply + +*Returns the amount of tokens in existence.* + + +```solidity +function totalSupply() external view returns (uint256); +``` + +### balanceOf + +*Returns the amount of tokens owned by an account (`owner`).* + + +```solidity +function balanceOf(address owner) external view returns (uint256); +``` + +### send + +*Moves `amount` tokens from the caller's account to `recipient`. +If send or receive hooks are registered for the caller and `recipient`, +the corresponding functions will be called with `data` and empty +`operatorData`. See {IERC777Sender} and {IERC777Recipient}. +Emits a {Sent} event. +Requirements +- the caller must have at least `amount` tokens. +- `recipient` cannot be the zero address. +- if `recipient` is a contract, it must implement the {IERC777Recipient} +interface.* + + +```solidity +function send(address recipient, uint256 amount, bytes calldata data) external; +``` + +### burn + +*Destroys `amount` tokens from the caller's account, reducing the +total supply. +If a send hook is registered for the caller, the corresponding function +will be called with `data` and empty `operatorData`. See {IERC777Sender}. +Emits a {Burned} event. +Requirements +- the caller must have at least `amount` tokens.* + + +```solidity +function burn(uint256 amount, bytes calldata data) external; +``` + +### isOperatorFor + +*Returns true if an account is an operator of `tokenHolder`. +Operators can send and burn tokens on behalf of their owners. All +accounts are their own operator. +See [operatorSend](/contracts/interfaces/IERC777.sol/interface.IERC777.md#operatorsend) and {operatorBurn}.* + + +```solidity +function isOperatorFor(address operator, address tokenHolder) external view returns (bool); +``` + +### authorizeOperator + +*Make an account an operator of the caller. +See [isOperatorFor](/contracts/interfaces/IERC777.sol/interface.IERC777.md#isoperatorfor). +Emits an {AuthorizedOperator} event. +Requirements +- `operator` cannot be calling address.* + + +```solidity +function authorizeOperator(address operator) external; +``` + +### revokeOperator + +*Make an account an operator of the caller. +See [isOperatorFor](/contracts/interfaces/IERC777.sol/interface.IERC777.md#isoperatorfor) and {defaultOperators}. +Emits a {RevokedOperator} event. +Requirements +- `operator` cannot be calling address.* + + +```solidity +function revokeOperator(address operator) external; +``` + +### defaultOperators + +*Returns the list of default operators. These accounts are operators +for all token holders, even if [authorizeOperator](/contracts/interfaces/IERC777.sol/interface.IERC777.md#authorizeoperator) was never called on +them. +This list is immutable, but individual holders may revoke these via +{revokeOperator}, in which case {isOperatorFor} will return false.* + + +```solidity +function defaultOperators() external view returns (address[] memory); +``` + +### operatorSend + +*Moves `amount` tokens from `sender` to `recipient`. The caller must +be an operator of `sender`. +If send or receive hooks are registered for `sender` and `recipient`, +the corresponding functions will be called with `data` and +`operatorData`. See {IERC777Sender} and {IERC777Recipient}. +Emits a {Sent} event. +Requirements +- `sender` cannot be the zero address. +- `sender` must have at least `amount` tokens. +- the caller must be an operator for `sender`. +- `recipient` cannot be the zero address. +- if `recipient` is a contract, it must implement the {IERC777Recipient} +interface.* + + +```solidity +function operatorSend( + address sender, + address recipient, + uint256 amount, + bytes calldata data, + bytes calldata operatorData +) external; +``` + +### operatorBurn + +*Destoys `amount` tokens from `account`, reducing the total supply. +The caller must be an operator of `account`. +If a send hook is registered for `account`, the corresponding function +will be called with `data` and `operatorData`. See {IERC777Sender}. +Emits a {Burned} event. +Requirements +- `account` cannot be the zero address. +- `account` must have at least `amount` tokens. +- the caller must be an operator for `account`.* + + +```solidity +function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external; +``` + +## Events +### Sent + +```solidity +event Sent( + address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData +); +``` + +### Minted + +```solidity +event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); +``` + +### Burned + +```solidity +event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); +``` + +### AuthorizedOperator + +```solidity +event AuthorizedOperator(address indexed operator, address indexed tokenHolder); +``` + +### RevokedOperator + +```solidity +event RevokedOperator(address indexed operator, address indexed tokenHolder); +``` + diff --git a/foundry/docs/src/contracts/interfaces/IERC777Recipient.sol/interface.IERC777Recipient.md b/foundry/docs/src/contracts/interfaces/IERC777Recipient.sol/interface.IERC777Recipient.md new file mode 100644 index 000000000..b5aeb1c4a --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IERC777Recipient.sol/interface.IERC777Recipient.md @@ -0,0 +1,33 @@ +# IERC777Recipient +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IERC777Recipient.sol) + +*Interface of the ERC777TokensRecipient standard as defined in the EIP. +Accounts can be notified of {IERC777} tokens being sent to them by having a +contract implement this interface (contract holders can be their own +implementer) and registering it on the +https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. +See {IERC1820Registry} and {ERC1820Implementer}.* + + +## Functions +### tokensReceived + +*Called by an {IERC777} token contract whenever tokens are being +moved or created into a registered account (`to`). The type of operation +is conveyed by `from` being the zero address or not. +This call occurs _after_ the token contract's state is updated, so +{IERC777-balanceOf}, etc., can be used to query the post-operation state. +This function may revert to prevent the operation from being executed.* + + +```solidity +function tokensReceived( + address operator, + address from, + address to, + uint256 amount, + bytes calldata userData, + bytes calldata operatorData +) external; +``` + diff --git a/foundry/docs/src/contracts/interfaces/IERC777Sender.sol/interface.IERC777Sender.md b/foundry/docs/src/contracts/interfaces/IERC777Sender.sol/interface.IERC777Sender.md new file mode 100644 index 000000000..2b370ed68 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IERC777Sender.sol/interface.IERC777Sender.md @@ -0,0 +1,33 @@ +# IERC777Sender +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IERC777Sender.sol) + +*Interface of the ERC777TokensSender standard as defined in the EIP. +{IERC777} Token holders can be notified of operations performed on their +tokens by having a contract implement this interface (contract holders can be +their own implementer) and registering it on the +https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. +See {IERC1820Registry} and {ERC1820Implementer}.* + + +## Functions +### tokensToSend + +*Called by an {IERC777} token contract whenever a registered holder's +(`from`) tokens are about to be moved or destroyed. The type of operation +is conveyed by `to` being the zero address or not. +This call occurs _before_ the token contract's state is updated, so +{IERC777-balanceOf}, etc., can be used to query the pre-operation state. +This function may revert to prevent the operation from being executed.* + + +```solidity +function tokensToSend( + address operator, + address from, + address to, + uint256 amount, + bytes calldata userData, + bytes calldata operatorData +) external; +``` + diff --git a/foundry/docs/src/contracts/interfaces/ILoanPool.sol/interface.ILoanPool.md b/foundry/docs/src/contracts/interfaces/ILoanPool.sol/interface.ILoanPool.md new file mode 100644 index 000000000..d3dd06cc8 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/ILoanPool.sol/interface.ILoanPool.md @@ -0,0 +1,29 @@ +# ILoanPool +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/ILoanPool.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### tokenPrice + + +```solidity +function tokenPrice() external view returns (uint256 price); +``` + +### borrowInterestRate + + +```solidity +function borrowInterestRate() external view returns (uint256); +``` + +### totalAssetSupply + + +```solidity +function totalAssetSupply() external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/interfaces/ILoanTokenLogicProxy.sol/interface.ILoanTokenLogicProxy.md b/foundry/docs/src/contracts/interfaces/ILoanTokenLogicProxy.sol/interface.ILoanTokenLogicProxy.md new file mode 100644 index 000000000..41c61b047 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/ILoanTokenLogicProxy.sol/interface.ILoanTokenLogicProxy.md @@ -0,0 +1,26 @@ +# ILoanTokenLogicProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/ILoanTokenLogicProxy.sol) + + +## Functions +### beaconAddress + + +```solidity +function beaconAddress() external view returns (address); +``` + +### setBeaconAddress + + +```solidity +function setBeaconAddress(address _newBeaconAddress) external; +``` + +### getTarget + + +```solidity +function getTarget() external view returns (address); +``` + diff --git a/foundry/docs/src/contracts/interfaces/ILoanTokenModules.sol/interface.ILoanTokenModules.md b/foundry/docs/src/contracts/interfaces/ILoanTokenModules.sol/interface.ILoanTokenModules.md new file mode 100644 index 000000000..cab4be09b --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/ILoanTokenModules.sol/interface.ILoanTokenModules.md @@ -0,0 +1,553 @@ +# ILoanTokenModules +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/ILoanTokenModules.sol) + + +## Functions +### setAdmin + + +```solidity +function setAdmin(address _admin) external; +``` + +### setPauser + + +```solidity +function setPauser(address _pauser) external; +``` + +### setupLoanParams + + +```solidity +function setupLoanParams(LoanParams[] calldata loanParamsList, bool areTorqueLoans) external; +``` + +### disableLoanParams + + +```solidity +function disableLoanParams(address[] calldata collateralTokens, bool[] calldata isTorqueLoans) external; +``` + +### setDemandCurve + + +```solidity +function setDemandCurve( + uint256 _baseRate, + uint256 _rateMultiplier, + uint256 _lowUtilBaseRate, + uint256 _lowUtilRateMultiplier, + uint256 _targetLevel, + uint256 _kinkLevel, + uint256 _maxScaleRate +) external; +``` + +### toggleFunctionPause + + +```solidity +function toggleFunctionPause(string calldata funcId, bool isPaused) external; +``` + +### setTransactionLimits + + +```solidity +function setTransactionLimits(address[] calldata addresses, uint256[] calldata limits) external; +``` + +### changeLoanTokenNameAndSymbol + + +```solidity +function changeLoanTokenNameAndSymbol(string calldata _name, string calldata _symbol) external; +``` + +### marginTrade + +END LOAN TOKEN SETTINGS LOWER ADMIN +START LOAN TOKEN LOGIC STANDARD + + +```solidity +function marginTrade( + bytes32 loanId, + uint256 leverageAmount, + uint256 loanTokenSent, + uint256 collateralTokenSent, + address collateralTokenAddress, + address trader, + uint256 minEntryPrice, + bytes calldata loanDataBytes +) external payable returns (uint256, uint256); +``` + +### marginTradeAffiliate + + +```solidity +function marginTradeAffiliate( + bytes32 loanId, + uint256 leverageAmount, + uint256 loanTokenSent, + uint256 collateralTokenSent, + address collateralTokenAddress, + address trader, + uint256 minEntryPrice, + address affiliateReferrer, + bytes calldata loanDataBytes +) external payable returns (uint256, uint256); +``` + +### borrowInterestRate + + +```solidity +function borrowInterestRate() external view returns (uint256); +``` + +### mint + + +```solidity +function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount); +``` + +### burn + + +```solidity +function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); +``` + +### checkPause + + +```solidity +function checkPause(string calldata funcId) external view returns (bool isPaused); +``` + +### nextBorrowInterestRate + + +```solidity +function nextBorrowInterestRate(uint256 borrowAmount) external view returns (uint256); +``` + +### totalAssetBorrow + + +```solidity +function totalAssetBorrow() external view returns (uint256); +``` + +### totalAssetSupply + + +```solidity +function totalAssetSupply() external view returns (uint256); +``` + +### borrow + + +```solidity +function borrow( + bytes32 loanId, + uint256 withdrawAmount, + uint256 initialLoanDuration, + uint256 collateralTokenSent, + address collateralTokenAddress, + address borrower, + address receiver, + bytes calldata +) external payable returns (uint256, uint256); +``` + +### transfer + + +```solidity +function transfer(address _to, uint256 _value) external returns (bool); +``` + +### transferFrom + + +```solidity +function transferFrom(address _from, address _to, uint256 _value) external returns (bool); +``` + +### setLiquidityMiningAddress + + +```solidity +function setLiquidityMiningAddress(address LMAddress) external; +``` + +### getLiquidityMiningAddress + + +```solidity +function getLiquidityMiningAddress() external view returns (address); +``` + +### setStakingContractAddress + + +```solidity +function setStakingContractAddress(address _stakingContractAddress) external; +``` + +### getStakingContractAddress + + +```solidity +function getStakingContractAddress() external view returns (address); +``` + +### getEstimatedMarginDetails + + +```solidity +function getEstimatedMarginDetails( + uint256 leverageAmount, + uint256 loanTokenSent, + uint256 collateralTokenSent, + address collateralTokenAddress +) external view returns (uint256 principal, uint256 collateral, uint256 interestRate); +``` + +### getDepositAmountForBorrow + + +```solidity +function getDepositAmountForBorrow(uint256 borrowAmount, uint256 initialLoanDuration, address collateralTokenAddress) + external + view + returns (uint256 depositAmount); +``` + +### getBorrowAmountForDeposit + + +```solidity +function getBorrowAmountForDeposit(uint256 depositAmount, uint256 initialLoanDuration, address collateralTokenAddress) + external + view + returns (uint256 borrowAmount); +``` + +### checkPriceDivergence + + +```solidity +function checkPriceDivergence(uint256 loanTokenSent, address collateralTokenAddress, uint256 minEntryPrice) + external + view; +``` + +### getMaxEscrowAmount + + +```solidity +function getMaxEscrowAmount(uint256 leverageAmount) external view returns (uint256 maxEscrowAmount); +``` + +### checkpointPrice + + +```solidity +function checkpointPrice(address _user) external view returns (uint256 price); +``` + +### assetBalanceOf + + +```solidity +function assetBalanceOf(address _owner) external view returns (uint256); +``` + +### profitOf + + +```solidity +function profitOf(address user) external view returns (int256); +``` + +### tokenPrice + + +```solidity +function tokenPrice() external view returns (uint256 price); +``` + +### avgBorrowInterestRate + + +```solidity +function avgBorrowInterestRate() external view returns (uint256); +``` + +### supplyInterestRate + + +```solidity +function supplyInterestRate() external view returns (uint256); +``` + +### nextSupplyInterestRate + + +```solidity +function nextSupplyInterestRate(uint256 supplyAmount) external view returns (uint256); +``` + +### totalSupplyInterestRate + + +```solidity +function totalSupplyInterestRate(uint256 assetSupply) external view returns (uint256); +``` + +### loanTokenAddress + + +```solidity +function loanTokenAddress() external view returns (address); +``` + +### getMarginBorrowAmountAndRate + + +```solidity +function getMarginBorrowAmountAndRate(uint256 leverageAmount, uint256 depositAmount) + external + view + returns (uint256, uint256); +``` + +### withdrawRBTCTo + + +```solidity +function withdrawRBTCTo(address payable _receiverAddress, uint256 _amount) external; +``` + +### initialPrice + +START LOAN TOKEN BASE + + +```solidity +function initialPrice() external view returns (uint256); +``` + +### mint + +START LOAN TOKEN LOGIC LM + + +```solidity +function mint(address receiver, uint256 depositAmount, bool useLM) external returns (uint256 minted); +``` + +### burn + + +```solidity +function burn(address receiver, uint256 burnAmount, bool useLM) external returns (uint256 redeemed); +``` + +### mintWithBTC + +START LOAN TOKEN LOGIC WRBTC + + +```solidity +function mintWithBTC(address receiver, bool useLM) external payable returns (uint256 mintAmount); +``` + +### burnToBTC + + +```solidity +function burnToBTC(address receiver, uint256 burnAmount, bool useLM) external returns (uint256 loanAmountPaid); +``` + +### marketLiquidity + + +```solidity +function marketLiquidity() external view returns (uint256); +``` + +### calculateSupplyInterestRate + + +```solidity +function calculateSupplyInterestRate(uint256 assetBorrow, uint256 assetSupply) external view returns (uint256); +``` + +### pauser + +START LOAN TOKEN LOGIC STORAGE + + +```solidity +function pauser() external view returns (address); +``` + +### liquidityMiningAddress + + +```solidity +function liquidityMiningAddress() external view returns (address); +``` + +### name + + +```solidity +function name() external view returns (string memory); +``` + +### symbol + + +```solidity +function symbol() external view returns (string memory); +``` + +### approve + +START ADVANCED TOKEN + + +```solidity +function approve(address _spender, uint256 _value) external returns (bool); +``` + +### allowance + +START ADVANCED TOKEN STORAGE + + +```solidity +function allowance(address _owner, address _spender) external view returns (uint256); +``` + +### balanceOf + + +```solidity +function balanceOf(address _owner) external view returns (uint256); +``` + +### totalSupply + + +```solidity +function totalSupply() external view returns (uint256); +``` + +### loanParamsIds + + +```solidity +function loanParamsIds(uint256) external view returns (bytes32); +``` + +## Events +### Transfer +EVENT +topic: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +### Approval +topic: 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 + + +```solidity +event Approval(address indexed owner, address indexed spender, uint256 value); +``` + +### AllowanceUpdate +topic: 0x628e75c63c1873bcd3885f7aee9f58ee36f60dc789b2a6b3a978c4189bc548ba + + +```solidity +event AllowanceUpdate(address indexed owner, address indexed spender, uint256 valueBefore, uint256 valueAfter); +``` + +### Mint +topic: 0xb4c03061fb5b7fed76389d5af8f2e0ddb09f8c70d1333abbb62582835e10accb + + +```solidity +event Mint(address indexed minter, uint256 tokenAmount, uint256 assetAmount, uint256 price); +``` + +### Burn +topic: 0x743033787f4738ff4d6a7225ce2bd0977ee5f86b91a902a58f5e4d0b297b4644 + + +```solidity +event Burn(address indexed burner, uint256 tokenAmount, uint256 assetAmount, uint256 price); +``` + +### FlashBorrow +topic: 0xc688ff9bd4a1c369dd44c5cf64efa9db6652fb6b280aa765cd43f17d256b816e + + +```solidity +event FlashBorrow(address borrower, address target, address loanToken, uint256 loanAmount); +``` + +### SetTransactionLimits +topic: 0x9bbd2de400810774339120e2f8a2b517ed748595e944529bba8ebabf314d0591 + + +```solidity +event SetTransactionLimits(address[] addresses, uint256[] limits); +``` + +### WithdrawRBTCTo + +```solidity +event WithdrawRBTCTo(address indexed to, uint256 amount); +``` + +### ToggledFunctionPaused + +```solidity +event ToggledFunctionPaused(string functionId, bool prevFlag, bool newFlag); +``` + +## Structs +### LoanParams +INTERFACE +START LOAN TOKEN SETTINGS LOWER ADMIN + + +```solidity +struct LoanParams { + bytes32 id; + bool active; + address owner; + address loanToken; + address collateralToken; + uint256 minInitialMargin; + uint256 maintenanceMargin; + uint256 maxLoanTerm; +} +``` + diff --git a/foundry/docs/src/contracts/interfaces/ISovryn.sol/contract.ISovryn.md b/foundry/docs/src/contracts/interfaces/ISovryn.sol/contract.ISovryn.md new file mode 100644 index 000000000..c794b52e5 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/ISovryn.sol/contract.ISovryn.md @@ -0,0 +1,927 @@ +# ISovryn +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/ISovryn.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md), [ProtocolSettingsEvents](/contracts/events/ProtocolSettingsEvents.sol/contract.ProtocolSettingsEvents.md), [LoanSettingsEvents](/contracts/events/LoanSettingsEvents.sol/contract.LoanSettingsEvents.md), [LoanOpeningsEvents](/contracts/events/LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md), [LoanMaintenanceEvents](/contracts/events/LoanMaintenanceEvents.sol/contract.LoanMaintenanceEvents.md), [LoanClosingsEvents](/contracts/events/LoanClosingsEvents.sol/contract.LoanClosingsEvents.md), [SwapsEvents](/contracts/events/SwapsEvents.sol/contract.SwapsEvents.md), [AffiliatesEvents](/contracts/events/AffiliatesEvents.sol/contract.AffiliatesEvents.md), [FeesEvents](/contracts/events/FeesEvents.sol/contract.FeesEvents.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### replaceContract + + +```solidity +function replaceContract(address target) external; +``` + +### setTargets + + +```solidity +function setTargets(string[] calldata sigsArr, address[] calldata targetsArr) external; +``` + +### getTarget + + +```solidity +function getTarget(string calldata sig) external view returns (address); +``` + +### setSovrynProtocolAddress + + +```solidity +function setSovrynProtocolAddress(address newProtocolAddress) external; +``` + +### setSOVTokenAddress + + +```solidity +function setSOVTokenAddress(address newSovTokenAddress) external; +``` + +### setLockedSOVAddress + + +```solidity +function setLockedSOVAddress(address newSOVLockedAddress) external; +``` + +### setMinReferralsToPayoutAffiliates + + +```solidity +function setMinReferralsToPayoutAffiliates(uint256 newMinReferrals) external; +``` + +### setPriceFeedContract + + +```solidity +function setPriceFeedContract(address newContract) external; +``` + +### setSwapsImplContract + + +```solidity +function setSwapsImplContract(address newContract) external; +``` + +### setLoanPool + + +```solidity +function setLoanPool(address[] calldata pools, address[] calldata assets) external; +``` + +### setSupportedTokens + + +```solidity +function setSupportedTokens(address[] calldata addrs, bool[] calldata toggles) external; +``` + +### setLendingFeePercent + + +```solidity +function setLendingFeePercent(uint256 newValue) external; +``` + +### setTradingFeePercent + + +```solidity +function setTradingFeePercent(uint256 newValue) external; +``` + +### setBorrowingFeePercent + + +```solidity +function setBorrowingFeePercent(uint256 newValue) external; +``` + +### setSwapExternalFeePercent + + +```solidity +function setSwapExternalFeePercent(uint256 newValue) external; +``` + +### setAffiliateFeePercent + + +```solidity +function setAffiliateFeePercent(uint256 newValue) external; +``` + +### setAffiliateTradingTokenFeePercent + + +```solidity +function setAffiliateTradingTokenFeePercent(uint256 newValue) external; +``` + +### setLiquidationIncentivePercent + + +```solidity +function setLiquidationIncentivePercent(uint256 newAmount) external; +``` + +### setMaxDisagreement + + +```solidity +function setMaxDisagreement(uint256 newAmount) external; +``` + +### setSourceBuffer + + +```solidity +function setSourceBuffer(uint256 newAmount) external; +``` + +### setMaxSwapSize + + +```solidity +function setMaxSwapSize(uint256 newAmount) external; +``` + +### setFeesController + + +```solidity +function setFeesController(address newController) external; +``` + +### withdrawFees + + +```solidity +function withdrawFees(address[] calldata tokens, address receiver) external returns (uint256 totalWRBTCWithdrawn); +``` + +### withdrawLendingFees + + +```solidity +function withdrawLendingFees(address token, address receiver, uint256 amount) external returns (bool); +``` + +### withdrawTradingFees + + +```solidity +function withdrawTradingFees(address token, address receiver, uint256 amount) external returns (bool); +``` + +### withdrawBorrowingFees + + +```solidity +function withdrawBorrowingFees(address token, address receiver, uint256 amount) external returns (bool); +``` + +### withdrawProtocolToken + + +```solidity +function withdrawProtocolToken(address receiver, uint256 amount) external returns (address, bool); +``` + +### depositProtocolToken + + +```solidity +function depositProtocolToken(uint256 amount) external; +``` + +### getLoanPoolsList + + +```solidity +function getLoanPoolsList(uint256 start, uint256 count) external view returns (bytes32[] memory); +``` + +### isLoanPool + + +```solidity +function isLoanPool(address loanPool) external view returns (bool); +``` + +### setWrbtcToken + + +```solidity +function setWrbtcToken(address wrbtcTokenAddress) external; +``` + +### setSovrynSwapContractRegistryAddress + + +```solidity +function setSovrynSwapContractRegistryAddress(address registryAddress) external; +``` + +### setProtocolTokenAddress + + +```solidity +function setProtocolTokenAddress(address _protocolTokenAddress) external; +``` + +### setRolloverBaseReward + + +```solidity +function setRolloverBaseReward(uint256 transactionCost) external; +``` + +### setRebatePercent + + +```solidity +function setRebatePercent(uint256 rebatePercent) external; +``` + +### setSpecialRebates + + +```solidity +function setSpecialRebates(address sourceToken, address destToken, uint256 specialRebatesPercent) external; +``` + +### getSpecialRebates + + +```solidity +function getSpecialRebates(address sourceToken, address destToken) + external + view + returns (uint256 specialRebatesPercent); +``` + +### togglePaused + + +```solidity +function togglePaused(bool paused) external; +``` + +### isProtocolPaused + + +```solidity +function isProtocolPaused() external view returns (bool); +``` + +### getSovrynSwapNetworkContract + + +```solidity +function getSovrynSwapNetworkContract(address sovrynSwapRegistryAddress) public view returns (address); +``` + +### getContractHexName + + +```solidity +function getContractHexName(string calldata source) external pure returns (bytes32 result); +``` + +### swapsImplExpectedRate + + +```solidity +function swapsImplExpectedRate(address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) + external + view + returns (uint256); +``` + +### swapsImplExpectedReturn + + +```solidity +function swapsImplExpectedReturn(address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) + external + view + returns (uint256 expectedReturn); +``` + +### setupLoanParams + + +```solidity +function setupLoanParams(LoanParams[] calldata loanParamsList) external returns (bytes32[] memory loanParamsIdList); +``` + +### disableLoanParams + + +```solidity +function disableLoanParams(bytes32[] calldata loanParamsIdList) external; +``` + +### getLoanParams + + +```solidity +function getLoanParams(bytes32[] calldata loanParamsIdList) + external + view + returns (LoanParams[] memory loanParamsList); +``` + +### getLoanParamsList + + +```solidity +function getLoanParamsList(address owner, uint256 start, uint256 count) + external + view + returns (bytes32[] memory loanParamsList); +``` + +### getTotalPrincipal + + +```solidity +function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); +``` + +### minInitialMargin + + +```solidity +function minInitialMargin(bytes32 loanParamsId) external view returns (uint256); +``` + +### borrowOrTradeFromPool + + +```solidity +function borrowOrTradeFromPool( + bytes32 loanParamsId, + bytes32 loanId, + bool isTorqueLoan, + uint256 initialMargin, + MarginTradeStructHelpers.SentAddresses calldata sentAddresses, + MarginTradeStructHelpers.SentAmounts calldata sentValues, + bytes calldata loanDataBytes +) external payable returns (uint256 newPrincipal, uint256 newCollateral); +``` + +### setDelegatedManager + + +```solidity +function setDelegatedManager(bytes32 loanId, address delegated, bool toggle) external; +``` + +### getEstimatedMarginExposure + + +```solidity +function getEstimatedMarginExposure( + address loanToken, + address collateralToken, + uint256 loanTokenSent, + uint256 collateralTokenSent, + uint256 interestRate, + uint256 newPrincipal +) external view returns (uint256); +``` + +### getRequiredCollateral + + +```solidity +function getRequiredCollateral( + address loanToken, + address collateralToken, + uint256 newPrincipal, + uint256 marginAmount, + bool isTorqueLoan +) external view returns (uint256 collateralAmountRequired); +``` + +### getBorrowAmount + + +```solidity +function getBorrowAmount( + address loanToken, + address collateralToken, + uint256 collateralTokenAmount, + uint256 marginAmount, + bool isTorqueLoan +) external view returns (uint256 borrowAmount); +``` + +### liquidate + + +```solidity +function liquidate(bytes32 loanId, address receiver, uint256 closeAmount) + external + payable + returns (uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken); +``` + +### rollover + + +```solidity +function rollover(bytes32 loanId, bytes calldata loanDataBytes) external; +``` + +### closeWithDeposit + + +```solidity +function closeWithDeposit(bytes32 loanId, address receiver, uint256 depositAmount) + external + payable + returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` + +### closeWithSwap + + +```solidity +function closeWithSwap( + bytes32 loanId, + address receiver, + uint256 swapAmount, + bool returnTokenIsCollateral, + bytes calldata loanDataBytes +) external returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` + +### depositCollateral + + +```solidity +function depositCollateral(bytes32 loanId, uint256 depositAmount) external payable; +``` + +### withdrawCollateral + + +```solidity +function withdrawCollateral(bytes32 loanId, address receiver, uint256 withdrawAmount) + external + returns (uint256 actualWithdrawAmount); +``` + +### withdrawAccruedInterest + + +```solidity +function withdrawAccruedInterest(address loanToken) external; +``` + +### getLenderInterestData + + +```solidity +function getLenderInterestData(address lender, address loanToken) + external + view + returns ( + uint256 interestPaid, + uint256 interestPaidDate, + uint256 interestOwedPerDay, + uint256 interestUnPaid, + uint256 interestFeePercent, + uint256 principalTotal + ); +``` + +### getLoanInterestData + + +```solidity +function getLoanInterestData(bytes32 loanId) + external + view + returns ( + address loanToken, + uint256 interestOwedPerDay, + uint256 interestDepositTotal, + uint256 interestDepositRemaining + ); +``` + +### getUserLoans + + +```solidity +function getUserLoans(address user, uint256 start, uint256 count, uint256 loanType, bool isLender, bool unsafeOnly) + external + view + returns (LoanReturnData[] memory loansData); +``` + +### getUserLoansV2 + + +```solidity +function getUserLoansV2(address user, uint256 start, uint256 count, uint256 loanType, bool isLender, bool unsafeOnly) + external + view + returns (LoanReturnDataV2[] memory loansDataV2); +``` + +### getLoan + + +```solidity +function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData); +``` + +### getLoanV2 + + +```solidity +function getLoanV2(bytes32 loanId) external view returns (LoanReturnDataV2 memory loanDataV2); +``` + +### getActiveLoans + + +```solidity +function getActiveLoans(uint256 start, uint256 count, bool unsafeOnly) + external + view + returns (LoanReturnData[] memory loansData); +``` + +### getActiveLoansV2 + + +```solidity +function getActiveLoansV2(uint256 start, uint256 count, bool unsafeOnly) + external + view + returns (LoanReturnDataV2[] memory loansDataV2); +``` + +### extendLoanDuration + + +```solidity +function extendLoanDuration(bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata) + external + returns (uint256 secondsExtended); +``` + +### reduceLoanDuration + + +```solidity +function reduceLoanDuration(bytes32 loanId, address receiver, uint256 withdrawAmount) + external + returns (uint256 secondsReduced); +``` + +### swapExternal + + +```solidity +function swapExternal( + address sourceToken, + address destToken, + address receiver, + address returnToSender, + uint256 sourceTokenAmount, + uint256 requiredDestTokenAmount, + uint256 minReturn, + bytes calldata swapData +) external returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); +``` + +### getSwapExpectedReturn + + +```solidity +function getSwapExpectedReturn(address sourceToken, address destToken, uint256 sourceTokenAmount) + external + view + returns (uint256); +``` + +### checkPriceDivergence + + +```solidity +function checkPriceDivergence(address sourceToken, address destToken, uint256 sourceTokenAmount, uint256 minReturn) + public + view; +``` + +### getUserNotFirstTradeFlag + + +```solidity +function getUserNotFirstTradeFlag(address user) external view returns (bool); +``` + +### setUserNotFirstTradeFlag + + +```solidity +function setUserNotFirstTradeFlag(address user) external; +``` + +### payTradingFeeToAffiliatesReferrer + + +```solidity +function payTradingFeeToAffiliatesReferrer( + address referrer, + address trader, + address token, + uint256 tradingFeeTokenBaseAmount +) external returns (uint256 affiliatesBonusSOVAmount, uint256 affiliatesBonusTokenAmount); +``` + +### setAffiliatesReferrer + + +```solidity +function setAffiliatesReferrer(address user, address referrer) external; +``` + +### getReferralsList + + +```solidity +function getReferralsList(address referrer) external view returns (address[] memory refList); +``` + +### getAffiliatesReferrerBalances + + +```solidity +function getAffiliatesReferrerBalances(address referrer) + external + view + returns (address[] memory referrerTokensList, uint256[] memory referrerTokensBalances); +``` + +### getAffiliatesReferrerTokensList + + +```solidity +function getAffiliatesReferrerTokensList(address referrer) external view returns (address[] memory tokensList); +``` + +### getAffiliatesReferrerTokenBalance + + +```solidity +function getAffiliatesReferrerTokenBalance(address referrer, address token) external view returns (uint256); +``` + +### withdrawAffiliatesReferrerTokenFees + + +```solidity +function withdrawAffiliatesReferrerTokenFees(address token, address receiver, uint256 amount) external; +``` + +### withdrawAllAffiliatesReferrerTokenFees + + +```solidity +function withdrawAllAffiliatesReferrerTokenFees(address receiver) external; +``` + +### getProtocolAddress + + +```solidity +function getProtocolAddress() external view returns (address); +``` + +### getSovTokenAddress + + +```solidity +function getSovTokenAddress() external view returns (address); +``` + +### getLockedSOVAddress + + +```solidity +function getLockedSOVAddress() external view returns (address); +``` + +### getFeeRebatePercent + + +```solidity +function getFeeRebatePercent() external view returns (uint256); +``` + +### getMinReferralsToPayout + + +```solidity +function getMinReferralsToPayout() external view returns (uint256); +``` + +### getAffiliatesUserReferrer + + +```solidity +function getAffiliatesUserReferrer(address user) external view returns (address referrer); +``` + +### getAffiliateRewardsHeld + + +```solidity +function getAffiliateRewardsHeld(address referrer) external view returns (uint256); +``` + +### getAffiliateTradingTokenFeePercent + + +```solidity +function getAffiliateTradingTokenFeePercent() external view returns (uint256 affiliateTradingTokenFeePercent); +``` + +### getAffiliatesTokenRewardsValueInRbtc + + +```solidity +function getAffiliatesTokenRewardsValueInRbtc(address referrer) external view returns (uint256 rbtcTotalAmount); +``` + +### getSwapExternalFeePercent + + +```solidity +function getSwapExternalFeePercent() external view returns (uint256 swapExternalFeePercent); +``` + +### setTradingRebateRewardsBasisPoint + + +```solidity +function setTradingRebateRewardsBasisPoint(uint256 newBasisPoint) external; +``` + +### getTradingRebateRewardsBasisPoint + + +```solidity +function getTradingRebateRewardsBasisPoint() external view returns (uint256); +``` + +### getDedicatedSOVRebate + + +```solidity +function getDedicatedSOVRebate() external view returns (uint256); +``` + +### setRolloverFlexFeePercent + + +```solidity +function setRolloverFlexFeePercent(uint256 newRolloverFlexFeePercent) external; +``` + +### getDefaultPathConversion + + +```solidity +function getDefaultPathConversion(address sourceTokenAddress, address destTokenAddress) + external + view + returns (IERC20[] memory); +``` + +### setDefaultPathConversion + + +```solidity +function setDefaultPathConversion(IERC20[] calldata defaultPath) external; +``` + +### removeDefaultPathConversion + + +```solidity +function removeDefaultPathConversion(address sourceTokenAddress, address destTokenAddress) external; +``` + +### checkCloseWithDepositIsTinyPosition + + +```solidity +function checkCloseWithDepositIsTinyPosition(bytes32 loanId, uint256 depositAmount) + external + view + returns (bool isTinyPosition, uint256 tinyPositionAmount); +``` + +### setAdmin + + +```solidity +function setAdmin(address newAdmin) external; +``` + +### getAdmin + + +```solidity +function getAdmin() external view returns (address); +``` + +### setPauser + + +```solidity +function setPauser(address newPauser) external; +``` + +### getPauser + + +```solidity +function getPauser() external view returns (address); +``` + +## Events +### PayInterestTransfer +Triggered whenever interest is paid to lender. + + +```solidity +event PayInterestTransfer(address indexed interestToken, address indexed lender, uint256 effectiveInterest); +``` + +## Structs +### LoanReturnData + +```solidity +struct LoanReturnData { + bytes32 loanId; + address loanToken; + address collateralToken; + uint256 principal; + uint256 collateral; + uint256 interestOwedPerDay; + uint256 interestDepositRemaining; + uint256 startRate; + uint256 startMargin; + uint256 maintenanceMargin; + uint256 currentMargin; + uint256 maxLoanTerm; + uint256 endTimestamp; + uint256 maxLiquidatable; + uint256 maxSeizable; +} +``` + +### LoanReturnDataV2 + +```solidity +struct LoanReturnDataV2 { + bytes32 loanId; + address loanToken; + address collateralToken; + address borrower; + uint256 principal; + uint256 collateral; + uint256 interestOwedPerDay; + uint256 interestDepositRemaining; + uint256 startRate; + uint256 startMargin; + uint256 maintenanceMargin; + uint256 currentMargin; + uint256 maxLoanTerm; + uint256 endTimestamp; + uint256 maxLiquidatable; + uint256 maxSeizable; + uint256 creationTimestamp; +} +``` + diff --git a/foundry/docs/src/contracts/interfaces/IWrbtc.sol/interface.IWrbtc.md b/foundry/docs/src/contracts/interfaces/IWrbtc.sol/interface.IWrbtc.md new file mode 100644 index 000000000..2bd8b4380 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IWrbtc.sol/interface.IWrbtc.md @@ -0,0 +1,22 @@ +# IWrbtc +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IWrbtc.sol) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### deposit + + +```solidity +function deposit() external payable; +``` + +### withdraw + + +```solidity +function withdraw(uint256 wad) external; +``` + diff --git a/foundry/docs/src/contracts/interfaces/IWrbtcERC20.sol/contract.IWrbtcERC20.md b/foundry/docs/src/contracts/interfaces/IWrbtcERC20.sol/contract.IWrbtcERC20.md new file mode 100644 index 000000000..68856e505 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/IWrbtcERC20.sol/contract.IWrbtcERC20.md @@ -0,0 +1,10 @@ +# IWrbtcERC20 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/interfaces/IWrbtcERC20.sol) + +**Inherits:** +[IWrbtc](/contracts/interfaces/IWrbtc.sol/interface.IWrbtc.md), [IERC20](/contracts/interfaces/IERC20.sol/contract.IERC20.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + diff --git a/foundry/docs/src/contracts/interfaces/README.md b/foundry/docs/src/contracts/interfaces/README.md new file mode 100644 index 000000000..1f61231c8 --- /dev/null +++ b/foundry/docs/src/contracts/interfaces/README.md @@ -0,0 +1,17 @@ + + +# Contents +- [IPot](IChai.sol/interface.IPot.md) +- [IChai](IChai.sol/contract.IChai.md) +- [IConverterAMM](IConverterAMM.sol/interface.IConverterAMM.md) +- [IERC20](IERC20.sol/contract.IERC20.md) +- [IERC20Mintable](IERC20Mintable.sol/contract.IERC20Mintable.md) +- [IERC777](IERC777.sol/interface.IERC777.md) +- [IERC777Recipient](IERC777Recipient.sol/interface.IERC777Recipient.md) +- [IERC777Sender](IERC777Sender.sol/interface.IERC777Sender.md) +- [ILoanPool](ILoanPool.sol/interface.ILoanPool.md) +- [ILoanTokenLogicProxy](ILoanTokenLogicProxy.sol/interface.ILoanTokenLogicProxy.md) +- [ILoanTokenModules](ILoanTokenModules.sol/interface.ILoanTokenModules.md) +- [ISovryn](ISovryn.sol/contract.ISovryn.md) +- [IWrbtc](IWrbtc.sol/interface.IWrbtc.md) +- [IWrbtcERC20](IWrbtcERC20.sol/contract.IWrbtcERC20.md) diff --git a/foundry/docs/src/contracts/locked/ILockedSOV.sol/interface.ILockedSOV.md b/foundry/docs/src/contracts/locked/ILockedSOV.sol/interface.ILockedSOV.md new file mode 100644 index 000000000..bb00fa664 --- /dev/null +++ b/foundry/docs/src/contracts/locked/ILockedSOV.sol/interface.ILockedSOV.md @@ -0,0 +1,88 @@ +# ILockedSOV +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/locked/ILockedSOV.sol) + +**Author:** +Franklin Richards - powerhousefrank@protonmail.com + +This interface is an incomplete yet useful for future migration of LockedSOV Contract. + +*Only use it if you know what you are doing.* + + +## Functions +### deposit + +Adds SOV to the user balance (Locked and Unlocked Balance based on `_basisPoint`). + + +```solidity +function deposit(address _userAddress, uint256 _sovAmount, uint256 _basisPoint) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_userAddress`|`address`|The user whose locked balance has to be updated with `_sovAmount`.| +|`_sovAmount`|`uint256`|The amount of SOV to be added to the locked and/or unlocked balance.| +|`_basisPoint`|`uint256`|The % (in Basis Point)which determines how much will be unlocked immediately.| + + +### depositSOV + +Adds SOV to the locked balance of a user. + + +```solidity +function depositSOV(address _userAddress, uint256 _sovAmount) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_userAddress`|`address`|The user whose locked balance has to be updated with _sovAmount.| +|`_sovAmount`|`uint256`|The amount of SOV to be added to the locked balance.| + + +### withdrawAndStakeTokensFrom + +Withdraws unlocked tokens and Stakes Locked tokens for a user who already have a vesting created. + + +```solidity +function withdrawAndStakeTokensFrom(address _userAddress) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_userAddress`|`address`|The address of user tokens will be withdrawn.| + + +### cliff + + +```solidity +function cliff() external view returns (uint256); +``` + +### duration + + +```solidity +function duration() external view returns (uint256); +``` + +### getLockedBalance + + +```solidity +function getLockedBalance(address _addr) external view returns (uint256 _balance); +``` + +### getUnlockedBalance + + +```solidity +function getUnlockedBalance(address _addr) external view returns (uint256 _balance); +``` + diff --git a/foundry/docs/src/contracts/locked/LockedSOV.sol/contract.LockedSOV.md b/foundry/docs/src/contracts/locked/LockedSOV.sol/contract.LockedSOV.md new file mode 100644 index 000000000..effa437cd --- /dev/null +++ b/foundry/docs/src/contracts/locked/LockedSOV.sol/contract.LockedSOV.md @@ -0,0 +1,635 @@ +# LockedSOV +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/locked/LockedSOV.sol) + +**Inherits:** +[ILockedSOV](/contracts/locked/ILockedSOV.sol/interface.ILockedSOV.md) + +**Author:** +Franklin Richards - powerhousefrank@protonmail.com + +This contract is used to receive reward from other contracts, Create Vesting and Stake Tokens. + + +## State Variables +### MAX_BASIS_POINT + +```solidity +uint256 public constant MAX_BASIS_POINT = 10000; +``` + + +### MAX_DURATION + +```solidity +uint256 public constant MAX_DURATION = 37; +``` + + +### migration +True if the migration to a new Locked SOV Contract has started. + + +```solidity +bool public migration; +``` + + +### cliff +The cliff is the time period after which the tokens begin to unlock. + + +```solidity +uint256 public cliff; +``` + + +### duration +The duration is the time period after all tokens will have been unlocked. + + +```solidity +uint256 public duration; +``` + + +### SOV +The SOV token contract. + + +```solidity +IERC20 public SOV; +``` + + +### vestingRegistry +The Vesting registry contract. + + +```solidity +VestingRegistry public vestingRegistry; +``` + + +### newLockedSOV +The New (Future) Locked SOV. + + +```solidity +ILockedSOV public newLockedSOV; +``` + + +### lockedBalances +The locked user balances. + + +```solidity +mapping(address => uint256) private lockedBalances; +``` + + +### unlockedBalances +The unlocked user balances. + + +```solidity +mapping(address => uint256) private unlockedBalances; +``` + + +### isAdmin +The contracts/wallets with admin power. + + +```solidity +mapping(address => bool) private isAdmin; +``` + + +## Functions +### onlyAdmin + + +```solidity +modifier onlyAdmin(); +``` + +### migrationAllowed + + +```solidity +modifier migrationAllowed(); +``` + +### constructor + +Setup the required parameters. + + +```solidity +constructor(address _SOV, address _vestingRegistry, uint256 _cliff, uint256 _duration, address[] memory _admins) + public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_SOV`|`address`|The SOV Token Address.| +|`_vestingRegistry`|`address`|The Vesting Registry Address.| +|`_cliff`|`uint256`|The time period after which the tokens begin to unlock.| +|`_duration`|`uint256`|The time period after all tokens will have been unlocked.| +|`_admins`|`address[]`|The list of Admins to be added.| + + +### addAdmin + +The function to add a new admin. + +*Only callable by an Admin.* + + +```solidity +function addAdmin(address _newAdmin) public onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newAdmin`|`address`|The address of the new admin.| + + +### removeAdmin + +The function to remove an admin. + +*Only callable by an Admin.* + + +```solidity +function removeAdmin(address _adminToRemove) public onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_adminToRemove`|`address`|The address of the admin which should be removed.| + + +### changeRegistryCliffAndDuration + +The function to update the Vesting Registry, Duration and Cliff. + +*IMPORTANT 1: You have to change Vesting Registry if you want to change Duration and/or Cliff. +IMPORTANT 2: `_cliff` and `_duration` is multiplied by 4 weeks in this function.* + + +```solidity +function changeRegistryCliffAndDuration(address _vestingRegistry, uint256 _cliff, uint256 _duration) + external + onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingRegistry`|`address`|The Vesting Registry Address.| +|`_cliff`|`uint256`|The time period after which the tokens begin to unlock.| +|`_duration`|`uint256`|The time period after all tokens will have been unlocked.| + + +### deposit + +If duration is also zero, then it is similar to Unlocked SOV. + +Adds SOV to the user balance (Locked and Unlocked Balance based on `_basisPoint`). + + +```solidity +function deposit(address _userAddress, uint256 _sovAmount, uint256 _basisPoint) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_userAddress`|`address`|The user whose locked balance has to be updated with `_sovAmount`.| +|`_sovAmount`|`uint256`|The amount of SOV to be added to the locked and/or unlocked balance.| +|`_basisPoint`|`uint256`|The % (in Basis Point)which determines how much will be unlocked immediately.| + + +### depositSOV + +Adds SOV to the locked balance of a user. + +*This is here because there are dependency with other contracts.* + + +```solidity +function depositSOV(address _userAddress, uint256 _sovAmount) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_userAddress`|`address`|The user whose locked balance has to be updated with _sovAmount.| +|`_sovAmount`|`uint256`|The amount of SOV to be added to the locked balance.| + + +### _deposit + + +```solidity +function _deposit(address _userAddress, uint256 _sovAmount, uint256 _basisPoint) private; +``` + +### withdraw + +A function to withdraw the unlocked balance. + + +```solidity +function withdraw(address _receiverAddress) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiverAddress`|`address`|If specified, the unlocked balance will go to this address, else to msg.sender.| + + +### _withdraw + + +```solidity +function _withdraw(address _sender, address _receiverAddress) private; +``` + +### createVestingAndStake + +Creates vesting if not already created and Stakes tokens for a user. + +*Only use this function if the `duration` is small.* + + +```solidity +function createVestingAndStake() public; +``` + +### _createVestingAndStake + + +```solidity +function _createVestingAndStake(address _sender) private; +``` + +### createVesting + +Creates vesting contract (if it hasn't been created yet) for the calling user. + + +```solidity +function createVesting() public returns (address _vestingAddress); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingAddress`|`address`|The New Vesting Contract Created.| + + +### stakeTokens + +Stakes tokens for a user who already have a vesting created. + +*The user should already have a vesting created, else this function will throw error.* + + +```solidity +function stakeTokens() public; +``` + +### withdrawAndStakeTokens + +Withdraws unlocked tokens and Stakes Locked tokens for a user who already have a vesting created. + + +```solidity +function withdrawAndStakeTokens(address _receiverAddress) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_receiverAddress`|`address`|If specified, the unlocked balance will go to this address, else to msg.sender.| + + +### withdrawAndStakeTokensFrom + +Withdraws unlocked tokens and Stakes Locked tokens for a user who already have a vesting created. + + +```solidity +function withdrawAndStakeTokensFrom(address _userAddress) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_userAddress`|`address`|The address of user tokens will be withdrawn.| + + +### startMigration + +Function to start the process of migration to new contract. + + +```solidity +function startMigration(address _newLockedSOV) external onlyAdmin; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newLockedSOV`|`address`|The new locked sov contract address.| + + +### transfer + +Function to transfer the locked balance from this contract to new LockedSOV Contract. + +*Address is not specified to discourage selling lockedSOV to other address.* + + +```solidity +function transfer() external migrationAllowed; +``` + +### _createVesting + +Creates a Vesting Contract for a user. + +*Does not do anything if Vesting Contract was already created.* + + +```solidity +function _createVesting(address _tokenOwner) internal returns (address _vestingAddress); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the vesting contract.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingAddress`|`address`|The Vesting Contract Address.| + + +### _getVesting + +Here zero is given in place of amount, as amount is not really used in `vestingRegistry.createVesting()`. + +Returns the Vesting Contract Address. + + +```solidity +function _getVesting(address _tokenOwner) internal view returns (address _vestingAddress); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_tokenOwner`|`address`|The owner of the vesting contract.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_vestingAddress`|`address`|The Vesting Contract Address.| + + +### _stakeTokens + +Stakes the tokens in a particular vesting contract. + + +```solidity +function _stakeTokens(address _sender, address _vesting) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|| +|`_vesting`|`address`|The Vesting Contract Address.| + + +### getLockedBalance + +The function to get the locked balance of a user. + + +```solidity +function getLockedBalance(address _addr) external view returns (uint256 _balance); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_addr`|`address`|The address of the user to check the locked balance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_balance`|`uint256`|The locked balance of the address `_addr`.| + + +### getUnlockedBalance + +The function to get the unlocked balance of a user. + + +```solidity +function getUnlockedBalance(address _addr) external view returns (uint256 _balance); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_addr`|`address`|The address of the user to check the unlocked balance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_balance`|`uint256`|The unlocked balance of the address `_addr`.| + + +### adminStatus + +The function to check is an address is admin or not. + + +```solidity +function adminStatus(address _addr) external view returns (bool _status); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_addr`|`address`|The address of the user to check the admin status.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_status`|`bool`|True if admin, False otherwise.| + + +## Events +### AdminAdded +Emitted when a new Admin is added to the admin list. + + +```solidity +event AdminAdded(address indexed _initiator, address indexed _newAdmin); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_newAdmin`|`address`|The address of the new admin.| + +### AdminRemoved +Emitted when an admin is removed from the admin list. + + +```solidity +event AdminRemoved(address indexed _initiator, address indexed _removedAdmin); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_removedAdmin`|`address`|The address of the removed admin.| + +### RegistryCliffAndDurationUpdated +Emitted when Vesting Registry, Duration and/or Cliff is updated. + + +```solidity +event RegistryCliffAndDurationUpdated( + address indexed _initiator, address indexed _vestingRegistry, uint256 _cliff, uint256 _duration +); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_vestingRegistry`|`address`|The Vesting Registry Contract.| +|`_cliff`|`uint256`|The time period after which the tokens begin to unlock.| +|`_duration`|`uint256`|The time period after all tokens will have been unlocked.| + +### Deposited +Emitted when a new deposit is made. + + +```solidity +event Deposited(address indexed _initiator, address indexed _userAddress, uint256 _sovAmount, uint256 _basisPoint); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_userAddress`|`address`|The user to whose un/locked balance a new deposit was made.| +|`_sovAmount`|`uint256`|The amount of SOV to be added to the un/locked balance.| +|`_basisPoint`|`uint256`|The % (in Basis Point) which determines how much will be unlocked immediately.| + +### Withdrawn +Emitted when a user withdraws the fund. + + +```solidity +event Withdrawn(address indexed _initiator, address indexed _userAddress, uint256 _sovAmount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_userAddress`|`address`|The user whose unlocked balance has to be withdrawn.| +|`_sovAmount`|`uint256`|The amount of SOV withdrawn from the unlocked balance.| + +### VestingCreated +Emitted when a user creates a vesting for himself. + + +```solidity +event VestingCreated(address indexed _initiator, address indexed _userAddress, address indexed _vesting); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_userAddress`|`address`|The user whose unlocked balance has to be withdrawn.| +|`_vesting`|`address`|The Vesting Contract.| + +### TokenStaked +Emitted when a user stakes tokens. + + +```solidity +event TokenStaked(address indexed _initiator, address indexed _vesting, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_vesting`|`address`|The Vesting Contract.| +|`_amount`|`uint256`|The amount of locked tokens staked by the user.| + +### MigrationStarted +Emitted when an admin initiates a migration to new Locked SOV Contract. + + +```solidity +event MigrationStarted(address indexed _initiator, address indexed _newLockedSOV); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_newLockedSOV`|`address`|The address of the new Locked SOV Contract.| + +### UserTransfered +Emitted when a user initiates the transfer to a new Locked SOV Contract. + + +```solidity +event UserTransfered(address indexed _initiator, uint256 _amount); +``` + +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initiator`|`address`|The address which initiated this event to be emitted.| +|`_amount`|`uint256`|The amount of locked tokens to transfer from this contract to the new one.| + diff --git a/foundry/docs/src/contracts/locked/README.md b/foundry/docs/src/contracts/locked/README.md new file mode 100644 index 000000000..3049543b7 --- /dev/null +++ b/foundry/docs/src/contracts/locked/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [ILockedSOV](ILockedSOV.sol/interface.ILockedSOV.md) +- [LockedSOV](LockedSOV.sol/contract.LockedSOV.md) diff --git a/foundry/docs/src/contracts/mixins/EnumerableAddressSet.sol/library.EnumerableAddressSet.md b/foundry/docs/src/contracts/mixins/EnumerableAddressSet.sol/library.EnumerableAddressSet.md new file mode 100644 index 000000000..92bdd6327 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/EnumerableAddressSet.sol/library.EnumerableAddressSet.md @@ -0,0 +1,114 @@ +# EnumerableAddressSet +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/EnumerableAddressSet.sol) + +*Based on Library for managing +https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive +types. +Sets have the following properties: +- Elements are added, removed, and checked for existence in constant time +(O(1)). +- Elements are enumerated in O(n). No guarantees are made on the ordering. +As of v2.5.0, only `address` sets are supported. +Include with `using EnumerableSet for EnumerableSet.AddressSet;`. +_Available since v2.5.0._* + + +## Functions +### add + +*Add a value to a set. O(1). +Returns false if the value was already in the set.* + + +```solidity +function add(AddressSet storage set, address value) internal returns (bool); +``` + +### remove + +*Removes a value from a set. O(1). +Returns false if the value was not present in the set.* + + +```solidity +function remove(AddressSet storage set, address value) internal returns (bool); +``` + +### contains + +*Returns true if the value is in the set. O(1).* + + +```solidity +function contains(AddressSet storage set, address value) internal view returns (bool); +``` + +### enumerate + +*Returns an array with all values in the set. O(N). +Note that there are no guarantees on the ordering of values inside the +array, and it may change when more values are added or removed. +WARNING: This function may run out of gas on large sets: use [length](/contracts/mixins/EnumerableAddressSet.sol/library.EnumerableAddressSet.md#length) and +{get} instead in these cases.* + + +```solidity +function enumerate(AddressSet storage set) internal view returns (address[] memory); +``` + +### enumerateChunk + +*Returns a chunk of array as recommended in enumerate() to avoid running of gas. +Note that there are no guarantees on the ordering of values inside the +array, and it may change when more values are added or removed. +WARNING: This function may run out of gas on large sets: use [length](/contracts/mixins/EnumerableAddressSet.sol/library.EnumerableAddressSet.md#length) and +{get} instead in these cases.* + + +```solidity +function enumerateChunk(AddressSet storage set, uint256 start, uint256 count) + internal + view + returns (address[] memory output); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`AddressSet`|| +|`start`|`uint256`|start index of chunk| +|`count`|`uint256`|num of element to return; if count == 0 then returns all the elements from the @param start| + + +### length + +*Returns the number of elements on the set. O(1).* + + +```solidity +function length(AddressSet storage set) internal view returns (uint256); +``` + +### get + +*Returns the element stored at position `index` in the set. O(1). +Note that there are no guarantees on the ordering of values inside the +array, and it may change when more values are added or removed. +Requirements: +- `index` must be strictly less than [length](/contracts/mixins/EnumerableAddressSet.sol/library.EnumerableAddressSet.md#length).* + + +```solidity +function get(AddressSet storage set, uint256 index) internal view returns (address); +``` + +## Structs +### AddressSet + +```solidity +struct AddressSet { + mapping(address => uint256) index; + address[] values; +} +``` + diff --git a/foundry/docs/src/contracts/mixins/EnumerableBytes32Set.sol/library.EnumerableBytes32Set.md b/foundry/docs/src/contracts/mixins/EnumerableBytes32Set.sol/library.EnumerableBytes32Set.md new file mode 100644 index 000000000..84efd46f1 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/EnumerableBytes32Set.sol/library.EnumerableBytes32Set.md @@ -0,0 +1,229 @@ +# EnumerableBytes32Set +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/EnumerableBytes32Set.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +Sets have the following properties: +- Elements are added, removed, and checked for existence in constant time +(O(1)). +- Elements are enumerated in O(n). No guarantees are made on the ordering. +Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. + + +## Functions +### addAddress + +Add an address value to a set. O(1). + + +```solidity +function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| +|`addrvalue`|`address`|The address to add.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|False if the value was already in the set.| + + +### addBytes32 + +Add a value to a set. O(1). + + +```solidity +function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| +|`value`|`bytes32`|The new value to add.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|False if the value was already in the set.| + + +### removeAddress + +Remove an address value from a set. O(1). + + +```solidity +function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| +|`addrvalue`|`address`|The address to remove.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|False if the address was not present in the set.| + + +### removeBytes32 + +Remove a value from a set. O(1). + + +```solidity +function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| +|`value`|`bytes32`|The value to remove.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|False if the value was not present in the set.| + + +### contains + +If the element we're deleting is the last one, +we can just remove it without doing a swap. +Move the last value to the index where the deleted value is. +Update the index for the moved value. +Delete the index entry for the deleted value. +Delete the old entry for the moved value. + +Find out whether a value exists in the set. + + +```solidity +function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| +|`value`|`bytes32`|The value to find.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|True if the value is in the set. O(1).| + + +### containsAddress + +*Returns true if the value is in the set. O(1).* + + +```solidity +function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool); +``` + +### enumerate + +Get all set values. + +*Note that there are no guarantees on the ordering of values inside the +array, and it may change when more values are added or removed. +WARNING: This function may run out of gas on large sets: use [length](/contracts/mixins/EnumerableBytes32Set.sol/library.EnumerableBytes32Set.md#length) and +{get} instead in these cases.* + + +```solidity +function enumerate(Bytes32Set storage set, uint256 start, uint256 count) + internal + view + returns (bytes32[] memory output); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| +|`start`|`uint256`|The offset of the returning set.| +|`count`|`uint256`|The limit of number of values to return.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`output`|`bytes32[]`|An array with all values in the set. O(N).| + + +### length + +Get the legth of the set. + + +```solidity +function length(Bytes32Set storage set) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|the number of elements on the set. O(1).| + + +### get + +Get an item from the set by its index. + +*Note that there are no guarantees on the ordering of values inside the +array, and it may change when more values are added or removed. +Requirements: +- `index` must be strictly less than [length](/contracts/mixins/EnumerableBytes32Set.sol/library.EnumerableBytes32Set.md#length).* + + +```solidity +function get(Bytes32Set storage set, uint256 index) internal view returns (bytes32); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes32Set`|The set of values.| +|`index`|`uint256`|The index of the value to return.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes32`|the element stored at position `index` in the set. O(1).| + + +## Structs +### Bytes32Set + +```solidity +struct Bytes32Set { + mapping(bytes32 => uint256) index; + bytes32[] values; +} +``` + diff --git a/foundry/docs/src/contracts/mixins/EnumerableBytes4Set.sol/library.EnumerableBytes4Set.md b/foundry/docs/src/contracts/mixins/EnumerableBytes4Set.sol/library.EnumerableBytes4Set.md new file mode 100644 index 000000000..af549df17 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/EnumerableBytes4Set.sol/library.EnumerableBytes4Set.md @@ -0,0 +1,176 @@ +# EnumerableBytes4Set +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/EnumerableBytes4Set.sol) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +Sets have the following properties: +- Elements are added, removed, and checked for existence in constant time +(O(1)). +- Elements are enumerated in O(n). No guarantees are made on the ordering. +Include with `using EnumerableBytes4Set for EnumerableBytes4Set.Bytes4Set;`. + + +## Functions +### addBytes4 + +Add a value to a set. O(1). + + +```solidity +function addBytes4(Bytes4Set storage set, bytes4 value) internal returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes4Set`|The set of values.| +|`value`|`bytes4`|The new value to add.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|False if the value was already in the set.| + + +### removeBytes4 + +Remove a value from a set. O(1). + + +```solidity +function removeBytes4(Bytes4Set storage set, bytes4 value) internal returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes4Set`|The set of values.| +|`value`|`bytes4`|The value to remove.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|False if the value was not present in the set.| + + +### contains + +If the element we're deleting is the last one, +we can just remove it without doing a swap. +Move the last value to the index where the deleted value is. +Update the index for the moved value. +Delete the index entry for the deleted value. +Delete the old entry for the moved value. + +Find out whether a value exists in the set. + + +```solidity +function contains(Bytes4Set storage set, bytes4 value) internal view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes4Set`|The set of values.| +|`value`|`bytes4`|The value to find.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|True if the value is in the set. O(1).| + + +### enumerate + +Get all set values. + +*Note that there are no guarantees on the ordering of values inside the +array, and it may change when more values are added or removed. +WARNING: This function may run out of gas on large sets: use [length](/contracts/mixins/EnumerableBytes4Set.sol/library.EnumerableBytes4Set.md#length) and +{get} instead in these cases.* + + +```solidity +function enumerate(Bytes4Set storage set, uint256 start, uint256 count) + internal + view + returns (bytes4[] memory output); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes4Set`|The set of values.| +|`start`|`uint256`|The offset of the returning set.| +|`count`|`uint256`|The limit of number of values to return.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`output`|`bytes4[]`|An array with all values in the set. O(N).| + + +### length + +Get the legth of the set. + + +```solidity +function length(Bytes4Set storage set) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes4Set`|The set of values.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|the number of elements on the set. O(1).| + + +### get + +Get an item from the set by its index. + +*Note that there are no guarantees on the ordering of values inside the +array, and it may change when more values are added or removed. +Requirements: +- `index` must be strictly less than [length](/contracts/mixins/EnumerableBytes4Set.sol/library.EnumerableBytes4Set.md#length).* + + +```solidity +function get(Bytes4Set storage set, uint256 index) internal view returns (bytes4); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`set`|`Bytes4Set`|The set of values.| +|`index`|`uint256`|The index of the value to return.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes4`|the element stored at position `index` in the set. O(1).| + + +## Structs +### Bytes4Set + +```solidity +struct Bytes4Set { + mapping(bytes4 => uint256) index; + bytes4[] values; +} +``` + diff --git a/foundry/docs/src/contracts/mixins/FeesHelper.sol/contract.FeesHelper.md b/foundry/docs/src/contracts/mixins/FeesHelper.sol/contract.FeesHelper.md new file mode 100644 index 000000000..69039d862 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/FeesHelper.sol/contract.FeesHelper.md @@ -0,0 +1,204 @@ +# FeesHelper +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/FeesHelper.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md), [FeesEvents](/contracts/events/FeesEvents.sol/contract.FeesEvents.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### _getTradingFee + +Calculate trading fee. + + +```solidity +function _getTradingFee(uint256 feeTokenAmount) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`feeTokenAmount`|`uint256`|The amount of tokens to trade.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The fee of the trade.| + + +### _getSwapExternalFee + +Calculate swap external fee. + + +```solidity +function _getSwapExternalFee(uint256 feeTokenAmount) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`feeTokenAmount`|`uint256`|The amount of token to swap.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The fee of the swap.| + + +### _getBorrowingFee + +Calculate the loan origination fee. + + +```solidity +function _getBorrowingFee(uint256 feeTokenAmount) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`feeTokenAmount`|`uint256`|The amount of tokens to borrow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The fee of the loan.| + + +### _payTradingFeeToAffiliate + +Settle the trading fee and pay the token reward to the affiliates referrer. + + +```solidity +function _payTradingFeeToAffiliate(address referrer, address trader, address feeToken, uint256 tradingFee) + internal + returns (uint256 affiliatesBonusSOVAmount, uint256 affiliatesBonusTokenAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The affiliate referrer address to send the reward to.| +|`trader`|`address`|The account that performs this trade.| +|`feeToken`|`address`|The address of the token in which the trading fee is paid.| +|`tradingFee`|`uint256`|The amount of tokens accrued as fees on the trading.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`affiliatesBonusSOVAmount`|`uint256`|the total SOV amount that is distributed to the referrer| +|`affiliatesBonusTokenAmount`|`uint256`|the total Token Base on the trading fee pairs that is distributed to the referrer| + + +### _payTradingFee + +Settle the trading fee and pay the token reward to the user. + + +```solidity +function _payTradingFee(address user, bytes32 loanId, address feeToken, address feeTokenPair, uint256 tradingFee) + internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address to send the reward to.| +|`loanId`|`bytes32`|The Id of the associated loan - used for logging only.| +|`feeToken`|`address`|The address of the token in which the trading fee is paid.| +|`feeTokenPair`|`address`|| +|`tradingFee`|`uint256`|The amount of tokens accrued as fees on the trading.| + + +### _payBorrowingFee + +Trading fee paid to protocol. +Increase the storage variable keeping track of the accumulated fees. +Pay the token reward to the user. + +Settle the borrowing fee and pay the token reward to the user. + + +```solidity +function _payBorrowingFee(address user, bytes32 loanId, address feeToken, address feeTokenPair, uint256 borrowingFee) + internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address to send the reward to.| +|`loanId`|`bytes32`|The Id of the associated loan - used for logging only.| +|`feeToken`|`address`|The address of the token in which the borrowig fee is paid.| +|`feeTokenPair`|`address`|| +|`borrowingFee`|`uint256`|The height of the fee.| + + +### _payLendingFee + +Increase the storage variable keeping track of the accumulated fees. +Pay the token reward to the user. + +Settle the lending fee (based on the interest). Pay no token reward to the user. + + +```solidity +function _payLendingFee(address user, address feeToken, uint256 lendingFee) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address to send the reward to.| +|`feeToken`|`address`|The address of the token in which the lending fee is paid.| +|`lendingFee`|`uint256`|The height of the fee.| + + +### _settleFeeRewardForInterestExpense + +Increase the storage variable keeping track of the accumulated fees. +Settle and pay borrowers based on the fees generated by their interest payments. + + +```solidity +function _settleFeeRewardForInterestExpense( + LoanInterest storage loanInterestLocal, + bytes32 loanId, + address feeToken, + address feeTokenPair, + address user, + uint256 interestTime +) internal; +``` + +### _payFeeReward + +This represents the fee generated by a borrower's interest payment. + +Pay the potocolToken reward to user. The reward is worth 50% of the trading/borrowing fee. + + +```solidity +function _payFeeReward(address user, bytes32 loanId, address feeToken, address feeTokenPair, uint256 feeAmount) + internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address to send the reward to.| +|`loanId`|`bytes32`|The Id of the associeated loan - used for logging only.| +|`feeToken`|`address`|The address of the token in which the trading/borrowing fee was paid.| +|`feeTokenPair`|`address`|| +|`feeAmount`|`uint256`|The height of the fee.| + + diff --git a/foundry/docs/src/contracts/mixins/InterestUser.sol/contract.InterestUser.md b/foundry/docs/src/contracts/mixins/InterestUser.sol/contract.InterestUser.md new file mode 100644 index 000000000..fdfca6194 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/InterestUser.sol/contract.InterestUser.md @@ -0,0 +1,55 @@ +# InterestUser +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/InterestUser.sol) + +**Inherits:** +[VaultController](/contracts/mixins/VaultController.sol/contract.VaultController.md), [FeesHelper](/contracts/mixins/FeesHelper.sol/contract.FeesHelper.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### _payInterest + +Internal function to pay interest of a loan. + +*Calls _payInterestTransfer internal function to transfer tokens.* + + +```solidity +function _payInterest(address lender, address interestToken) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lender`|`address`|The account address of the lender.| +|`interestToken`|`address`|The token address to pay interest with.| + + +### _payInterestTransfer + +Internal function to transfer tokens for the interest of a loan. + + +```solidity +function _payInterestTransfer(address lender, address interestToken, uint256 interestOwedNow) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lender`|`address`|The account address of the lender.| +|`interestToken`|`address`|The token address to pay interest with.| +|`interestOwedNow`|`uint256`|The amount of interest to pay.| + + +## Events +### PayInterestTransfer +Triggered whenever interest is paid to lender. + + +```solidity +event PayInterestTransfer(address indexed interestToken, address indexed lender, uint256 effectiveInterest); +``` + diff --git a/foundry/docs/src/contracts/mixins/LiquidationHelper.sol/contract.LiquidationHelper.md b/foundry/docs/src/contracts/mixins/LiquidationHelper.sol/contract.LiquidationHelper.md new file mode 100644 index 000000000..bc65ad2f3 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/LiquidationHelper.sol/contract.LiquidationHelper.md @@ -0,0 +1,49 @@ +# LiquidationHelper +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/LiquidationHelper.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized margin +trading and lending https://bzx.network similar to the dYdX protocol. +This contract computes the liquidation amount. + + +## Functions +### _getLiquidationAmounts + +Compute how much needs to be liquidated in order to restore the +desired margin (maintenance + 5%). + + +```solidity +function _getLiquidationAmounts( + uint256 principal, + uint256 collateral, + uint256 currentMargin, + uint256 maintenanceMargin, + uint256 collateralToLoanRate +) internal view returns (uint256 maxLiquidatable, uint256 maxSeizable, uint256 incentivePercent); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`principal`|`uint256`|The total borrowed amount (in loan tokens).| +|`collateral`|`uint256`|The collateral (in collateral tokens).| +|`currentMargin`|`uint256`|The current margin.| +|`maintenanceMargin`|`uint256`|The maintenance (minimum) margin.| +|`collateralToLoanRate`|`uint256`|The exchange rate from collateral to loan tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`maxLiquidatable`|`uint256`|The collateral you can get liquidating.| +|`maxSeizable`|`uint256`|The loan you available for liquidation.| +|`incentivePercent`|`uint256`|The discount on collateral.| + + diff --git a/foundry/docs/src/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md b/foundry/docs/src/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md new file mode 100644 index 000000000..a4f8d52de --- /dev/null +++ b/foundry/docs/src/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md @@ -0,0 +1,15 @@ +# ModuleCommonFunctionalities +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/ModuleCommonFunctionalities.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + + +## Functions +### whenNotPaused + + +```solidity +modifier whenNotPaused(); +``` + diff --git a/foundry/docs/src/contracts/mixins/ProtocolTokenUser.sol/contract.ProtocolTokenUser.md b/foundry/docs/src/contracts/mixins/ProtocolTokenUser.sol/contract.ProtocolTokenUser.md new file mode 100644 index 000000000..60cc5ffb9 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/ProtocolTokenUser.sol/contract.ProtocolTokenUser.md @@ -0,0 +1,38 @@ +# ProtocolTokenUser +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/ProtocolTokenUser.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized margin +trading and lending https://bzx.network similar to the dYdX protocol. +This contract implements functionality to withdraw protocol tokens. + + +## Functions +### _withdrawProtocolToken + +Internal function to withdraw an amount of protocol tokens from this contract. + + +```solidity +function _withdrawProtocolToken(address receiver, uint256 amount) internal returns (address, bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The address of the recipient.| +|`amount`|`uint256`|The amount of tokens to withdraw.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The protocol token address.| +|``|`bool`|Withdrawal success (true/false).| + + diff --git a/foundry/docs/src/contracts/mixins/README.md b/foundry/docs/src/contracts/mixins/README.md new file mode 100644 index 000000000..d1db08f19 --- /dev/null +++ b/foundry/docs/src/contracts/mixins/README.md @@ -0,0 +1,13 @@ + + +# Contents +- [EnumerableAddressSet](EnumerableAddressSet.sol/library.EnumerableAddressSet.md) +- [EnumerableBytes32Set](EnumerableBytes32Set.sol/library.EnumerableBytes32Set.md) +- [EnumerableBytes4Set](EnumerableBytes4Set.sol/library.EnumerableBytes4Set.md) +- [FeesHelper](FeesHelper.sol/contract.FeesHelper.md) +- [InterestUser](InterestUser.sol/contract.InterestUser.md) +- [LiquidationHelper](LiquidationHelper.sol/contract.LiquidationHelper.md) +- [ModuleCommonFunctionalities](ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) +- [ProtocolTokenUser](ProtocolTokenUser.sol/contract.ProtocolTokenUser.md) +- [RewardHelper](RewardHelper.sol/contract.RewardHelper.md) +- [VaultController](VaultController.sol/contract.VaultController.md) diff --git a/foundry/docs/src/contracts/mixins/RewardHelper.sol/contract.RewardHelper.md b/foundry/docs/src/contracts/mixins/RewardHelper.sol/contract.RewardHelper.md new file mode 100644 index 000000000..11465ba2c --- /dev/null +++ b/foundry/docs/src/contracts/mixins/RewardHelper.sol/contract.RewardHelper.md @@ -0,0 +1,40 @@ +# RewardHelper +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/RewardHelper.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + +This contract calculates the reward for rollover transactions. +A rollover is a renewal of a deposit. Instead of liquidating a deposit +on maturity, you can roll it over into a new deposit. The outstanding +principal of the old deposit is rolled over with or without the interest +outstanding on it. + + +## Functions +### _getRolloverReward + +Calculate the reward of a rollover transaction. + + +```solidity +function _getRolloverReward(address collateralToken, address loanToken, uint256 positionSize) + internal + view + returns (uint256 reward); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`collateralToken`|`address`|The address of the collateral token.| +|`loanToken`|`address`|The address of the loan token.| +|`positionSize`|`uint256`|The amount of value of the position.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`reward`|`uint256`|The base fee + the flex fee.| + + diff --git a/foundry/docs/src/contracts/mixins/VaultController.sol/contract.VaultController.md b/foundry/docs/src/contracts/mixins/VaultController.sol/contract.VaultController.md new file mode 100644 index 000000000..bd528cd2a --- /dev/null +++ b/foundry/docs/src/contracts/mixins/VaultController.sol/contract.VaultController.md @@ -0,0 +1,130 @@ +# VaultController +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/mixins/VaultController.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + +Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized margin +trading and lending https://bzx.network similar to the dYdX protocol. +This contract implements functionality to deposit and withdraw wrBTC and +other tokens from the vault. + + +## Functions +### vaultEtherDeposit + +Deposit wrBTC into the vault. + + +```solidity +function vaultEtherDeposit(address from, uint256 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`from`|`address`|The address of the account paying the deposit.| +|`value`|`uint256`|The amount of wrBTC tokens to transfer.| + + +### vaultEtherWithdraw + +Withdraw wrBTC from the vault. + + +```solidity +function vaultEtherWithdraw(address to, uint256 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`to`|`address`|The address of the recipient.| +|`value`|`uint256`|The amount of wrBTC tokens to transfer.| + + +### vaultDeposit + +Deposit tokens into the vault. + + +```solidity +function vaultDeposit(address token, address from, uint256 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token instance.| +|`from`|`address`|The address of the account paying the deposit.| +|`value`|`uint256`|The amount of tokens to transfer.| + + +### vaultWithdraw + +Withdraw tokens from the vault. + + +```solidity +function vaultWithdraw(address token, address to, uint256 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token instance.| +|`to`|`address`|The address of the recipient.| +|`value`|`uint256`|The amount of tokens to transfer.| + + +### vaultTransfer + +Transfer tokens from an account into another one. + + +```solidity +function vaultTransfer(address token, address from, address to, uint256 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token instance.| +|`from`|`address`|The address of the account paying.| +|`to`|`address`|The address of the recipient.| +|`value`|`uint256`|The amount of tokens to transfer.| + + +### vaultApprove + +Approve an allowance of tokens to be spent by an account. + + +```solidity +function vaultApprove(address token, address to, uint256 value) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token instance.| +|`to`|`address`|The address of the spender.| +|`value`|`uint256`|The amount of tokens to allow.| + + +## Events +### VaultDeposit + +```solidity +event VaultDeposit(address indexed asset, address indexed from, uint256 amount); +``` + +### VaultWithdraw + +```solidity +event VaultWithdraw(address indexed asset, address indexed to, uint256 amount); +``` + diff --git a/foundry/docs/src/contracts/modules/Affiliates.sol/contract.Affiliates.md b/foundry/docs/src/contracts/modules/Affiliates.sol/contract.Affiliates.md new file mode 100644 index 000000000..5f2d68de7 --- /dev/null +++ b/foundry/docs/src/contracts/modules/Affiliates.sol/contract.Affiliates.md @@ -0,0 +1,506 @@ +# Affiliates +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/Affiliates.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md), [AffiliatesEvents](/contracts/events/AffiliatesEvents.sol/contract.AffiliatesEvents.md), [ModuleCommonFunctionalities](/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + +Copyright 2017-2020, Sovryn, All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +Track referrals and reward referrers (affiliates) with tokens. +In-detail specifications are found at https://wiki.sovryn.app/en/community/Affiliates + +*Module: Affiliates upgradable +Storage: from State, functions called from Protocol by delegatecall* + + +## Functions +### constructor + +Void constructor. + + +```solidity +constructor() public; +``` + +### function + +Avoid calls to this contract except for those explicitly declared. + + +```solidity +function() external; +``` + +### initialize + +Set delegate callable functions by proxy contract. + +*This contract is designed as a module, this way logic can be +expanded and upgraded w/o losing storage that is kept in the protocol (State.sol) +initialize() is used to register in the proxy external (module) functions +to be called via the proxy.* + + +```solidity +function initialize(address target) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The address of a new logic implementation.| + + +### onlyCallableByLoanPools + +Function modifier to avoid any other calls not coming from loan pools. + + +```solidity +modifier onlyCallableByLoanPools(); +``` + +### onlyCallableInternal + +Function modifier to avoid any other calls not coming from within protocol functions. + + +```solidity +modifier onlyCallableInternal(); +``` + +### setAffiliatesReferrer + +Loan pool calls this function to tell affiliates +a user coming from a referrer is trading and should be registered if not yet. +Taking into account some user status flags may lead to the user and referrer +become added or not to the affiliates record. + + +```solidity +function setAffiliatesReferrer(address user, address referrer) external onlyCallableByLoanPools whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address of the user that is trading on loan pools.| +|`referrer`|`address`|The address of the referrer the user is coming from.| + + +### getReferralsList + +Getter to query the referrals coming from a referrer. + + +```solidity +function getReferralsList(address referrer) external view returns (address[] memory refList); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The address of a given referrer.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`refList`|`address[]`|The referralsList mapping value by referrer.| + + +### getUserNotFirstTradeFlag + +Getter to query the not-first-trade flag of a user. + + +```solidity +function getUserNotFirstTradeFlag(address user) public view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address of a given user.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|The userNotFirstTradeFlag mapping value by user.| + + +### setUserNotFirstTradeFlag + +Setter to toggle on the not-first-trade flag of a user. + + +```solidity +function setUserNotFirstTradeFlag(address user) external onlyCallableByLoanPools whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address of a given user.| + + +### _getAffiliatesTradingFeePercentForSOV + +Internal getter to query the fee share for affiliate program. + +*It returns a value defined at protocol storage (State.sol)* + + +```solidity +function _getAffiliatesTradingFeePercentForSOV() internal view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The percentage of fee share w/ 18 decimals.| + + +### _getReferrerTradingFeeForToken + +Internal to calculate the affiliates trading token fee amount. +Affiliates program has 2 kind of rewards: +1. x% based on the fee of the token that is traded (in form of the token itself). +2. x% based on the fee of the token that is traded (in form of SOV). +This _getReferrerTradingFeeForToken calculates the first one +by applying a custom percentage multiplier. + + +```solidity +function _getReferrerTradingFeeForToken(uint256 feeTokenAmount) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`feeTokenAmount`|`uint256`|The trading token fee amount.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The affiliates share of the trading token fee amount.| + + +### getAffiliateTradingTokenFeePercent + +Getter to query the fee share of trading token fee for affiliate program. + +*It returns a value defined at protocol storage (State.sol)* + + +```solidity +function getAffiliateTradingTokenFeePercent() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The percentage of fee share w/ 18 decimals.| + + +### getMinReferralsToPayout + +Getter to query referral threshold for paying out to the referrer. + +*It returns a value defined at protocol storage (State.sol)* + + +```solidity +function getMinReferralsToPayout() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The minimum number of referrals set by Protocol.| + + +### _getSovBonusAmount + +Get the sovToken reward of a trade. + +*The reward is worth x% of the trading fee.* + + +```solidity +function _getSovBonusAmount(address feeToken, uint256 feeAmount) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`feeToken`|`address`|The address of the token in which the trading/borrowing fee was paid.| +|`feeAmount`|`uint256`|The height of the fee.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The reward amount.| + + +### payTradingFeeToAffiliatesReferrer + +Protocol calls this function to pay the affiliates rewards to a user (referrer). + +*Calculate the reward amount, querying the price feed. +dest token = SOV* + +*Affiliates program has 2 kind of rewards: +1. x% based on the fee of the token that is traded (in form of the token itself). +2. x% based on the fee of the token that is traded (in form of SOV). +Both are paid in this function.* + +*Actually they are not paid, but just holded by protocol until user claims them by +actively calling withdrawAffiliatesReferrerTokenFees() function, +and/or when unvesting lockedSOV.* + +*To be precise, what this function does is updating the registers of the rewards +for the referrer including the assignment of the SOV tokens as rewards to the +referrer's vesting contract.* + + +```solidity +function payTradingFeeToAffiliatesReferrer( + address referrer, + address trader, + address token, + uint256 tradingFeeTokenBaseAmount +) + external + onlyCallableInternal + whenNotPaused + returns (uint256 referrerBonusSovAmount, uint256 referrerBonusTokenAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The address of the referrer.| +|`trader`|`address`|The address of the trader.| +|`token`|`address`|The address of the token in which the trading/borrowing fee was paid.| +|`tradingFeeTokenBaseAmount`|`uint256`|Total trading fee amount, the base for calculating referrer's fees.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`referrerBonusSovAmount`|`uint256`|The amount of SOV tokens paid to the referrer (through a vesting contract, lockedSOV).| +|`referrerBonusTokenAmount`|`uint256`|The amount of trading tokens paid directly to the referrer.| + + +### withdrawAffiliatesReferrerTokenFees + +Process token fee rewards first. +Then process SOV rewards. +If referrals less than minimum, temp the rewards SOV to the storage +If referrals >= minimum, directly send all of the remain rewards to locked sov +Call depositSOV() in LockedSov contract +Set the affiliaterewardsheld = 0 + +Referrer calls this function to receive its reward in a given token. +It will send the other (non-SOV) reward tokens from trading protocol fees, +to the referrer’s wallet. + +*Rewards are held by protocol in different tokens coming from trading fees. +Referrer has to claim them one by one for every token with accumulated balance.* + + +```solidity +function withdrawAffiliatesReferrerTokenFees(address token, address receiver, uint256 amount) public whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token to withdraw.| +|`receiver`|`address`|The address of the withdrawal beneficiary.| +|`amount`|`uint256`|The amount of tokens to claim. If greater than balance, just sends balance.| + + +### withdrawAllAffiliatesReferrerTokenFees + +Withdraw to msg.sender all token fees for a referrer. + +*It's done by looping through its available tokens.* + + +```solidity +function withdrawAllAffiliatesReferrerTokenFees(address receiver) external whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The address of the withdrawal beneficiary.| + + +### _removeAffiliatesReferrerToken + +Internal function to delete a referrer's token balance. + + +```solidity +function _removeAffiliatesReferrerToken(address referrer, address token) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The address of the referrer.| +|`token`|`address`|The address of the token specifying the balance to remove.| + + +### getAffiliatesReferrerBalances + +Get all token balances of a referrer. + + +```solidity +function getAffiliatesReferrerBalances(address referrer) + public + view + returns (address[] memory referrerTokensList, uint256[] memory referrerTokensBalances); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The address of the referrer.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`referrerTokensList`|`address[]`|The array of available tokens (keys).| +|`referrerTokensBalances`|`uint256[]`|The array of token balances (values).| + + +### getAffiliatesTokenRewardsValueInRbtc + +*Get all token rewards estimation value in rbtc.* + + +```solidity +function getAffiliatesTokenRewardsValueInRbtc(address referrer) external view returns (uint256 rbtcTotalAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|Address of referrer.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`rbtcTotalAmount`|`uint256`|The value estimation in rbtc.| + + +### getAffiliatesReferrerTokensList + +Get all available tokens at the affiliates program for a given referrer. + + +```solidity +function getAffiliatesReferrerTokensList(address referrer) public view returns (address[] memory tokensList); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The address of a given referrer.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`tokensList`|`address[]`|The list of available tokens.| + + +### getAffiliatesReferrerTokenBalance + +Getter to query the affiliate balance for a given referrer and token. + + +```solidity +function getAffiliatesReferrerTokenBalance(address referrer, address token) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The address of the referrer.| +|`token`|`address`|The address of the token to get balance for.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The affiliatesReferrerBalances mapping value by referrer and token keys.| + + +### getAffiliatesUserReferrer + +Getter to query the address of referrer for a given user. + + +```solidity +function getAffiliatesUserReferrer(address user) public view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The address of the user.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The address on affiliatesUserReferrer mapping value by user key.| + + +### getAffiliateRewardsHeld + +Getter to query the reward amount held for a given referrer. + + +```solidity +function getAffiliateRewardsHeld(address referrer) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`referrer`|`address`|The address of the referrer.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The affiliateRewardsHeld mapping value by referrer key.| + + +## Structs +### SetAffiliatesReferrerResult +Data structure comprised of 3 flags to compute the result of setting a referrer. + + +```solidity +struct SetAffiliatesReferrerResult { + bool success; + bool alreadySet; + bool userNotFirstTradeFlag; +} +``` + diff --git a/foundry/docs/src/contracts/modules/LoanClosingsLiquidation.sol/contract.LoanClosingsLiquidation.md b/foundry/docs/src/contracts/modules/LoanClosingsLiquidation.sol/contract.LoanClosingsLiquidation.md new file mode 100644 index 000000000..5aa480861 --- /dev/null +++ b/foundry/docs/src/contracts/modules/LoanClosingsLiquidation.sol/contract.LoanClosingsLiquidation.md @@ -0,0 +1,148 @@ +# LoanClosingsLiquidation +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/LoanClosingsLiquidation.sol) + +**Inherits:** +[LoanClosingsShared](/contracts/modules/LoanClosingsShared.sol/contract.LoanClosingsShared.md), [LiquidationHelper](/contracts/mixins/LiquidationHelper.sol/contract.LiquidationHelper.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +Ways to close a loan: liquidation. Margin trade +positions are always closed with a swap. +Loans are liquidated if the position goes below margin maintenance. + + +## State Variables +### MONTH + +```solidity +uint256 internal constant MONTH = 365 days / 12; +``` + + +## Functions +### constructor + + +```solidity +constructor() public; +``` + +### function + + +```solidity +function() external; +``` + +### initialize + + +```solidity +function initialize(address target) external onlyOwner; +``` + +### liquidate + +Liquidate an unhealty loan. + +*Public wrapper for _liquidate internal function. +The caller needs to approve the closeAmount prior to calling. Will +not liquidate more than is needed to restore the desired margin +(maintenance +5%). +Whenever the current margin of a loan falls below maintenance margin, +it needs to be liquidated. Anybody can initiate a liquidation and buy +the collateral tokens at a discounted rate (5%).* + + +```solidity +function liquidate(bytes32 loanId, address receiver, uint256 closeAmount) + external + payable + nonReentrant + globallyNonReentrant + iTokenSupplyUnchanged(loanId) + whenNotPaused + returns (uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan to liquidate. loanId is the ID of the loan, which is created on loan opening. It can be obtained either by parsing the Trade event or by reading the open loans from the contract by calling getActiveLoans or getUserLoans.| +|`receiver`|`address`|The receiver of the seized amount.| +|`closeAmount`|`uint256`|The amount to close in loanTokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanCloseAmount`|`uint256`|The amount of the collateral token of the loan.| +|`seizedAmount`|`uint256`|The seized amount in the collateral token.| +|`seizedToken`|`address`|The loan token address.| + + +### _liquidate + +Internal function for liquidating an unhealthy loan. +The caller needs to approve the closeAmount prior to calling. Will +not liquidate more than is needed to restore the desired margin +(maintenance +5%). +Whenever the current margin of a loan falls below maintenance margin, +it needs to be liquidated. Anybody can initiate a liquidation and buy +the collateral tokens at a discounted rate (5%). + + +```solidity +function _liquidate(bytes32 loanId, address receiver, uint256 closeAmount) + internal + returns (uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan to liquidate.| +|`receiver`|`address`|The receiver of the seized amount.| +|`closeAmount`|`uint256`|The amount to close in loanTokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanCloseAmount`|`uint256`|The amount of the collateral token of the loan.| +|`seizedAmount`|`uint256`|The seized amount in the collateral token.| +|`seizedToken`|`address`|The loan token address.| + + +### _swapBackExcess + +Swap back excessive loan tokens to collateral tokens. + + +```solidity +function _swapBackExcess( + Loan memory loanLocal, + LoanParams memory loanParamsLocal, + uint256 swapAmount, + bytes memory loanDataBytes +) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|The loan object.| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`swapAmount`|`uint256`|The amount to be swapped.| +|`loanDataBytes`|`bytes`|Additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`destTokenAmountReceived`|`uint256`|The amount of destiny tokens received.| +|`sourceTokenAmountUsed`|`uint256`|The amount of source tokens used.| +|`collateralToLoanSwapRate`|`uint256`|The swap rate of collateral.| + + diff --git a/foundry/docs/src/contracts/modules/LoanClosingsRollover.sol/contract.LoanClosingsRollover.md b/foundry/docs/src/contracts/modules/LoanClosingsRollover.sol/contract.LoanClosingsRollover.md new file mode 100644 index 000000000..c7c60dd5b --- /dev/null +++ b/foundry/docs/src/contracts/modules/LoanClosingsRollover.sol/contract.LoanClosingsRollover.md @@ -0,0 +1,136 @@ +# LoanClosingsRollover +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/LoanClosingsRollover.sol) + +**Inherits:** +[LoanClosingsShared](/contracts/modules/LoanClosingsShared.sol/contract.LoanClosingsShared.md), [LiquidationHelper](/contracts/mixins/LiquidationHelper.sol/contract.LiquidationHelper.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +Ways to close a loan: rollover. Margin trade +positions are always closed with a swap. + + +## State Variables +### MONTH + +```solidity +uint256 internal constant MONTH = 365 days / 12; +``` + + +## Functions +### constructor + + +```solidity +constructor() public; +``` + +### function + + +```solidity +function() external; +``` + +### initialize + + +```solidity +function initialize(address target) external onlyOwner; +``` + +### rollover + +Roll over a loan. + +*Public wrapper for _rollover internal function. +Each loan has a duration. In case of a margin trade it is set to 28 +days, in case of borrowing, it can be set by the user. On loan +openning, the user pays the interest for this duration in advance. +If closing early, he gets the excess refunded. If it is not closed +before the end date, it needs to be rolled over. On rollover the +interest is paid for the next period. In case of margin trading +it's 28 days, in case of borrowing it's a month. +The function rollover on the protocol contract extends the loan +duration by the maximum term (28 days for margin trades at the moment +of writing), pays the interest to the lender and refunds the caller +for the gas cost by sending 2 * the gas cost using the fast gas price +as base for the calculation.* + + +```solidity +function rollover(bytes32 loanId, bytes calldata) + external + nonReentrant + globallyNonReentrant + iTokenSupplyUnchanged(loanId) + whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan to roll over. // param calldata The payload for the call. These loan DataBytes are additional loan data (not in use for token swaps).| +|``|`bytes`|| + + +### _rollover + +Internal function for roll over a loan. +Each loan has a duration. In case of a margin trade it is set to 28 +days, in case of borrowing, it can be set by the user. On loan +openning, the user pays the interest for this duration in advance. +If closing early, he gets the excess refunded. If it is not closed +before the end date, it needs to be rolled over. On rollover the +interest is paid for the next period. In case of margin trading +it's 28 days, in case of borrowing it's a month. + + +```solidity +function _rollover(bytes32 loanId, bytes memory loanDataBytes) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan to roll over.| +|`loanDataBytes`|`bytes`|The payload for the call. These loan DataBytes are additional loan data (not in use for token swaps).| + + +### _swapBackExcess + +fee token +pairToken (used to check if there is any special rebates or not) -- to pay fee reward +loanDataBytes + +Swap back excessive loan tokens to collateral tokens. + + +```solidity +function _swapBackExcess( + Loan memory loanLocal, + LoanParams memory loanParamsLocal, + uint256 swapAmount, + bytes memory loanDataBytes +) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|The loan object.| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`swapAmount`|`uint256`|The amount to be swapped.| +|`loanDataBytes`|`bytes`|Additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`destTokenAmountReceived`|`uint256`|The amount of destiny tokens received.| +|`sourceTokenAmountUsed`|`uint256`|The amount of source tokens used.| +|`collateralToLoanSwapRate`|`uint256`|The swap rate of collateral.| + + diff --git a/foundry/docs/src/contracts/modules/LoanClosingsShared.sol/contract.LoanClosingsShared.md b/foundry/docs/src/contracts/modules/LoanClosingsShared.sol/contract.LoanClosingsShared.md new file mode 100644 index 000000000..796dd8ee2 --- /dev/null +++ b/foundry/docs/src/contracts/modules/LoanClosingsShared.sol/contract.LoanClosingsShared.md @@ -0,0 +1,422 @@ +# LoanClosingsShared +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/LoanClosingsShared.sol) + +**Inherits:** +[LoanClosingsEvents](/contracts/events/LoanClosingsEvents.sol/contract.LoanClosingsEvents.md), [VaultController](/contracts/mixins/VaultController.sol/contract.VaultController.md), [InterestUser](/contracts/mixins/InterestUser.sol/contract.InterestUser.md), [SwapsUser](/contracts/swaps/SwapsUser.sol/contract.SwapsUser.md), [RewardHelper](/contracts/mixins/RewardHelper.sol/contract.RewardHelper.md), [ModuleCommonFunctionalities](/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract should only contains the internal function that is being used / utilized by +LoanClosingsLiquidation, LoanClosingsRollover & LoanClosingsWith contract + + +## State Variables +### MONTH + +```solidity +uint256 internal constant MONTH = 365 days / 12; +``` + + +### paySwapExcessToBorrowerThreshold + +```solidity +uint256 public constant paySwapExcessToBorrowerThreshold = 10000000000000; +``` + + +### TINY_AMOUNT + +```solidity +uint256 public constant TINY_AMOUNT = 25e13; +``` + + +## Functions +### iTokenSupplyUnchanged + +modifier for invariant check + + +```solidity +modifier iTokenSupplyUnchanged(bytes32 loanId); +``` + +### _settleInterestToPrincipal + +Validate iToken total supply + +*computes the interest which needs to be refunded to the borrower based on the amount he's closing and either +subtracts it from the amount which still needs to be paid back (in case outstanding amount > interest) or withdraws the +excess to the borrower (in case interest > outstanding).* + + +```solidity +function _settleInterestToPrincipal( + Loan memory loanLocal, + LoanParams memory loanParamsLocal, + uint256 loanCloseAmount, + address receiver +) internal returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|the loan| +|`loanParamsLocal`|`LoanParams`|the loan params| +|`loanCloseAmount`|`uint256`|the amount to be closed (base for the computation)| +|`receiver`|`address`|the address of the receiver (usually the borrower)| + + +### _returnPrincipalWithDeposit + + +```solidity +function _returnPrincipalWithDeposit(address loanToken, address receiver, uint256 principalNeeded) internal; +``` + +### worthTheTransfer + +*checks if the amount of the asset to be transfered is worth the transfer fee* + + +```solidity +function worthTheTransfer(address asset, uint256 amount) internal returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`asset`|`address`|the asset to be transfered| +|`amount`|`uint256`|the amount to be transfered| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|True if the amount is bigger than the threshold| + + +### _doCollateralSwap + +swaps collateral tokens for loan tokens + + +```solidity +function _doCollateralSwap( + Loan memory loanLocal, + LoanParams memory loanParamsLocal, + uint256 swapAmount, + uint256 principalNeeded, + bool returnTokenIsCollateral, + bytes memory loanDataBytes +) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|the loan object| +|`loanParamsLocal`|`LoanParams`|the loan parameters| +|`swapAmount`|`uint256`|the amount to be swapped| +|`principalNeeded`|`uint256`|the required destination token amount| +|`returnTokenIsCollateral`|`bool`|if true -> required destination token amount will be passed on, else not note: quite dirty. should be refactored.| +|`loanDataBytes`|`bytes`|additional loan data (not in use for token swaps)| + + +### _withdrawAsset + +Withdraw asset to receiver. + + +```solidity +function _withdrawAsset(address assetToken, address receiver, uint256 assetAmount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`assetToken`|`address`|The loan token.| +|`receiver`|`address`|The address of the receiver.| +|`assetAmount`|`uint256`|The loan token amount.| + + +### _closeLoan + +Internal function to close a loan. + + +```solidity +function _closeLoan(Loan storage loanLocal, uint256 loanCloseAmount) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|The loan object.| +|`loanCloseAmount`|`uint256`|The amount to close: principal or lower.| + + +### _settleInterest + + +```solidity +function _settleInterest(LoanParams memory loanParamsLocal, Loan memory loanLocal, uint256 closePrincipal) + internal + returns (uint256); +``` + +### _checkAuthorized + +fee token +pairToken (used to check if there is any special rebates or not) -- to pay fee reward + +Check sender is borrower or delegatee and loan id exists. + + +```solidity +function _checkAuthorized(bytes32 loanId) internal view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|byte32 of the loan id.| + + +### _closeWithSwap + +Internal function for closing a position by swapping the +collateral back to loan tokens, paying the lender and withdrawing +the remainder. + + +```solidity +function _closeWithSwap( + bytes32 loanId, + address receiver, + uint256 swapAmount, + bool returnTokenIsCollateral, + bytes memory loanDataBytes +) internal returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The id of the loan.| +|`receiver`|`address`|The receiver of the remainder (unused collatral + profit).| +|`swapAmount`|`uint256`|Defines how much of the position should be closed and is denominated in collateral tokens. If swapAmount >= collateral, the complete position will be closed. Else if returnTokenIsCollateral, (swapAmount/collateral) * principal will be swapped (partial closure). Else coveredPrincipal| +|`returnTokenIsCollateral`|`bool`|Defines if the remainder should be paid out in collateral tokens or underlying loan tokens.| +|`loanDataBytes`|`bytes`|| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanCloseAmount`|`uint256`|The amount of the collateral token of the loan.| +|`withdrawAmount`|`uint256`|The withdraw amount in the collateral token.| +|`withdrawToken`|`address`|The loan token address.| + + +### _finalizeClose + +Can't swap more than collateral. +loanCloseAmountLessInterest will be passed as required amount amount of destination tokens. +this means, the actual swapAmount passed to the swap contract does not matter at all. +the source token amount will be computed depending on the required amount amount of destination tokens. +Computes the interest refund for the borrower and sends it to the lender to cover part of the principal. +loanCloseAmount is calculated after swap; for this case we want to swap the entire source amount +and determine the loanCloseAmount and withdraw amount based on that. +swapAmount repurposed for collateralToLoanSwapRate to avoid stack too deep error. +The amount of source tokens to swap (only matters if !returnTokenIsCollateral or loanCloseAmountLessInterest = 0) +This is the amount of destination tokens we want to receive (only matters if returnTokenIsCollateral) +Condition prior to swap: swapAmount != loanLocal.collateral && !returnTokenIsCollateral +Amounts that is closed. +Amount that is returned to the lender. +Remaining amount withdrawn to the receiver. +Pay back the amount which was covered by the swap. +Reduce the collateral by the amount which was swapped for the closure. +Repays principal to lender. +The lender always gets back an ERC20 (even wrbtc), so we call +withdraw directly rather than use the _withdrawAsset helper function. +collateralToLoanSwapRate + +Close a loan. + +*Wrapper for _closeLoan internal function.* + + +```solidity +function _finalizeClose( + Loan storage loanLocal, + LoanParams storage loanParamsLocal, + uint256 loanCloseAmount, + uint256 collateralCloseAmount, + uint256 collateralToLoanSwapRate, + CloseTypes closeType +) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|The loan object.| +|`loanParamsLocal`|`LoanParams`|The loan params.| +|`loanCloseAmount`|`uint256`|The amount to close: principal or lower.| +|`collateralCloseAmount`|`uint256`|The amount of collateral to close.| +|`collateralToLoanSwapRate`|`uint256`|The price rate collateral/loan token.| +|`closeType`|`CloseTypes`|The type of loan close.| + + +### _coverPrincipalWithSwap + +This is still called even with full loan close to return collateralToLoanRate +Note: We can safely skip the margin check if closing +via closeWithDeposit or if closing the loan in full by any method. +loan fully closed +swaps a share of a loan's collateral or the complete collateral in order to cover the principle. + +Swaps a share of a loan's collateral or the complete collateral +in order to cover the principle. + + +```solidity +function _coverPrincipalWithSwap( + Loan memory loanLocal, + LoanParams memory loanParamsLocal, + uint256 swapAmount, + uint256 principalNeeded, + bool returnTokenIsCollateral, + bytes memory loanDataBytes +) + internal + returns (uint256 coveredPrincipal, uint256 usedCollateral, uint256 withdrawAmount, uint256 collateralToLoanSwapRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|the loan| +|`loanParamsLocal`|`LoanParams`|the loan parameters| +|`swapAmount`|`uint256`|in case principalNeeded == 0 or !returnTokenIsCollateral, this is the amount which is going to be swapped. Else, swapAmount doesn't matter, because the amount of source tokens needed for the swap is estimated by the connector.| +|`principalNeeded`|`uint256`|the required amount of destination tokens in order to cover the principle (only used if returnTokenIsCollateral)| +|`returnTokenIsCollateral`|`bool`|tells if the user wants to withdraw his remaining collateral + profit in collateral tokens| +|`loanDataBytes`|`bytes`|| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`coveredPrincipal`|`uint256`|The amount of principal that is covered.| +|`usedCollateral`|`uint256`|The amount of collateral used.| +|`withdrawAmount`|`uint256`|The withdraw amount in the collateral token.| +|`collateralToLoanSwapRate`|`uint256`|The swap rate of collateral.| + + +### _emitClosingEvents + +Better fill than expected. +Send excess to borrower if the amount is big enough to be +worth the gas fees. +Else, give the excess to the lender (if it goes to the +borrower, they're very confused. causes more trouble than it's worth) +sourceTokenAmountUsed == swapAmount == loanLocal.collateral +sourceTokenAmountUsed == swapAmount < loanLocal.collateral +Edge case where swap covers full principal. +Excess collateral refunds to the borrower. + + +```solidity +function _emitClosingEvents( + LoanParams memory loanParamsLocal, + Loan memory loanLocal, + uint256 loanCloseAmount, + uint256 collateralCloseAmount, + uint256 collateralToLoanRate, + uint256 collateralToLoanSwapRate, + uint256 currentMargin, + CloseTypes closeType +) internal; +``` + +### _getAmountInRbtc + +user (borrower) +lender +loanId +closer +loanToken +collateralToken +loanCloseAmount +collateralCloseAmount +collateralToLoanRate +currentMargin +exitPrice = 1 / collateralToLoanSwapRate +currentLeverage = 100 / currentMargin +user (trader) +lender +loanId +collateralToken +loanToken +closer +positionCloseSize +loanCloseAmount +exitPrice (1 / collateralToLoanSwapRate) +currentLeverage + +*returns amount of the asset converted to RBTC* + + +```solidity +function _getAmountInRbtc(address asset, uint256 amount) internal view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`asset`|`address`|the asset to be transferred| +|`amount`|`uint256`|the amount to be transferred| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|amount in RBTC| + + +### _checkLoan + +*private function which check the loanLocal & loanParamsLocal does exist* + + +```solidity +function _checkLoan(bytes32 loanId) internal view returns (Loan storage, LoanParams storage); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|bytes32 of loanId| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`Loan`|Loan storage| +|``|`LoanParams`|LoanParams storage| + + +## Enums +### CloseTypes + +```solidity +enum CloseTypes { + Deposit, + Swap, + Liquidation +} +``` + diff --git a/foundry/docs/src/contracts/modules/LoanClosingsWith.sol/contract.LoanClosingsWith.md b/foundry/docs/src/contracts/modules/LoanClosingsWith.sol/contract.LoanClosingsWith.md new file mode 100644 index 000000000..5dc5e38ae --- /dev/null +++ b/foundry/docs/src/contracts/modules/LoanClosingsWith.sol/contract.LoanClosingsWith.md @@ -0,0 +1,166 @@ +# LoanClosingsWith +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/LoanClosingsWith.sol) + +**Inherits:** +[LoanClosingsShared](/contracts/modules/LoanClosingsShared.sol/contract.LoanClosingsShared.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +Close a loan w/deposit, close w/swap. There are 2 functions for ending a loan on the +protocol contract: closeWithSwap and closeWithDeposit. Margin trade +positions are always closed with a swap. +Loans are liquidated if the position goes below margin maintenance. + + +## Functions +### constructor + + +```solidity +constructor() public; +``` + +### function + + +```solidity +function() external; +``` + +### initialize + + +```solidity +function initialize(address target) external onlyOwner; +``` + +### closeWithDeposit + +Closes a loan by doing a deposit. + +*Public wrapper for _closeWithDeposit internal function.* + + +```solidity +function closeWithDeposit(bytes32 loanId, address receiver, uint256 depositAmount) + public + payable + nonReentrant + globallyNonReentrant + iTokenSupplyUnchanged(loanId) + whenNotPaused + returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The id of the loan.| +|`receiver`|`address`|The receiver of the remainder.| +|`depositAmount`|`uint256`|Defines how much of the position should be closed. It is denominated in loan tokens. (e.g. rBTC on a iSUSD contract). If depositAmount > principal, the complete loan will be closed else deposit amount (partial closure).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanCloseAmount`|`uint256`|The amount of the collateral token of the loan.| +|`withdrawAmount`|`uint256`|The withdraw amount in the collateral token.| +|`withdrawToken`|`address`|The loan token address.| + + +### closeWithSwap + +Close a position by swapping the collateral back to loan tokens +paying the lender and withdrawing the remainder. + +*Public wrapper for _closeWithSwap internal function.* + + +```solidity +function closeWithSwap(bytes32 loanId, address receiver, uint256 swapAmount, bool returnTokenIsCollateral, bytes memory) + public + nonReentrant + globallyNonReentrant + iTokenSupplyUnchanged(loanId) + whenNotPaused + returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The id of the loan.| +|`receiver`|`address`|The receiver of the remainder (unused collateral + profit).| +|`swapAmount`|`uint256`|Defines how much of the position should be closed and is denominated in collateral tokens. If swapAmount >= collateral, the complete position will be closed. Else if returnTokenIsCollateral, (swapAmount/collateral) * principal will be swapped (partial closure). Else coveredPrincipal| +|`returnTokenIsCollateral`|`bool`|Defines if the remainder should be paid out in collateral tokens or underlying loan tokens.| +|``|`bytes`|| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanCloseAmount`|`uint256`|The amount of the collateral token of the loan.| +|`withdrawAmount`|`uint256`|The withdraw amount in the collateral token.| +|`withdrawToken`|`address`|The loan token address.| + + +### _closeWithDeposit + +loanDataBytes + +Internal function for closing a loan by doing a deposit. + + +```solidity +function _closeWithDeposit(bytes32 loanId, address receiver, uint256 depositAmount) + internal + returns (uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The id of the loan.| +|`receiver`|`address`|The receiver of the remainder.| +|`depositAmount`|`uint256`|Defines how much of the position should be closed. It is denominated in loan tokens. If depositAmount > principal, the complete loan will be closed else deposit amount (partial closure).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanCloseAmount`|`uint256`|The amount of the collateral token of the loan.| +|`withdrawAmount`|`uint256`|The withdraw amount in the collateral token.| +|`withdrawToken`|`address`|The loan token address.| + + +### checkCloseWithDepositIsTinyPosition + +Can't close more than the full principal. +collateralCloseAmount +collateralToLoanSwapRate + +Function to check whether the given loanId & deposit amount when closing with deposit will cause the tiny position + + +```solidity +function checkCloseWithDepositIsTinyPosition(bytes32 loanId, uint256 depositAmount) + external + view + returns (bool isTinyPosition, uint256 tinyPositionAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The id of the loan.| +|`depositAmount`|`uint256`|Defines how much the deposit amount to close the position.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`isTinyPosition`|`bool`|true is indicating tiny position, false otherwise.| +|`tinyPositionAmount`|`uint256`|will return 0 for non tiny position, and will return the amount of tiny position if true| + + diff --git a/foundry/docs/src/contracts/modules/LoanMaintenance.sol/contract.LoanMaintenance.md b/foundry/docs/src/contracts/modules/LoanMaintenance.sol/contract.LoanMaintenance.md new file mode 100644 index 000000000..696e419af --- /dev/null +++ b/foundry/docs/src/contracts/modules/LoanMaintenance.sol/contract.LoanMaintenance.md @@ -0,0 +1,548 @@ +# LoanMaintenance +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/LoanMaintenance.sol) + +**Inherits:** +[LoanOpeningsEvents](/contracts/events/LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md), [LoanMaintenanceEvents](/contracts/events/LoanMaintenanceEvents.sol/contract.LoanMaintenanceEvents.md), [VaultController](/contracts/mixins/VaultController.sol/contract.VaultController.md), [InterestUser](/contracts/mixins/InterestUser.sol/contract.InterestUser.md), [SwapsUser](/contracts/swaps/SwapsUser.sol/contract.SwapsUser.md), [LiquidationHelper](/contracts/mixins/LiquidationHelper.sol/contract.LiquidationHelper.md), [ModuleCommonFunctionalities](/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains functions to query loan data and to modify its status +by withdrawing or depositing collateral. + + +## Functions +### constructor + +Empty public constructor. + + +```solidity +constructor() public; +``` + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external; +``` + +### initialize + +Set initial values of proxy targets. + + +```solidity +function initialize(address target) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The address of the logic contract instance.| + + +### depositCollateral + +Increase the margin of a position by depositing additional collateral. + + +```solidity +function depositCollateral(bytes32 loanId, uint256 depositAmount) external payable nonReentrant whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| +|`depositAmount`|`uint256`|The amount to be deposited in collateral tokens.| + + +### withdrawCollateral + +Withdraw from the collateral. This reduces the margin of a position. + + +```solidity +function withdrawCollateral(bytes32 loanId, address receiver, uint256 withdrawAmount) + external + nonReentrant + whenNotPaused + returns (uint256 actualWithdrawAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| +|`receiver`|`address`|The account getting the withdrawal.| +|`withdrawAmount`|`uint256`|The amount to be withdrawn in collateral tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`actualWithdrawAmount`|`uint256`|The amount withdrawn taking into account drawdowns.| + + +### withdrawAccruedInterest + +Withdraw accrued loan interest. + +*Wrapper for _payInterest internal function.* + + +```solidity +function withdrawAccruedInterest(address loanToken) external whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The loan token address.| + + +### extendLoanDuration + +Pay outstanding interest to lender. +Lender. + +Extend the loan duration by as much time as depositAmount can buy. + + +```solidity +function extendLoanDuration(bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata) + external + payable + nonReentrant + whenNotPaused + returns (uint256 secondsExtended); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| +|`depositAmount`|`uint256`|The amount to be deposited in loan tokens. Used to pay the interest for the new duration.| +|`useCollateral`|`bool`|Whether pay interests w/ the collateral. If true, depositAmount of loan tokens will be purchased with the collateral. // param calldata The payload for the call. These loan DataBytes are additional loan data (not in use for token swaps).| +|``|`bytes`|| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`secondsExtended`|`uint256`|The amount of time in seconds the loan is extended.| + + +### reduceLoanDuration + +Pay outstanding interest to lender. +fee token +pairToken (used to check if there is any special rebates or not) -- to pay fee reward +Handle back interest: calculates interest owned since the loan +endtime passed but the loan remained open. +Deposit interest. +Used the whole converted loanToken to extend the loan duration +Pay out backInterestOwed +Loan term has to at least be greater than one hour. + +Reduce the loan duration by withdrawing from the deposited interest. + + +```solidity +function reduceLoanDuration(bytes32 loanId, address receiver, uint256 withdrawAmount) + external + nonReentrant + whenNotPaused + returns (uint256 secondsReduced); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| +|`receiver`|`address`|The account getting the withdrawal.| +|`withdrawAmount`|`uint256`|The amount to be withdrawn in loan tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`secondsReduced`|`uint256`|The amount of time in seconds the loan is reduced.| + + +### getLenderInterestData + +Pay outstanding interest to lender. +fee token +pairToken (used to check if there is any special rebates or not) -- to pay fee reward +Withdraw interest. +Loan term has to at least be greater than one hour. + +Get current lender interest data totals for all loans +with a specific oracle and interest token. + + +```solidity +function getLenderInterestData(address lender, address loanToken) + external + view + returns ( + uint256 interestPaid, + uint256 interestPaidDate, + uint256 interestOwedPerDay, + uint256 interestUnPaid, + uint256 interestFeePercent, + uint256 principalTotal + ); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lender`|`address`|The lender address.| +|`loanToken`|`address`|The loan token address.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`interestPaid`|`uint256`|The total amount of interest that has been paid to a lender so far.| +|`interestPaidDate`|`uint256`|The date of the last interest pay out, or 0 if no interest has been withdrawn yet.| +|`interestOwedPerDay`|`uint256`|The amount of interest the lender is earning per day.| +|`interestUnPaid`|`uint256`|The total amount of interest the lender is owned and not yet withdrawn.| +|`interestFeePercent`|`uint256`|The fee retained by the protocol before interest is paid to the lender.| +|`principalTotal`|`uint256`|The total amount of outstanding principal the lender has loaned.| + + +### getLoanInterestData + +Get current interest data for a loan. + + +```solidity +function getLoanInterestData(bytes32 loanId) + external + view + returns ( + address loanToken, + uint256 interestOwedPerDay, + uint256 interestDepositTotal, + uint256 interestDepositRemaining + ); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The loan token that interest is paid in.| +|`interestOwedPerDay`|`uint256`|The amount of interest the borrower is paying per day.| +|`interestDepositTotal`|`uint256`|The total amount of interest the borrower has deposited.| +|`interestDepositRemaining`|`uint256`|The amount of deposited interest that is not yet owed to a lender.| + + +### getUserLoans + +Get all user loans. +Only returns data for loans that are active. + + +```solidity +function getUserLoans(address user, uint256 start, uint256 count, uint256 loanType, bool isLender, bool unsafeOnly) + external + view + returns (LoanReturnData[] memory loansData); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The user address.| +|`start`|`uint256`|The lower loan ID to start with.| +|`count`|`uint256`|The maximum number of results.| +|`loanType`|`uint256`|The type of loan. loanType 0: all loans. loanType 1: margin trade loans. loanType 2: non-margin trade loans.| +|`isLender`|`bool`|Whether the user is lender or borrower.| +|`unsafeOnly`|`bool`|The safe filter (True/False).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loansData`|`LoanReturnData[]`|The array of loans as query result.| + + +### getUserLoansV2 + +loanId + +Get all user loans. +Only returns data for loans that are active. + + +```solidity +function getUserLoansV2(address user, uint256 start, uint256 count, uint256 loanType, bool isLender, bool unsafeOnly) + external + view + returns (LoanReturnDataV2[] memory loansDataV2); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`user`|`address`|The user address.| +|`start`|`uint256`|The lower loan ID to start with.| +|`count`|`uint256`|The maximum number of results.| +|`loanType`|`uint256`|The type of loan. loanType 0: all loans. loanType 1: margin trade loans. loanType 2: non-margin trade loans.| +|`isLender`|`bool`|Whether the user is lender or borrower.| +|`unsafeOnly`|`bool`|The safe filter (True/False).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loansDataV2`|`LoanReturnDataV2[]`|loansData The array of loans as query result.| + + +### getLoan + +loanId + +Get one loan data structure by matching ID. +Wrapper to internal _getLoan call. + + +```solidity +function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanData`|`LoanReturnData`|loansData The data structure w/ loan information.| + + +### getLoanV2 + +loanType +unsafeOnly + +Get one loan data structure by matching ID. +Wrapper to internal _getLoan call. + + +```solidity +function getLoanV2(bytes32 loanId) external view returns (LoanReturnDataV2 memory loanDataV2); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanDataV2`|`LoanReturnDataV2`|loansData The data structure w/ loan information.| + + +### getActiveLoans + +loanType +unsafeOnly + +Get all active loans. + + +```solidity +function getActiveLoans(uint256 start, uint256 count, bool unsafeOnly) + external + view + returns (LoanReturnData[] memory loansData); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`start`|`uint256`|The lower loan ID to start with.| +|`count`|`uint256`|The maximum number of results.| +|`unsafeOnly`|`bool`|The safe filter (True/False).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loansData`|`LoanReturnData[]`|The data structure w/ loan information.| + + +### getActiveLoansV2 + +loanId +loanType + +*New view function which will return the loan data.* + +*This function was created to support backward compatibility* + +*As in we the old getActiveLoans function is not expected to be changed by the wathcers.* + + +```solidity +function getActiveLoansV2(uint256 start, uint256 count, bool unsafeOnly) + external + view + returns (LoanReturnDataV2[] memory loansDataV2); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`start`|`uint256`|The lower loan ID to start with.| +|`count`|`uint256`|The maximum number of results.| +|`unsafeOnly`|`bool`|The safe filter (True/False).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loansDataV2`|`LoanReturnDataV2[]`|loanData The data structure| + + +### _getLoan + +loanId +loanType + +Internal function to get one loan data structure. + + +```solidity +function _getLoan(bytes32 loanId, uint256 loanType, bool unsafeOnly) + internal + view + returns (LoanReturnData memory loanData); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| +|`loanType`|`uint256`|The type of loan. loanType 0: all loans. loanType 1: margin trade loans. loanType 2: non-margin trade loans.| +|`unsafeOnly`|`bool`|The safe filter (True/False).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanData`|`LoanReturnData`|loansData The data structure w/ the loan information.| + + +### _getLoanV2 + +Internal function to get one loan data structure v2. + + +```solidity +function _getLoanV2(bytes32 loanId, uint256 loanType, bool unsafeOnly) + internal + view + returns (LoanReturnDataV2 memory loanDataV2); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|A unique ID representing the loan.| +|`loanType`|`uint256`|The type of loan. loanType 0: all loans. loanType 1: margin trade loans. loanType 2: non-margin trade loans.| +|`unsafeOnly`|`bool`|The safe filter (True/False).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanDataV2`|`LoanReturnDataV2`|loansData The data v2 structure w/ the loan information.| + + +### _doCollateralSwap + +Internal function to collect interest from the collateral. + + +```solidity +function _doCollateralSwap(Loan storage loanLocal, LoanParams memory loanParamsLocal, uint256 depositAmount) + internal + returns (uint256 purchasedLoanToken); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanLocal`|`Loan`|The loan object.| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`depositAmount`|`uint256`|The amount of underlying tokens provided on the loan.| + + +## Structs +### LoanReturnData + +```solidity +struct LoanReturnData { + bytes32 loanId; + address loanToken; + address collateralToken; + uint256 principal; + uint256 collateral; + uint256 interestOwedPerDay; + uint256 interestDepositRemaining; + uint256 startRate; + uint256 startMargin; + uint256 maintenanceMargin; + uint256 currentMargin; + uint256 maxLoanTerm; + uint256 endTimestamp; + uint256 maxLiquidatable; + uint256 maxSeizable; +} +``` + +### LoanReturnDataV2 + +```solidity +struct LoanReturnDataV2 { + bytes32 loanId; + address loanToken; + address collateralToken; + address borrower; + uint256 principal; + uint256 collateral; + uint256 interestOwedPerDay; + uint256 interestDepositRemaining; + uint256 startRate; + uint256 startMargin; + uint256 maintenanceMargin; + uint256 currentMargin; + uint256 maxLoanTerm; + uint256 endTimestamp; + uint256 maxLiquidatable; + uint256 maxSeizable; + uint256 creationTimestamp; +} +``` + diff --git a/foundry/docs/src/contracts/modules/LoanOpenings.sol/contract.LoanOpenings.md b/foundry/docs/src/contracts/modules/LoanOpenings.sol/contract.LoanOpenings.md new file mode 100644 index 000000000..8432c1ade --- /dev/null +++ b/foundry/docs/src/contracts/modules/LoanOpenings.sol/contract.LoanOpenings.md @@ -0,0 +1,541 @@ +# LoanOpenings +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/LoanOpenings.sol) + +**Inherits:** +[LoanOpeningsEvents](/contracts/events/LoanOpeningsEvents.sol/contract.LoanOpeningsEvents.md), [VaultController](/contracts/mixins/VaultController.sol/contract.VaultController.md), [InterestUser](/contracts/mixins/InterestUser.sol/contract.InterestUser.md), [SwapsUser](/contracts/swaps/SwapsUser.sol/contract.SwapsUser.md), [ModuleCommonFunctionalities](/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains functions to borrow and trade. + + +## Functions +### constructor + + +```solidity +constructor() public; +``` + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external; +``` + +### initialize + +Set function selectors on target contract. + + +```solidity +function initialize(address target) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The address of the target contract.| + + +### borrowOrTradeFromPool + +Borrow or trade from pool. + +*Note: Only callable by loan pools (iTokens). +Wrapper to _borrowOrTrade internal function.* + + +```solidity +function borrowOrTradeFromPool( + bytes32 loanParamsId, + bytes32 loanId, + bool isTorqueLoan, + uint256 initialMargin, + MarginTradeStructHelpers.SentAddresses calldata sentAddresses, + MarginTradeStructHelpers.SentAmounts calldata sentValues, + bytes calldata loanDataBytes +) external payable nonReentrant whenNotPaused returns (uint256 newPrincipal, uint256 newCollateral); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsId`|`bytes32`|The ID of the loan parameters.| +|`loanId`|`bytes32`|The ID of the loan. If 0, start a new loan.| +|`isTorqueLoan`|`bool`|Whether the loan is a Torque loan.| +|`initialMargin`|`uint256`|The initial amount of margin.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The addresses to send tokens: lender, borrower, receiver and manager: lender: must match loan if loanId provided. borrower: must match loan if loanId provided. receiver: receiver of funds (address(0) assumes borrower address). manager: delegated manager of loan unless address(0).| +|`sentValues`|`MarginTradeStructHelpers.SentAmounts`|The values to send: interestRate: New loan interest rate. newPrincipal: New loan size (borrowAmount + any borrowed interest). interestInitialAmount: New amount of interest to escrow for Torque loan (determines initial loan length). loanTokenReceived: Total loanToken deposit (amount not sent to borrower in the case of Torque loans). collateralTokenSent: Total collateralToken deposit. minEntryPrice: Minimum entry price for checking price divergence (Value of loan token in collateral).| +|`loanDataBytes`|`bytes`|The payload for the call. These loan DataBytes are additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`newPrincipal`|`uint256`|The new loan size.| +|`newCollateral`|`uint256`|The new collateral amount.| + + +### setDelegatedManager + +Only callable by loan pools. +Get required collateral. + +Set the delegated manager. + +*Wrapper for _setDelegatedManager internal function.* + + +```solidity +function setDelegatedManager(bytes32 loanId, address delegated, bool toggle) external whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan. If 0, start a new loan.| +|`delegated`|`address`|The address of the delegated manager.| +|`toggle`|`bool`|The flag true/false for the delegated manager.| + + +### getEstimatedMarginExposure + +Get the estimated margin exposure. +Margin is the money borrowed from a broker to purchase an investment +and is the difference between the total value of investment and the +loan amount. Margin trading refers to the practice of using borrowed +funds from a broker to trade a financial asset, which forms the +collateral for the loan from the broker. + + +```solidity +function getEstimatedMarginExposure( + address loanToken, + address collateralToken, + uint256 loanTokenSent, + uint256 collateralTokenSent, + uint256 interestRate, + uint256 newPrincipal +) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The loan token instance address.| +|`collateralToken`|`address`|The collateral token instance address.| +|`loanTokenSent`|`uint256`|The amount of loan tokens sent.| +|`collateralTokenSent`|`uint256`|The amount of collateral tokens sent.| +|`interestRate`|`uint256`|The interest rate. Percentage w/ 18 decimals.| +|`newPrincipal`|`uint256`|The updated amount of principal (current debt).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The margin exposure.| + + +### getRequiredCollateral + +Get the required collateral. + +*Calls internal _getRequiredCollateral and add fees.* + + +```solidity +function getRequiredCollateral( + address loanToken, + address collateralToken, + uint256 newPrincipal, + uint256 marginAmount, + bool isTorqueLoan +) public view returns (uint256 collateralAmountRequired); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The loan token instance address.| +|`collateralToken`|`address`|The collateral token instance address.| +|`newPrincipal`|`uint256`|The updated amount of principal (current debt).| +|`marginAmount`|`uint256`|The amount of margin of the trade.| +|`isTorqueLoan`|`bool`|Whether the loan is a Torque loan.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`collateralAmountRequired`|`uint256`|The required collateral.| + + +### getBorrowAmount + +Get the borrow amount of a trade loan. + +*Basically borrowAmount = collateral / marginAmount +Collateral is something that helps secure a loan. When you borrow money, +you agree that your lender can take something and sell it to get their +money back if you fail to repay the loan. That's the collateral.* + + +```solidity +function getBorrowAmount( + address loanToken, + address collateralToken, + uint256 collateralTokenAmount, + uint256 marginAmount, + bool isTorqueLoan +) public view returns (uint256 borrowAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The loan token instance address.| +|`collateralToken`|`address`|The collateral token instance address.| +|`collateralTokenAmount`|`uint256`|The amount of collateral.| +|`marginAmount`|`uint256`|The amount of margin of the trade.| +|`isTorqueLoan`|`bool`|Whether the loan is a Torque loan.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`borrowAmount`|`uint256`|The borrow amount.| + + +### _borrowOrTrade + +Adjust for over-collateralized loan. + +Borrow or trade. + + +```solidity +function _borrowOrTrade( + LoanParams memory loanParamsLocal, + bytes32 loanId, + bool isTorqueLoan, + uint256 collateralAmountRequired, + uint256 initialMargin, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + MarginTradeStructHelpers.SentAmounts memory sentValues, + bytes memory loanDataBytes +) internal returns (uint256, uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`loanId`|`bytes32`|The ID of the loan. If 0, start a new loan.| +|`isTorqueLoan`|`bool`|Whether the loan is a Torque loan.| +|`collateralAmountRequired`|`uint256`|The required amount of collateral.| +|`initialMargin`|`uint256`|The initial amount of margin.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The addresses to send tokens: lender, borrower, receiver and manager: lender: must match loan if loanId provided. borrower: must match loan if loanId provided. receiver: receiver of funds (address(0) assumes borrower address). manager: delegated manager of loan unless address(0).| +|`sentValues`|`MarginTradeStructHelpers.SentAmounts`|The values to send: interestRate: New loan interest rate. newPrincipal: New loan size (borrowAmount + any borrowed interest). interestInitialAmount: New amount of interest to escrow for Torque loan (determines initial loan length). loanTokenReceived: Total loanToken deposit (amount not sent to borrower in the case of Torque loans). collateralTokenSent: Total collateralToken deposit. minEntryPrice: Minimum entry price for checking price divergence (Value of loan token in collateral).| +|`loanDataBytes`|`bytes`|The payload for the call. These loan DataBytes are additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The new loan size.| +|``|`uint256`|The new collateral amount.| + + +### _updateCollateralAfterTrade + +maxLoanTerm == 0 indicates a Torque loan and requires that torqueInterest != 0 +torqueInterest +Initialize loan. +newRate +newPrincipal, +torqueInterest +substract out interest from usable loanToken sent. +borrower +fee token +pairToken (used to check if there is any special rebates or not) -- to pay fee reward +Update collateral after trade. +Settle collateral. +reclaiming variable -> interestDuration +reclaiming variable -> entryLeverage = 100 / initialMargin +newPrincipal, newCollateral + + +```solidity +function _updateCollateralAfterTrade( + bytes32 loanId, + LoanParams memory loanParamsLocal, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + MarginTradeStructHelpers.SentAmounts memory sentValues, + bytes memory loanDataBytes +) internal returns (MarginTradeStructHelpers.SentAmounts memory); +``` + +### _finalizeOpen + +borrower +loanTokenUsable (minSourceTokenAmount) +maxSourceTokenAmount (0 means minSourceTokenAmount) +requiredDestTokenAmount (enforces that all of loanTokenUsable is swapped) +bypassFee +Check the minEntryPrice with the rate + +Finalize an open loan. + +*Finalize it by updating local parameters of the loan.* + + +```solidity +function _finalizeOpen( + LoanParams memory loanParamsLocal, + Loan storage loanLocal, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + MarginTradeStructHelpers.SentAmounts memory sentValues, + bool isTorqueLoan +) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`loanLocal`|`Loan`|The loan object.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The addresses to send tokens: lender, borrower, receiver and manager: lender: must match loan if loanId provided. borrower: must match loan if loanId provided. receiver: receiver of funds (address(0) assumes borrower address). manager: delegated manager of loan unless address(0).| +|`sentValues`|`MarginTradeStructHelpers.SentAmounts`|The values to send: interestRate: New loan interest rate. newPrincipal: New loan size (borrowAmount + any borrowed interest). interestInitialAmount: New amount of interest to escrow for Torque loan (determines initial loan length). loanTokenReceived: Total loanToken deposit (amount not sent to borrower in the case of Torque loans). collateralTokenSent: Total collateralToken deposit. minEntryPrice: Minimum entry price for checking price divergence (Value of loan token in collateral).| +|`isTorqueLoan`|`bool`|Whether the loan is a Torque loan.| + + +### _emitOpeningEvents + +Emit the opening events. + +*TODO: here the actual used rate and margin should go.* + + +```solidity +function _emitOpeningEvents( + LoanParams memory loanParamsLocal, + Loan memory loanLocal, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + MarginTradeStructHelpers.SentAmounts memory sentValues, + uint256 collateralToLoanRate, + uint256 margin, + bool isTorqueLoan +) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`loanLocal`|`Loan`|The loan object.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The addresses to send tokens: lender, borrower, receiver and manager: lender: must match loan if loanId provided. borrower: must match loan if loanId provided. receiver: receiver of funds (address(0) assumes borrower address). manager: delegated manager of loan unless address(0).| +|`sentValues`|`MarginTradeStructHelpers.SentAmounts`|The values to send: interestRate: New loan interest rate. newPrincipal: New loan size (borrowAmount + any borrowed interest). interestInitialAmount: New amount of interest to escrow for Torque loan (determines initial loan length). loanTokenReceived: Total loanToken deposit (amount not sent to borrower in the case of Torque loans). collateralTokenSent: Total collateralToken deposit. minEntryPrice: Minimum entry price for checking price divergence (Value of loan token in collateral).| +|`collateralToLoanRate`|`uint256`|The exchange rate from collateral to loan tokens.| +|`margin`|`uint256`|The amount of margin of the trade.| +|`isTorqueLoan`|`bool`|Whether the loan is a Torque loan.| + + +### _setDelegatedManager + +user (borrower) +lender +loanId +loanToken +collateralToken +newPrincipal +newCollateral +interestRate +interestDuration +collateralToLoanRate, +currentMargin +currentLeverage = 100 / currentMargin +user (trader) +lender +loanId +collateralToken +loanToken +positionSize +borrowedAmount +interestRate, +settlementDate +entryPrice (loanToCollateralSwapRate) +entryLeverage +currentLeverage + +Set the delegated manager. + + +```solidity +function _setDelegatedManager(bytes32 loanId, address delegator, address delegated, bool toggle) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan. If 0, start a new loan.| +|`delegator`|`address`|The address of previous manager.| +|`delegated`|`address`|The address of the delegated manager.| +|`toggle`|`bool`|The flag true/false for the delegated manager.| + + +### _isCollateralSatisfied + +Calculate whether the collateral is satisfied. + +*Basically check collateral + drawdown >= 98% of required.* + + +```solidity +function _isCollateralSatisfied( + LoanParams memory loanParamsLocal, + Loan memory loanLocal, + uint256 initialMargin, + uint256 newCollateral, + uint256 collateralAmountRequired, + uint256 newPrincipal +) internal view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`loanLocal`|`Loan`|The loan object.| +|`initialMargin`|`uint256`|The initial amount of margin.| +|`newCollateral`|`uint256`|The amount of new collateral.| +|`collateralAmountRequired`|`uint256`|The amount of required collateral.| +|`newPrincipal`|`uint256`|The amount to borrow.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Whether the collateral is satisfied.| + + +### _initializeLoan + +Allow at most 2% under-collateralized. +Check that existing collateral is sufficient coverage. + +Initialize a loan. + + +```solidity +function _initializeLoan( + LoanParams memory loanParamsLocal, + bytes32 loanId, + uint256 initialMargin, + MarginTradeStructHelpers.SentAddresses memory sentAddresses, + uint256 newPrincipal +) internal returns (bytes32); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`loanId`|`bytes32`|The ID of the loan.| +|`initialMargin`|`uint256`|The amount of margin of the trade.| +|`sentAddresses`|`MarginTradeStructHelpers.SentAddresses`|The addresses to send tokens: lender, borrower, receiver and manager: lender: must match loan if loanId provided. borrower: must match loan if loanId provided. receiver: receiver of funds (address(0) assumes borrower address). manager: delegated manager of loan unless address(0).| +|`newPrincipal`|`uint256`|New loan size (borrowAmount + any borrowed interest).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes32`|The loanId.| + + +### _initializeInterest + +calculated later +calculated later +queried later + +Initialize a loan interest. + +*A Torque loan is an indefinite-term loan.* + + +```solidity +function _initializeInterest( + LoanParams memory loanParamsLocal, + Loan storage loanLocal, + uint256 newRate, + uint256 newPrincipal, + uint256 torqueInterest +) internal returns (uint256 interestAmountRequired); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| +|`loanLocal`|`Loan`|The loan object.| +|`newRate`|`uint256`|The new interest rate of the loan.| +|`newPrincipal`|`uint256`|The new principal amount of the loan.| +|`torqueInterest`|`uint256`|The interest rate of the Torque loan.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`interestAmountRequired`|`uint256`|The interest amount required.| + + +### _getRequiredCollateral + +Pay outstanding interest to lender. +fee token +pairToken (used to check if there is any special rebates or not) -- to pay fee reward +block.timestamp < endTimestamp was confirmed earlier. +Update stored owedPerDay +Indefinite-term (Torque) loan. +torqueInterest != 0 was confirmed earlier. +Loan term has to at least be greater than one hour. +Fixed-term loan. +Update remaining lender interest values. + +Get the required collateral. + +*Basically collateral = newPrincipal * marginAmount* + + +```solidity +function _getRequiredCollateral( + address loanToken, + address collateralToken, + uint256 newPrincipal, + uint256 marginAmount, + bool isTorqueLoan +) internal view returns (uint256 collateralTokenAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanToken`|`address`|The loan token instance address.| +|`collateralToken`|`address`|The collateral token instance address.| +|`newPrincipal`|`uint256`|The updated amount of principal (current debt).| +|`marginAmount`|`uint256`|The amount of margin of the trade.| +|`isTorqueLoan`|`bool`|Whether the loan is a Torque loan.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`collateralTokenAmount`|`uint256`|The required collateral.| + + diff --git a/foundry/docs/src/contracts/modules/LoanSettings.sol/contract.LoanSettings.md b/foundry/docs/src/contracts/modules/LoanSettings.sol/contract.LoanSettings.md new file mode 100644 index 000000000..7870102f1 --- /dev/null +++ b/foundry/docs/src/contracts/modules/LoanSettings.sol/contract.LoanSettings.md @@ -0,0 +1,191 @@ +# LoanSettings +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/LoanSettings.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md), [LoanSettingsEvents](/contracts/events/LoanSettingsEvents.sol/contract.LoanSettingsEvents.md), [ModuleCommonFunctionalities](/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains functions to get and set loan parameters. + + +## Functions +### constructor + +Empty public constructor. + + +```solidity +constructor() public; +``` + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external; +``` + +### initialize + +Set function selectors on target contract. + + +```solidity +function initialize(address target) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The address of the target contract.| + + +### setupLoanParams + +Setup loan parameters, by looping every loan +and populating its parameters. + +*For each loan calls _setupLoanParams internal function.* + + +```solidity +function setupLoanParams(LoanParams[] calldata loanParamsList) + external + whenNotPaused + returns (bytes32[] memory loanParamsIdList); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsList`|`LoanParams[]`|The array of loan parameters.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsIdList`|`bytes32[]`|The array of loan parameters IDs.| + + +### disableLoanParams + +Deactivate LoanParams for future loans. Active loans +using it are unaffected. + + +```solidity +function disableLoanParams(bytes32[] calldata loanParamsIdList) external whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsIdList`|`bytes32[]`|The array of loan parameters IDs to deactivate.| + + +### getLoanParams + +Get loan parameters for every matching IDs. + + +```solidity +function getLoanParams(bytes32[] memory loanParamsIdList) public view returns (LoanParams[] memory loanParamsList); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsIdList`|`bytes32[]`|The array of loan parameters IDs to match.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsList`|`LoanParams[]`|The result array of loan parameters.| + + +### getLoanParamsList + +Get loan parameters for an owner and a given page +defined by an offset and a limit. + + +```solidity +function getLoanParamsList(address owner, uint256 start, uint256 count) + external + view + returns (bytes32[] memory loanParamsList); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`owner`|`address`|The address of the loan owner.| +|`start`|`uint256`|The page offset.| +|`count`|`uint256`|The page limit.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsList`|`bytes32[]`|The result array of loan parameters.| + + +### getTotalPrincipal + +Get the total principal of the loans by a lender. + + +```solidity +function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`lender`|`address`|The address of the lender.| +|`loanToken`|`address`|The address of the token instance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The total principal of the loans.| + + +### _setupLoanParams + +Setup a loan parameters. + + +```solidity +function _setupLoanParams(LoanParams memory loanParamsLocal) internal returns (bytes32); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanParamsLocal`|`LoanParams`|The loan parameters.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes32`|loanParamsId The loan parameters ID.| + + +### minInitialMargin + +A defined maxLoanTerm has to be greater than one hour. + + +```solidity +function minInitialMargin(bytes32 loanParamsId) external view returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/modules/ProtocolSettings.sol/contract.ProtocolSettings.md b/foundry/docs/src/contracts/modules/ProtocolSettings.sol/contract.ProtocolSettings.md new file mode 100644 index 000000000..5fa9ec67c --- /dev/null +++ b/foundry/docs/src/contracts/modules/ProtocolSettings.sol/contract.ProtocolSettings.md @@ -0,0 +1,856 @@ +# ProtocolSettings +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/ProtocolSettings.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md), [ProtocolTokenUser](/contracts/mixins/ProtocolTokenUser.sol/contract.ProtocolTokenUser.md), [ProtocolSettingsEvents](/contracts/events/ProtocolSettingsEvents.sol/contract.ProtocolSettingsEvents.md), [ModuleCommonFunctionalities](/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains functions to customize protocol settings. + + +## Functions +### constructor + +Empty public constructor. + + +```solidity +constructor() public; +``` + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external; +``` + +### initialize + +Set function selectors on target contract. + + +```solidity +function initialize(address target) external onlyAdminOrOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The address of the target contract.| + + +### setSovrynProtocolAddress + +setting wrong address will break inter module functions calling +should be set once + + +```solidity +function setSovrynProtocolAddress(address newProtocolAddress) external onlyAdminOrOwner whenNotPaused; +``` + +### setSOVTokenAddress + + +```solidity +function setSOVTokenAddress(address newSovTokenAddress) external onlyAdminOrOwner whenNotPaused; +``` + +### setLockedSOVAddress + + +```solidity +function setLockedSOVAddress(address newLockedSOVAddress) external onlyAdminOrOwner whenNotPaused; +``` + +### setTradingRebateRewardsBasisPoint + +Set the basis point of trading rebate rewards (SOV), max value is 9999 (99.99% liquid, 0.01% vested). + + +```solidity +function setTradingRebateRewardsBasisPoint(uint256 newBasisPoint) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newBasisPoint`|`uint256`|Basis point value.| + + +### setMinReferralsToPayoutAffiliates + +Update the minimum number of referrals to get affiliates rewards. + + +```solidity +function setMinReferralsToPayoutAffiliates(uint256 newMinReferrals) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newMinReferrals`|`uint256`|The new minimum number of referrals.| + + +### setPriceFeedContract + +Set the address of the Price Feed instance. + + +```solidity +function setPriceFeedContract(address newContract) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newContract`|`address`|The address of the Price Feed new instance.| + + +### setSwapsImplContract + +Set the address of the asset swapper instance. + + +```solidity +function setSwapsImplContract(address newContract) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newContract`|`address`|The address of the asset swapper new instance.| + + +### setLoanPool + +Set a list of loan pools and its tokens. + + +```solidity +function setLoanPool(address[] calldata pools, address[] calldata assets) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`pools`|`address[]`|The array of addresses of new loan pool instances.| +|`assets`|`address[]`|The array of addresses of the corresponding underlying tokens.| + + +### setSupportedTokens + +Set a list of supported tokens by populating the +storage supportedTokens mapping. + + +```solidity +function setSupportedTokens(address[] calldata addrs, bool[] calldata toggles) + external + onlyAdminOrOwner + whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`addrs`|`address[]`|The array of addresses of the tokens.| +|`toggles`|`bool[]`|The array of flags indicating whether the corresponding token is supported or not.| + + +### setLendingFeePercent + +Set the value of lendingFeePercent storage variable. + + +```solidity +function setLendingFeePercent(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for lendingFeePercent.| + + +### setTradingFeePercent + +Set the value of tradingFeePercent storage variable. + + +```solidity +function setTradingFeePercent(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for tradingFeePercent.| + + +### setBorrowingFeePercent + +Set the value of borrowingFeePercent storage variable. + + +```solidity +function setBorrowingFeePercent(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for borrowingFeePercent.| + + +### setSwapExternalFeePercent + +Set the value of swapExtrernalFeePercent storage variable + + +```solidity +function setSwapExternalFeePercent(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|the new value for swapExternalFeePercent| + + +### setAffiliateFeePercent + +Set the value of affiliateFeePercent storage variable. + + +```solidity +function setAffiliateFeePercent(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for affiliateFeePercent.| + + +### setAffiliateTradingTokenFeePercent + +Set the value of affiliateTradingTokenFeePercent storage variable. + + +```solidity +function setAffiliateTradingTokenFeePercent(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for affiliateTradingTokenFeePercent.| + + +### setLiquidationIncentivePercent + +Set the value of liquidationIncentivePercent storage variable. + + +```solidity +function setLiquidationIncentivePercent(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for liquidationIncentivePercent.| + + +### setMaxDisagreement + +Set the value of the maximum swap spread. + + +```solidity +function setMaxDisagreement(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for maxDisagreement.| + + +### setSourceBuffer + +Set the value of the maximum source buffer. + +*To avoid rounding issues on the swap rate a small buffer is implemented.* + + +```solidity +function setSourceBuffer(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for the maximum source buffer.| + + +### setMaxSwapSize + +Set the value of the swap size limit. + + +```solidity +function setMaxSwapSize(uint256 newValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newValue`|`uint256`|The new value for the maximum swap size.| + + +### setFeesController + +Set the address of the feesController instance. + +*The fee sharing proxy must be the feesController of the +protocol contract. This allows the fee sharing proxy +to withdraw the fees.* + + +```solidity +function setFeesController(address newController) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newController`|`address`|The new address of the feesController.| + + +### setPauser + +Set the pauser address of sovryn protocol. +only pauser or owner can perform this action. + + +```solidity +function setPauser(address newPauser) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newPauser`|`address`|The new address of the pauser.| + + +### getPauser + +*Get pauser address.* + + +```solidity +function getPauser() external view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|pauser address.| + + +### setAdmin + + +```solidity +function setAdmin(address newAdmin) external onlyOwner; +``` + +### getAdmin + +*Get admin address.* + + +```solidity +function getAdmin() external view returns (address); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|admin address.| + + +### withdrawFees + +The feesController calls this function to withdraw fees +from three sources: lending, trading and borrowing. +The fees (except SOV) will be converted to wRBTC. +For SOV, it will be deposited directly to feeSharingCollector from the protocol. + + +```solidity +function withdrawFees(address[] calldata tokens, address receiver) + external + whenNotPaused + returns (uint256 totalWRBTCWithdrawn); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokens`|`address[]`|The array of address of the token instance.| +|`receiver`|`address`|The address of the withdrawal recipient.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`totalWRBTCWithdrawn`|`uint256`|The withdrawn total amount in wRBTC| + + +### withdrawLendingFees + +Will revert if disagreement found. + +The feesController calls this function to withdraw fees +accrued from lending operations. + + +```solidity +function withdrawLendingFees(address token, address receiver, uint256 amount) external whenNotPaused returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token instance.| +|`receiver`|`address`|The address of the withdrawal recipient.| +|`amount`|`uint256`|The amount of fees to get, ignored if greater than balance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Whether withdrawal was successful.| + + +### withdrawTradingFees + +The feesController calls this function to withdraw fees +accrued from trading operations. + + +```solidity +function withdrawTradingFees(address token, address receiver, uint256 amount) external whenNotPaused returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token instance.| +|`receiver`|`address`|The address of the withdrawal recipient.| +|`amount`|`uint256`|The amount of fees to get, ignored if greater than balance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Whether withdrawal was successful.| + + +### withdrawBorrowingFees + +The feesController calls this function to withdraw fees +accrued from borrowing operations. + + +```solidity +function withdrawBorrowingFees(address token, address receiver, uint256 amount) external whenNotPaused returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`address`|The address of the token instance.| +|`receiver`|`address`|The address of the withdrawal recipient.| +|`amount`|`uint256`|The amount of fees to get, ignored if greater than balance.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Whether withdrawal was successful.| + + +### withdrawProtocolToken + +The owner calls this function to withdraw protocol tokens. + +*Wrapper for ProtocolTokenUser::_withdrawProtocolToken internal function.* + + +```solidity +function withdrawProtocolToken(address receiver, uint256 amount) + external + onlyAdminOrOwner + whenNotPaused + returns (address, bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`receiver`|`address`|The address of the withdrawal recipient.| +|`amount`|`uint256`|The amount of tokens to get.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|The protocol token address.| +|``|`bool`|Withdrawal success (true/false).| + + +### depositProtocolToken + +The owner calls this function to deposit protocol tokens. + + +```solidity +function depositProtocolToken(uint256 amount) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`amount`|`uint256`|The tokens of fees to send.| + + +### getLoanPoolsList + +Get a list of loan pools. + +*Update local balance* + +*Send the tokens* + + +```solidity +function getLoanPoolsList(uint256 start, uint256 count) external view returns (bytes32[] memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`start`|`uint256`|The offset.| +|`count`|`uint256`|The limit.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bytes32[]`|The array of loan pools.| + + +### isLoanPool + +Check whether a token is a pool token. + +*By querying its underlying token.* + + +```solidity +function isLoanPool(address loanPool) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanPool`|`address`|The token address to check.| + + +### setSovrynSwapContractRegistryAddress + +Set the contract registry address of the SovrynSwap network. + + +```solidity +function setSovrynSwapContractRegistryAddress(address registryAddress) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`registryAddress`|`address`|the address of the registry contract.| + + +### setWrbtcToken + +Set the wrBTC contract address. + + +```solidity +function setWrbtcToken(address wrbtcTokenAddress) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`wrbtcTokenAddress`|`address`|The address of the wrBTC contract.| + + +### setProtocolTokenAddress + +Set the protocol token contract address. + + +```solidity +function setProtocolTokenAddress(address _protocolTokenAddress) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_protocolTokenAddress`|`address`|The address of the protocol token contract.| + + +### setRolloverBaseReward + +Set rollover base reward. It should be denominated in wrBTC. + + +```solidity +function setRolloverBaseReward(uint256 baseRewardValue) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`baseRewardValue`|`uint256`|The base reward.| + + +### setRebatePercent + +Set the fee rebate percent. + + +```solidity +function setRebatePercent(uint256 rebatePercent) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`rebatePercent`|`uint256`|The fee rebate percent.| + + +### setSpecialRebates + +Set the special fee rebate percent for specific pair + + +```solidity +function setSpecialRebates(address sourceToken, address destToken, uint256 specialRebatesPercent) + external + onlyAdminOrOwner + whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|| +|`destToken`|`address`|| +|`specialRebatesPercent`|`uint256`|The new special fee rebate percent.| + + +### getSpecialRebates + +Get a rebate percent of specific pairs. + + +```solidity +function getSpecialRebates(address sourceTokenAddress, address destTokenAddress) + external + view + returns (uint256 specialRebatesPercent); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The source of pairs.| +|`destTokenAddress`|`address`|The dest of pairs.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`specialRebatesPercent`|`uint256`|The percent rebates of the pairs.| + + +### getProtocolAddress + + +```solidity +function getProtocolAddress() external view returns (address); +``` + +### getSovTokenAddress + + +```solidity +function getSovTokenAddress() external view returns (address); +``` + +### getLockedSOVAddress + + +```solidity +function getLockedSOVAddress() external view returns (address); +``` + +### getFeeRebatePercent + + +```solidity +function getFeeRebatePercent() external view returns (uint256); +``` + +### togglePaused + + +```solidity +function togglePaused(bool paused) external onlyPauserOrOwner; +``` + +### isProtocolPaused + + +```solidity +function isProtocolPaused() external view returns (bool); +``` + +### getSwapExternalFeePercent + + +```solidity +function getSwapExternalFeePercent() external view returns (uint256); +``` + +### getTradingRebateRewardsBasisPoint + +Get the basis point of trading rebate rewards. + + +```solidity +function getTradingRebateRewardsBasisPoint() external view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The basis point value.| + + +### getDedicatedSOVRebate + +If SOV balance is less than the fees held, it will return 0. + +*Get how much SOV that is dedicated to pay the trading rebate rewards.* + + +```solidity +function getDedicatedSOVRebate() public view returns (uint256); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|total dedicated SOV.| + + +### setRolloverFlexFeePercent + +Set rolloverFlexFeePercent (max value is 1%) + + +```solidity +function setRolloverFlexFeePercent(uint256 newRolloverFlexFeePercent) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newRolloverFlexFeePercent`|`uint256`|uint256 value of new rollover flex fee percentage (0.1 ether = 0.1%)| + + +### getDefaultPathConversion + +*Get default path conversion for pairs.* + + +```solidity +function getDefaultPathConversion(address sourceTokenAddress, address destTokenAddress) + external + view + returns (IERC20[] memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|source token address.| +|`destTokenAddress`|`address`|destination token address.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`IERC20[]`|default path of the conversion.| + + +### setDefaultPathConversion + +*Set default path conversion for pairs.* + + +```solidity +function setDefaultPathConversion(IERC20[] calldata defaultPath) external onlyAdminOrOwner whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`defaultPath`|`IERC20[]`|array of addresses for the default path.| + + +### removeDefaultPathConversion + +*Remove the default path conversion for pairs* + + +```solidity +function removeDefaultPathConversion(address sourceTokenAddress, address destTokenAddress) + external + onlyAdminOrOwner + whenNotPaused; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|source token address.| +|`destTokenAddress`|`address`|destination token address| + + diff --git a/foundry/docs/src/contracts/modules/README.md b/foundry/docs/src/contracts/modules/README.md new file mode 100644 index 000000000..f71c53f3c --- /dev/null +++ b/foundry/docs/src/contracts/modules/README.md @@ -0,0 +1,15 @@ + + +# Contents +- [interfaces](/contracts/modules/interfaces) +- [Affiliates](Affiliates.sol/contract.Affiliates.md) +- [LoanClosingsLiquidation](LoanClosingsLiquidation.sol/contract.LoanClosingsLiquidation.md) +- [LoanClosingsRollover](LoanClosingsRollover.sol/contract.LoanClosingsRollover.md) +- [LoanClosingsShared](LoanClosingsShared.sol/contract.LoanClosingsShared.md) +- [LoanClosingsWith](LoanClosingsWith.sol/contract.LoanClosingsWith.md) +- [LoanMaintenance](LoanMaintenance.sol/contract.LoanMaintenance.md) +- [LoanOpenings](LoanOpenings.sol/contract.LoanOpenings.md) +- [LoanSettings](LoanSettings.sol/contract.LoanSettings.md) +- [ProtocolSettings](ProtocolSettings.sol/contract.ProtocolSettings.md) +- [SwapsExternal](SwapsExternal.sol/contract.SwapsExternal.md) +- [SwapsImplSovrynSwapModule](SwapsImplSovrynSwapModule.sol/contract.SwapsImplSovrynSwapModule.md) diff --git a/foundry/docs/src/contracts/modules/SwapsExternal.sol/contract.SwapsExternal.md b/foundry/docs/src/contracts/modules/SwapsExternal.sol/contract.SwapsExternal.md new file mode 100644 index 000000000..825b8404c --- /dev/null +++ b/foundry/docs/src/contracts/modules/SwapsExternal.sol/contract.SwapsExternal.md @@ -0,0 +1,149 @@ +# SwapsExternal +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/SwapsExternal.sol) + +**Inherits:** +[VaultController](/contracts/mixins/VaultController.sol/contract.VaultController.md), [SwapsUser](/contracts/swaps/SwapsUser.sol/contract.SwapsUser.md), [ModuleCommonFunctionalities](/contracts/mixins/ModuleCommonFunctionalities.sol/contract.ModuleCommonFunctionalities.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains functions to calculate and execute swaps. + + +## Functions +### constructor + +Empty public constructor. + + +```solidity +constructor() public; +``` + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external; +``` + +### initialize + +Set function selectors on target contract. + + +```solidity +function initialize(address target) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The address of the target contract.| + + +### swapExternal + +Perform a swap w/ tokens or rBTC as source currency. + +*External wrapper that calls SwapsUser::_swapsCall +after turning potential incoming rBTC into wrBTC tokens.* + + +```solidity +function swapExternal( + address sourceToken, + address destToken, + address receiver, + address returnToSender, + uint256 sourceTokenAmount, + uint256 requiredDestTokenAmount, + uint256 minReturn, + bytes memory swapData +) public payable nonReentrant whenNotPaused returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source token instance.| +|`destToken`|`address`|The address of the destiny token instance.| +|`receiver`|`address`|The address of the recipient account.| +|`returnToSender`|`address`|The address of the sender account.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens.| +|`requiredDestTokenAmount`|`uint256`|The amount of required destiny tokens.| +|`minReturn`|`uint256`|Minimum amount (position size) in the collateral tokens.| +|`swapData`|`bytes`|Additional swap data (not in use yet).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`destTokenAmountReceived`|`uint256`|The amount of destiny tokens sent.| +|`sourceTokenAmountUsed`|`uint256`|The amount of source tokens spent.| + + +### getSwapExpectedReturn + +Get the swap expected return value. + +*Get payed value, be it rBTC or tokenized.* + +*Update wrBTC balance for this contract.* + +*Perform the swap w/ tokens. +user +minSourceTokenAmount +maxSourceTokenAmount +loanId (not tied to a specific loan) +bypassFee +user* + +*External wrapper that calls SwapsUser::_swapsExpectedReturn* + + +```solidity +function getSwapExpectedReturn(address sourceToken, address destToken, uint256 sourceTokenAmount) + external + view + returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source token instance.| +|`destToken`|`address`|The address of the destiny token instance.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The expected return value.| + + +### checkPriceDivergence + +Check the slippage based on the swapExpectedReturn. + + +```solidity +function checkPriceDivergence(address sourceToken, address destToken, uint256 sourceTokenAmount, uint256 minReturn) + public + view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source token instance.| +|`destToken`|`address`|The address of the destiny token instance.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens.| +|`minReturn`|`uint256`|The amount (max slippage) that will be compared to the swapsExpectedReturn.| + + diff --git a/foundry/docs/src/contracts/modules/SwapsImplSovrynSwapModule.sol/contract.SwapsImplSovrynSwapModule.md b/foundry/docs/src/contracts/modules/SwapsImplSovrynSwapModule.sol/contract.SwapsImplSovrynSwapModule.md new file mode 100644 index 000000000..3a84df95a --- /dev/null +++ b/foundry/docs/src/contracts/modules/SwapsImplSovrynSwapModule.sol/contract.SwapsImplSovrynSwapModule.md @@ -0,0 +1,117 @@ +# SwapsImplSovrynSwapModule +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/SwapsImplSovrynSwapModule.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md), [ModulesCommonEvents](/contracts/events/ModulesCommonEvents.sol/contract.ModulesCommonEvents.md) + + +## Functions +### constructor + +Empty public constructor. + + +```solidity +constructor() public; +``` + +### function + +Fallback function is to react to receiving value (rBTC). + + +```solidity +function() external; +``` + +### initialize + +Set function selectors on target contract. + + +```solidity +function initialize(address target) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`target`|`address`|The address of the target contract.| + + +### getContractHexName + +Get the hex name of a contract. + + +```solidity +function getContractHexName(string memory source) public pure returns (bytes32 result); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`source`|`string`|The name of the contract.| + + +### getSovrynSwapNetworkContract + +Look up the Sovryn swap network contract registered at the given address. + + +```solidity +function getSovrynSwapNetworkContract(address sovrynSwapRegistryAddress) public view returns (ISovrynSwapNetwork); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sovrynSwapRegistryAddress`|`address`|The address of the registry.| + + +### swapsImplExpectedRate + +Get the expected rate for 1 source token when exchanging the +given amount of source tokens. + + +```solidity +function swapsImplExpectedRate(address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) + external + view + returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token contract.| +|`destTokenAddress`|`address`|The address of the destination token contract.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens to get the rate for.| + + +### swapsImplExpectedReturn + +Get the expected return amount when exchanging the given +amount of source tokens. + +Right now, this function is being called directly by _swapsExpectedReturn from the protocol +So, this function is not using _getConversionPath function since it will try to read the defaultPath storage which is stored in the protocol's slot, and it will cause an issue for direct call. +Instead, this function is accepting additional parameters called defaultPath which value can be declared by the caller (protocol in this case). + + +```solidity +function swapsImplExpectedReturn(address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) + external + view + returns (uint256 expectedReturn); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token contract.| +|`destTokenAddress`|`address`|The address of the destination token contract.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens to get the return for.| + + diff --git a/foundry/docs/src/contracts/modules/interfaces/ProtocolAffiliatesInterface.sol/interface.ProtocolAffiliatesInterface.md b/foundry/docs/src/contracts/modules/interfaces/ProtocolAffiliatesInterface.sol/interface.ProtocolAffiliatesInterface.md new file mode 100644 index 000000000..01824dde5 --- /dev/null +++ b/foundry/docs/src/contracts/modules/interfaces/ProtocolAffiliatesInterface.sol/interface.ProtocolAffiliatesInterface.md @@ -0,0 +1,38 @@ +# ProtocolAffiliatesInterface +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/interfaces/ProtocolAffiliatesInterface.sol) + +Copyright 2020, Denis Savelev. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### setAffiliatesReferrer + + +```solidity +function setAffiliatesReferrer(address user, address referrer) external; +``` + +### setUserNotFirstTradeFlag + + +```solidity +function setUserNotFirstTradeFlag(address user_) external; +``` + +### getUserNotFirstTradeFlag + + +```solidity +function getUserNotFirstTradeFlag(address user_) external returns (bool); +``` + +### payTradingFeeToAffiliatesReferrer + + +```solidity +function payTradingFeeToAffiliatesReferrer(address affiliate, address trader, address token, uint256 amount) + external + returns (uint256 affiliatesBonusSOVAmount, uint256 affiliatesBonusTokenAmount); +``` + diff --git a/foundry/docs/src/contracts/modules/interfaces/ProtocolSwapExternalInterface.sol/interface.ProtocolSwapExternalInterface.md b/foundry/docs/src/contracts/modules/interfaces/ProtocolSwapExternalInterface.sol/interface.ProtocolSwapExternalInterface.md new file mode 100644 index 000000000..34578d9fa --- /dev/null +++ b/foundry/docs/src/contracts/modules/interfaces/ProtocolSwapExternalInterface.sol/interface.ProtocolSwapExternalInterface.md @@ -0,0 +1,24 @@ +# ProtocolSwapExternalInterface +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/modules/interfaces/ProtocolSwapExternalInterface.sol) + +Copyright 2020, Denis Savelev. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### swapExternal + + +```solidity +function swapExternal( + address sourceToken, + address destToken, + address receiver, + address returnToSender, + uint256 sourceTokenAmount, + uint256 requiredDestTokenAmount, + uint256 minReturn, + bytes calldata swapData +) external returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); +``` + diff --git a/foundry/docs/src/contracts/modules/interfaces/README.md b/foundry/docs/src/contracts/modules/interfaces/README.md new file mode 100644 index 000000000..790a4cde9 --- /dev/null +++ b/foundry/docs/src/contracts/modules/interfaces/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [ProtocolAffiliatesInterface](ProtocolAffiliatesInterface.sol/interface.ProtocolAffiliatesInterface.md) +- [ProtocolSwapExternalInterface](ProtocolSwapExternalInterface.sol/interface.ProtocolSwapExternalInterface.md) diff --git a/foundry/docs/src/contracts/multisig/MultiSigKeyHolders.sol/contract.MultiSigKeyHolders.md b/foundry/docs/src/contracts/multisig/MultiSigKeyHolders.sol/contract.MultiSigKeyHolders.md new file mode 100644 index 000000000..2a98665b6 --- /dev/null +++ b/foundry/docs/src/contracts/multisig/MultiSigKeyHolders.sol/contract.MultiSigKeyHolders.md @@ -0,0 +1,440 @@ +# MultiSigKeyHolders +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/multisig/MultiSigKeyHolders.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + + +## State Variables +### MAX_OWNER_COUNT + +```solidity +uint256 public constant MAX_OWNER_COUNT = 50; +``` + + +### ERROR_INVALID_ADDRESS + +```solidity +string private constant ERROR_INVALID_ADDRESS = "Invalid address"; +``` + + +### ERROR_INVALID_REQUIRED + +```solidity +string private constant ERROR_INVALID_REQUIRED = "Invalid required"; +``` + + +### isEthereumAddressAdded +Flag and index for Ethereum address. + + +```solidity +mapping(address => Data) private isEthereumAddressAdded; +``` + + +### ethereumAddresses +List of Ethereum addresses. + + +```solidity +address[] private ethereumAddresses; +``` + + +### ethereumRequired +Required number of signatures for the Ethereum multisig. + + +```solidity +uint256 public ethereumRequired = 2; +``` + + +### isBitcoinAddressAdded +Flag and index for Bitcoin address. + + +```solidity +mapping(string => Data) private isBitcoinAddressAdded; +``` + + +### bitcoinAddresses +List of Bitcoin addresses. + + +```solidity +string[] private bitcoinAddresses; +``` + + +### bitcoinRequired +Required number of signatures for the Bitcoin multisig. + + +```solidity +uint256 public bitcoinRequired = 2; +``` + + +## Functions +### validRequirement + + +```solidity +modifier validRequirement(uint256 ownerCount, uint256 _required); +``` + +### addEthereumAddress + +Add rBTC address to the key holders. + + +```solidity +function addEthereumAddress(address _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`address`|The address to be added.| + + +### addEthereumAddresses + +Add rBTC addresses to the key holders. + + +```solidity +function addEthereumAddresses(address[] memory _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`address[]`|The addresses to be added.| + + +### _addEthereumAddress + +Internal function to add rBTC address to the key holders. + + +```solidity +function _addEthereumAddress(address _address) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`address`|The address to be added.| + + +### removeEthereumAddress + +Remove rBTC address to the key holders. + + +```solidity +function removeEthereumAddress(address _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`address`|The address to be removed.| + + +### removeEthereumAddresses + +Remove rBTC addresses to the key holders. + + +```solidity +function removeEthereumAddresses(address[] memory _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`address[]`|The addresses to be removed.| + + +### _removeEthereumAddress + +Internal function to remove rBTC address to the key holders. + + +```solidity +function _removeEthereumAddress(address _address) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`address`|The address to be removed.| + + +### isEthereumAddressOwner + +Get whether rBTC address is a key holder. + + +```solidity +function isEthereumAddressOwner(address _address) public view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`address`|The rBTC address to be checked.| + + +### getEthereumAddresses + +Get array of rBTC key holders. + + +```solidity +function getEthereumAddresses() public view returns (address[] memory); +``` + +### changeEthereumRequirement + +Set flag ethereumRequired to true/false. + + +```solidity +function changeEthereumRequirement(uint256 _required) + public + onlyOwner + validRequirement(ethereumAddresses.length, _required); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_required`|`uint256`|The new value of the ethereumRequired flag.| + + +### addBitcoinAddress + +Add bitcoin address to the key holders. + + +```solidity +function addBitcoinAddress(string memory _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`string`|The address to be added.| + + +### addBitcoinAddresses + +Add bitcoin addresses to the key holders. + + +```solidity +function addBitcoinAddresses(string[] memory _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`string[]`|The addresses to be added.| + + +### _addBitcoinAddress + +Internal function to add bitcoin address to the key holders. + + +```solidity +function _addBitcoinAddress(string memory _address) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`string`|The address to be added.| + + +### removeBitcoinAddress + +Remove bitcoin address to the key holders. + + +```solidity +function removeBitcoinAddress(string memory _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`string`|The address to be removed.| + + +### removeBitcoinAddresses + +Remove bitcoin addresses to the key holders. + + +```solidity +function removeBitcoinAddresses(string[] memory _address) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`string[]`|The addresses to be removed.| + + +### _removeBitcoinAddress + +Internal function to remove bitcoin address to the key holders. + + +```solidity +function _removeBitcoinAddress(string memory _address) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`string`|The address to be removed.| + + +### isBitcoinAddressOwner + +Get whether bitcoin address is a key holder. + + +```solidity +function isBitcoinAddressOwner(string memory _address) public view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_address`|`string`|The bitcoin address to be checked.| + + +### getBitcoinAddresses + +Get array of bitcoin key holders. + + +```solidity +function getBitcoinAddresses() public view returns (string[] memory); +``` + +### changeBitcoinRequirement + +Set flag bitcoinRequired to true/false. + + +```solidity +function changeBitcoinRequirement(uint256 _required) + public + onlyOwner + validRequirement(bitcoinAddresses.length, _required); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_required`|`uint256`|The new value of the bitcoinRequired flag.| + + +### addEthereumAndBitcoinAddresses + +Add rBTC and bitcoin addresses to the key holders. + + +```solidity +function addEthereumAndBitcoinAddresses(address[] memory _ethereumAddress, string[] memory _bitcoinAddress) + public + onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_ethereumAddress`|`address[]`|the rBTC addresses to be added.| +|`_bitcoinAddress`|`string[]`|the bitcoin addresses to be added.| + + +### removeEthereumAndBitcoinAddresses + +Remove rBTC and bitcoin addresses to the key holders. + + +```solidity +function removeEthereumAndBitcoinAddresses(address[] memory _ethereumAddress, string[] memory _bitcoinAddress) + public + onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_ethereumAddress`|`address[]`|The rBTC addresses to be removed.| +|`_bitcoinAddress`|`string[]`|The bitcoin addresses to be removed.| + + +## Events +### EthereumAddressAdded + +```solidity +event EthereumAddressAdded(address indexed account); +``` + +### EthereumAddressRemoved + +```solidity +event EthereumAddressRemoved(address indexed account); +``` + +### EthereumRequirementChanged + +```solidity +event EthereumRequirementChanged(uint256 required); +``` + +### BitcoinAddressAdded + +```solidity +event BitcoinAddressAdded(string account); +``` + +### BitcoinAddressRemoved + +```solidity +event BitcoinAddressRemoved(string account); +``` + +### BitcoinRequirementChanged + +```solidity +event BitcoinRequirementChanged(uint256 required); +``` + +## Structs +### Data +Helps removing items from array. + + +```solidity +struct Data { + bool added; + uint248 index; +} +``` + diff --git a/foundry/docs/src/contracts/multisig/MultiSigWallet.sol/contract.MultiSigWallet.md b/foundry/docs/src/contracts/multisig/MultiSigWallet.sol/contract.MultiSigWallet.md new file mode 100644 index 000000000..e080cd8f3 --- /dev/null +++ b/foundry/docs/src/contracts/multisig/MultiSigWallet.sol/contract.MultiSigWallet.md @@ -0,0 +1,560 @@ +# MultiSigWallet +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/multisig/MultiSigWallet.sol) + +**Author:** +Stefan George - + + +## State Variables +### MAX_OWNER_COUNT + +```solidity +uint256 public constant MAX_OWNER_COUNT = 50; +``` + + +### transactions + +```solidity +mapping(uint256 => Transaction) public transactions; +``` + + +### confirmations + +```solidity +mapping(uint256 => mapping(address => bool)) public confirmations; +``` + + +### isOwner + +```solidity +mapping(address => bool) public isOwner; +``` + + +### owners + +```solidity +address[] public owners; +``` + + +### required + +```solidity +uint256 public required; +``` + + +### transactionCount + +```solidity +uint256 public transactionCount; +``` + + +## Functions +### onlyWallet + + +```solidity +modifier onlyWallet(); +``` + +### ownerDoesNotExist + + +```solidity +modifier ownerDoesNotExist(address owner); +``` + +### ownerExists + + +```solidity +modifier ownerExists(address owner); +``` + +### transactionExists + + +```solidity +modifier transactionExists(uint256 transactionId); +``` + +### confirmed + + +```solidity +modifier confirmed(uint256 transactionId, address owner); +``` + +### notConfirmed + + +```solidity +modifier notConfirmed(uint256 transactionId, address owner); +``` + +### notExecuted + + +```solidity +modifier notExecuted(uint256 transactionId); +``` + +### notNull + + +```solidity +modifier notNull(address _address); +``` + +### validRequirement + + +```solidity +modifier validRequirement(uint256 ownerCount, uint256 _required); +``` + +### function + +Fallback function allows to deposit ether. + + +```solidity +function() external payable; +``` + +### constructor + +Contract constructor sets initial owners and required number +of confirmations. + + +```solidity +constructor(address[] memory _owners, uint256 _required) public validRequirement(_owners.length, _required); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owners`|`address[]`|List of initial owners.| +|`_required`|`uint256`|Number of required confirmations.| + + +### addOwner + +Allows to add a new owner. Transaction has to be sent by wallet. + + +```solidity +function addOwner(address owner) + public + onlyWallet + ownerDoesNotExist(owner) + notNull(owner) + validRequirement(owners.length + 1, required); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`owner`|`address`|Address of new owner.| + + +### removeOwner + +Allows to remove an owner. Transaction has to be sent by wallet. + + +```solidity +function removeOwner(address owner) public onlyWallet ownerExists(owner); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`owner`|`address`|Address of owner.| + + +### replaceOwner + +Allows to replace an owner with a new owner. Transaction has +to be sent by wallet. + + +```solidity +function replaceOwner(address owner, address newOwner) + public + onlyWallet + ownerExists(owner) + ownerDoesNotExist(newOwner); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`owner`|`address`|Address of owner to be replaced.| +|`newOwner`|`address`|Address of new owner.| + + +### changeRequirement + +Allows to change the number of required confirmations. +Transaction has to be sent by wallet. + + +```solidity +function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_required`|`uint256`|Number of required confirmations.| + + +### submitTransaction + +Allows an owner to submit and confirm a transaction. + + +```solidity +function submitTransaction(address destination, uint256 value, bytes memory data) + public + returns (uint256 transactionId); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`destination`|`address`|Transaction target address.| +|`value`|`uint256`|Transaction ether value.| +|`data`|`bytes`|Transaction data payload.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Returns transaction ID.| + + +### confirmTransaction + +Allows an owner to confirm a transaction. + + +```solidity +function confirmTransaction(uint256 transactionId) + public + ownerExists(msg.sender) + transactionExists(transactionId) + notConfirmed(transactionId, msg.sender); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Transaction ID.| + + +### revokeConfirmation + +Allows an owner to revoke a confirmation for a transaction. + + +```solidity +function revokeConfirmation(uint256 transactionId) + public + ownerExists(msg.sender) + confirmed(transactionId, msg.sender) + notExecuted(transactionId); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Transaction ID.| + + +### executeTransaction + +Allows anyone to execute a confirmed transaction. + + +```solidity +function executeTransaction(uint256 transactionId) + public + ownerExists(msg.sender) + confirmed(transactionId, msg.sender) + notExecuted(transactionId); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Transaction ID.| + + +### external_call + +Low level transaction execution. + +*Call has been separated into its own function in order to +take advantage of the Solidity's code generator to produce a +loop that copies tx.data into memory.* + + +```solidity +function external_call(address destination, uint256 value, uint256 dataLength, bytes memory data) + internal + returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`destination`|`address`|The address of the Smart Contract to call.| +|`value`|`uint256`|The amout of rBTC to send w/ the transaction.| +|`dataLength`|`uint256`|The size of the payload.| +|`data`|`bytes`|The payload.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Success or failure.| + + +### isConfirmed + +"Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) +First 32 bytes are the padded length of data, so exclude that +34710 is the value that solidity is currently emitting +It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + +callNewAccountGas (25000, in case the destination address does not exist and needs creating) +Size of the input (in bytes) - this is what fixes the padding problem +Output is ignored, therefore the output size is zero + +Returns the confirmation status of a transaction. + + +```solidity +function isConfirmed(uint256 transactionId) public view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Transaction ID.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|Confirmation status.| + + +### addTransaction + +Adds a new transaction to the transaction mapping, +if transaction does not exist yet. + + +```solidity +function addTransaction(address destination, uint256 value, bytes memory data) + internal + notNull(destination) + returns (uint256 transactionId); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`destination`|`address`|Transaction target address.| +|`value`|`uint256`|Transaction ether value.| +|`data`|`bytes`|Transaction data payload.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Returns transaction ID.| + + +### getConfirmationCount + +Get the number of confirmations of a transaction. + + +```solidity +function getConfirmationCount(uint256 transactionId) public view returns (uint256 count); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Transaction ID.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`count`|`uint256`|Number of confirmations.| + + +### getTransactionCount + +Get the total number of transactions after filers are applied. + + +```solidity +function getTransactionCount(bool pending, bool executed) public view returns (uint256 count); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`pending`|`bool`|Include pending transactions.| +|`executed`|`bool`|Include executed transactions.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`count`|`uint256`|Total number of transactions after filters are applied.| + + +### getOwners + +Get the list of owners. + + +```solidity +function getOwners() public view returns (address[] memory); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address[]`|List of owner addresses.| + + +### getConfirmations + +Get the array with owner addresses, which confirmed transaction. + + +```solidity +function getConfirmations(uint256 transactionId) public view returns (address[] memory _confirmations); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`transactionId`|`uint256`|Transaction ID.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_confirmations`|`address[]`|Returns array of owner addresses.| + + +### getTransactionIds + +Get the list of transaction IDs in defined range. + + +```solidity +function getTransactionIds(uint256 from, uint256 to, bool pending, bool executed) + public + view + returns (uint256[] memory _transactionIds); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`from`|`uint256`|Index start position of transaction array.| +|`to`|`uint256`|Index end position of transaction array.| +|`pending`|`bool`|Include pending transactions.| +|`executed`|`bool`|Include executed transactions.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_transactionIds`|`uint256[]`|Returns array of transaction IDs.| + + +## Events +### Confirmation + +```solidity +event Confirmation(address indexed sender, uint256 indexed transactionId); +``` + +### Revocation + +```solidity +event Revocation(address indexed sender, uint256 indexed transactionId); +``` + +### Submission + +```solidity +event Submission(uint256 indexed transactionId); +``` + +### Execution + +```solidity +event Execution(uint256 indexed transactionId); +``` + +### ExecutionFailure + +```solidity +event ExecutionFailure(uint256 indexed transactionId); +``` + +### Deposit + +```solidity +event Deposit(address indexed sender, uint256 value); +``` + +### OwnerAddition + +```solidity +event OwnerAddition(address indexed owner); +``` + +### OwnerRemoval + +```solidity +event OwnerRemoval(address indexed owner); +``` + +### RequirementChange + +```solidity +event RequirementChange(uint256 required); +``` + +## Structs +### Transaction + +```solidity +struct Transaction { + address destination; + uint256 value; + bytes data; + bool executed; +} +``` + diff --git a/foundry/docs/src/contracts/multisig/README.md b/foundry/docs/src/contracts/multisig/README.md new file mode 100644 index 000000000..aa79f8aa6 --- /dev/null +++ b/foundry/docs/src/contracts/multisig/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [MultiSigKeyHolders](MultiSigKeyHolders.sol/contract.MultiSigKeyHolders.md) +- [MultiSigWallet](MultiSigWallet.sol/contract.MultiSigWallet.md) diff --git a/foundry/docs/src/contracts/openzeppelin/Address.sol/library.Address.md b/foundry/docs/src/contracts/openzeppelin/Address.sol/library.Address.md new file mode 100644 index 000000000..76a81c1a5 --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/Address.sol/library.Address.md @@ -0,0 +1,59 @@ +# Address +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/Address.sol) + +*Collection of functions related to the address type* + + +## Functions +### isContract + +*Returns true if `account` is a contract. +[IMPORTANT] +==== +It is unsafe to assume that an address for which this function returns +false is an externally-owned account (EOA) and not a contract. +Among others, `isContract` will return false for the following +types of addresses: +- an externally-owned account +- a contract in construction +- an address where a contract will be created +- an address where a contract lived, but was destroyed +====* + + +```solidity +function isContract(address account) internal view returns (bool); +``` + +### toPayable + +*Converts an `address` into `address payable`. Note that this is +simply a type cast: the actual underlying value is not changed. +_Available since v2.4.0._* + + +```solidity +function toPayable(address account) internal pure returns (address payable); +``` + +### sendValue + +*Replacement for Solidity's `transfer`: sends `amount` wei to +`recipient`, forwarding all available gas and reverting on errors. +https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost +of certain opcodes, possibly making contracts go over the 2300 gas limit +imposed by `transfer`, making them unable to receive funds via +`transfer`. [sendValue](/contracts/openzeppelin/Address.sol/library.Address.md#sendvalue) removes this limitation. +https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. +IMPORTANT: because control is transferred to `recipient`, care must be +taken to not create reentrancy vulnerabilities. Consider using +{ReentrancyGuard} or the +https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html +#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. +_Available since v2.4.0._* + + +```solidity +function sendValue(address recipient, uint256 amount) internal; +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/Context.sol/contract.Context.md b/foundry/docs/src/contracts/openzeppelin/Context.sol/contract.Context.md new file mode 100644 index 000000000..5f997ce7a --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/Context.sol/contract.Context.md @@ -0,0 +1,26 @@ +# Context +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/Context.sol) + + +## Functions +### constructor + + +```solidity +constructor() internal; +``` + +### _msgSender + + +```solidity +function _msgSender() internal view returns (address payable); +``` + +### _msgData + + +```solidity +function _msgData() internal view returns (bytes memory); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/ERC20.sol/contract.ERC20.md b/foundry/docs/src/contracts/openzeppelin/ERC20.sol/contract.ERC20.md new file mode 100644 index 000000000..c9750d0f4 --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/ERC20.sol/contract.ERC20.md @@ -0,0 +1,213 @@ +# ERC20 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/ERC20.sol) + +**Inherits:** +[Context](/contracts/openzeppelin/Context.sol/contract.Context.md), [IERC20_](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md) + +*Implementation of the {IERC20} interface. +This implementation is agnostic to the way tokens are created. This means +that a supply mechanism has to be added in a derived contract using {_mint}. +For a generic mechanism see {ERC20Mintable}. +TIP: For a detailed writeup see our guide +https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How +to implement supply mechanisms]. +We have followed general OpenZeppelin guidelines: functions revert instead +of returning `false` on failure. This behavior is nonetheless conventional +and does not conflict with the expectations of ERC20 applications. +Additionally, an {Approval} event is emitted on calls to {transferFrom}. +This allows applications to reconstruct the allowance for all accounts just +by listening to said events. Other implementations of the EIP may not emit +these events, as it isn't required by the specification. +Finally, the non-standard {decreaseAllowance} and {increaseAllowance} +functions have been added to mitigate the well-known issues around setting +allowances. See {IERC20-approve}.* + + +## State Variables +### _balances + +```solidity +mapping(address => uint256) private _balances; +``` + + +### _allowances + +```solidity +mapping(address => mapping(address => uint256)) private _allowances; +``` + + +### _totalSupply + +```solidity +uint256 private _totalSupply; +``` + + +## Functions +### totalSupply + +*See [IERC20-totalSupply](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#totalsupply).* + + +```solidity +function totalSupply() public view returns (uint256); +``` + +### balanceOf + +*See [IERC20-balanceOf](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#balanceof).* + + +```solidity +function balanceOf(address account) public view returns (uint256); +``` + +### transfer + +*See [IERC20-transfer](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#transfer). +Requirements: +- `recipient` cannot be the zero address. +- the caller must have a balance of at least `amount`.* + + +```solidity +function transfer(address recipient, uint256 amount) public returns (bool); +``` + +### allowance + +*See [IERC20-allowance](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#allowance).* + + +```solidity +function allowance(address owner, address spender) public view returns (uint256); +``` + +### approve + +*See [IERC20-approve](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#approve). +Requirements: +- `spender` cannot be the zero address.* + + +```solidity +function approve(address spender, uint256 amount) public returns (bool); +``` + +### transferFrom + +*See [IERC20-transferFrom](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#transferfrom). +Emits an {Approval} event indicating the updated allowance. This is not +required by the EIP. See the note at the beginning of {ERC20}; +Requirements: +- `sender` and `recipient` cannot be the zero address. +- `sender` must have a balance of at least `amount`. +- the caller must have allowance for `sender`'s tokens of at least +`amount`.* + + +```solidity +function transferFrom(address sender, address recipient, uint256 amount) public returns (bool); +``` + +### increaseAllowance + +*Atomically increases the allowance granted to `spender` by the caller. +This is an alternative to [approve](/contracts/openzeppelin/ERC20.sol/contract.ERC20.md#approve) that can be used as a mitigation for +problems described in {IERC20-approve}. +Emits an {Approval} event indicating the updated allowance. +Requirements: +- `spender` cannot be the zero address.* + + +```solidity +function increaseAllowance(address spender, uint256 addedValue) public returns (bool); +``` + +### decreaseAllowance + +*Atomically decreases the allowance granted to `spender` by the caller. +This is an alternative to [approve](/contracts/openzeppelin/ERC20.sol/contract.ERC20.md#approve) that can be used as a mitigation for +problems described in {IERC20-approve}. +Emits an {Approval} event indicating the updated allowance. +Requirements: +- `spender` cannot be the zero address. +- `spender` must have allowance for the caller of at least +`subtractedValue`.* + + +```solidity +function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); +``` + +### _transfer + +*Moves tokens `amount` from `sender` to `recipient`. +This is internal function is equivalent to [transfer](/contracts/openzeppelin/ERC20.sol/contract.ERC20.md#transfer), and can be used to +e.g. implement automatic token fees, slashing mechanisms, etc. +Emits a {Transfer} event. +Requirements: +- `sender` cannot be the zero address. +- `recipient` cannot be the zero address. +- `sender` must have a balance of at least `amount`.* + + +```solidity +function _transfer(address sender, address recipient, uint256 amount) internal; +``` + +### _mint + +*Creates `amount` tokens and assigns them to `account`, increasing +the total supply. +Emits a {Transfer} event with `from` set to the zero address. +Requirements +- `to` cannot be the zero address.* + + +```solidity +function _mint(address account, uint256 amount) internal; +``` + +### _burn + +*Destroys `amount` tokens from `account`, reducing the +total supply. +Emits a {Transfer} event with `to` set to the zero address. +Requirements +- `account` cannot be the zero address. +- `account` must have at least `amount` tokens.* + + +```solidity +function _burn(address account, uint256 amount) internal; +``` + +### _approve + +*Sets `amount` as the allowance of `spender` over the `owner`s tokens. +This is internal function is equivalent to `approve`, and can be used to +e.g. set automatic allowances for certain subsystems, etc. +Emits an {Approval} event. +Requirements: +- `owner` cannot be the zero address. +- `spender` cannot be the zero address.* + + +```solidity +function _approve(address owner, address spender, uint256 amount) internal; +``` + +### _burnFrom + +*Destroys `amount` tokens from `account`.`amount` is then deducted +from the caller's allowance. +See [_burn](/contracts/openzeppelin/ERC20.sol/contract.ERC20.md#_burn) and {_approve}.* + + +```solidity +function _burnFrom(address account, uint256 amount) internal; +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/ERC20Detailed.sol/contract.ERC20Detailed.md b/foundry/docs/src/contracts/openzeppelin/ERC20Detailed.sol/contract.ERC20Detailed.md new file mode 100644 index 000000000..6596566b2 --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/ERC20Detailed.sol/contract.ERC20Detailed.md @@ -0,0 +1,78 @@ +# ERC20Detailed +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/ERC20Detailed.sol) + +**Inherits:** +[IERC20_](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md) + +*Optional functions from the ERC20 standard.* + + +## State Variables +### _name + +```solidity +string private _name; +``` + + +### _symbol + +```solidity +string private _symbol; +``` + + +### _decimals + +```solidity +uint8 private _decimals; +``` + + +## Functions +### constructor + +*Sets the values for `name`, `symbol`, and `decimals`. All three of +these values are immutable: they can only be set once during +construction.* + + +```solidity +constructor(string memory name, string memory symbol, uint8 decimals) public; +``` + +### name + +*Returns the name of the token.* + + +```solidity +function name() public view returns (string memory); +``` + +### symbol + +*Returns the symbol of the token, usually a shorter version of the +name.* + + +```solidity +function symbol() public view returns (string memory); +``` + +### decimals + +*Returns the number of decimals used to get its user representation. +For example, if `decimals` equals `2`, a balance of `505` tokens should +be displayed to a user as `5,05` (`505 / 10 ** 2`). +Tokens usually opt for a value of 18, imitating the relationship between +Ether and Wei. +NOTE: This information is only used for _display_ purposes: it in +no way affects any of the arithmetic of the contract, including +[IERC20-balanceOf](/contracts/interfaces/IERC20.sol/contract.IERC20.md#balanceof) and {IERC20-transfer}.* + + +```solidity +function decimals() public view returns (uint8); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md b/foundry/docs/src/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md new file mode 100644 index 000000000..67e6b602d --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md @@ -0,0 +1,99 @@ +# IERC20_ +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/IERC20_.sol) + +*Interface of the ERC20 standard as defined in the EIP. Does not include +the optional functions; to access them see {ERC20Detailed}.* + + +## Functions +### totalSupply + +*Returns the amount of tokens in existence.* + + +```solidity +function totalSupply() external view returns (uint256); +``` + +### balanceOf + +*Returns the amount of tokens owned by `account`.* + + +```solidity +function balanceOf(address account) external view returns (uint256); +``` + +### transfer + +*Moves `amount` tokens from the caller's account to `recipient`. +Returns a boolean value indicating whether the operation succeeded. +Emits a [Transfer](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#transfer) event.* + + +```solidity +function transfer(address recipient, uint256 amount) external returns (bool); +``` + +### allowance + +*Returns the remaining number of tokens that `spender` will be +allowed to spend on behalf of `owner` through [transferFrom](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#transferfrom). This is +zero by default. +This value changes when {approve} or {transferFrom} are called.* + + +```solidity +function allowance(address owner, address spender) external view returns (uint256); +``` + +### approve + +*Sets `amount` as the allowance of `spender` over the caller's tokens. +Returns a boolean value indicating whether the operation succeeded. +IMPORTANT: Beware that changing an allowance with this method brings the risk +that someone may use both the old and the new allowance by unfortunate +transaction ordering. One possible solution to mitigate this race +condition is to first reduce the spender's allowance to 0 and set the +desired value afterwards: +https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 +Emits an [Approval](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#approval) event.* + + +```solidity +function approve(address spender, uint256 amount) external returns (bool); +``` + +### transferFrom + +*Moves `amount` tokens from `sender` to `recipient` using the +allowance mechanism. `amount` is then deducted from the caller's +allowance. +Returns a boolean value indicating whether the operation succeeded. +Emits a [Transfer](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#transfer) event.* + + +```solidity +function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); +``` + +## Events +### Transfer +*Emitted when `value` tokens are moved from one account (`from`) to +another (`to`). +Note that `value` may be zero.* + + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +### Approval +*Emitted when the allowance of a `spender` for an `owner` is set by +a call to [approve](/contracts/openzeppelin/IERC20_.sol/interface.IERC20_.md#approve). `value` is the new allowance.* + + +```solidity +event Approval(address indexed owner, address indexed spender, uint256 value); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/Initializable.sol/contract.Initializable.md b/foundry/docs/src/contracts/openzeppelin/Initializable.sol/contract.Initializable.md new file mode 100644 index 000000000..b5197f9b6 --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/Initializable.sol/contract.Initializable.md @@ -0,0 +1,42 @@ +# Initializable +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/Initializable.sol) + +*This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed +behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an +external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer +function so it can only be called once. The [initializer](/contracts/openzeppelin/Initializable.sol/contract.Initializable.md#initializer) modifier provided by this contract will have this effect. +TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as +possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. +CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure +that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.* + + +## State Variables +### _initialized +*Indicates that the contract has been initialized.* + + +```solidity +bool private _initialized; +``` + + +### _initializing +*Indicates that the contract is in the process of being initialized.* + + +```solidity +bool private _initializing; +``` + + +## Functions +### initializer + +*Modifier to protect an initializer function from being invoked twice.* + + +```solidity +modifier initializer(); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/Ownable.sol/contract.Ownable.md b/foundry/docs/src/contracts/openzeppelin/Ownable.sol/contract.Ownable.md new file mode 100644 index 000000000..19065576b --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/Ownable.sol/contract.Ownable.md @@ -0,0 +1,85 @@ +# Ownable +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/Ownable.sol) + +**Inherits:** +[Context](/contracts/openzeppelin/Context.sol/contract.Context.md) + +*Contract module which provides a basic access control mechanism, where +there is an account (an owner) that can be granted exclusive access to +specific functions. +This module is used through inheritance. It will make available the modifier +`onlyOwner`, which can be applied to your functions to restrict their use to +the owner.* + + +## State Variables +### _owner + +```solidity +address private _owner; +``` + + +## Functions +### constructor + +*Initializes the contract setting the deployer as the initial owner.* + + +```solidity +constructor() internal; +``` + +### owner + +*Returns the address of the current owner.* + + +```solidity +function owner() public view returns (address); +``` + +### onlyOwner + +*Throws if called by any account other than the owner.* + + +```solidity +modifier onlyOwner(); +``` + +### isOwner + +*Returns true if the caller is the current owner.* + + +```solidity +function isOwner() public view returns (bool); +``` + +### transferOwnership + +*Transfers ownership of the contract to a new account (`newOwner`). +Can only be called by the current owner.* + + +```solidity +function transferOwnership(address newOwner) public onlyOwner; +``` + +### _transferOwnership + +*Transfers ownership of the contract to a new account (`newOwner`).* + + +```solidity +function _transferOwnership(address newOwner) internal; +``` + +## Events +### OwnershipTransferred + +```solidity +event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/PausableOz.sol/contract.PausableOz.md b/foundry/docs/src/contracts/openzeppelin/PausableOz.sol/contract.PausableOz.md new file mode 100644 index 000000000..ea9f38d9d --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/PausableOz.sol/contract.PausableOz.md @@ -0,0 +1,85 @@ +# PausableOz +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/PausableOz.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + + +## State Variables +### _paused + +```solidity +bool internal _paused; +``` + + +## Functions +### constructor + + +```solidity +constructor() internal; +``` + +### paused + +*Returns true if the contract is paused, and false otherwise.* + + +```solidity +function paused() public view returns (bool); +``` + +### whenNotPaused + +*Modifier to make a function callable only when the contract is not paused.* + + +```solidity +modifier whenNotPaused(); +``` + +### whenPaused + +*Modifier to make a function callable only when the contract is paused.* + + +```solidity +modifier whenPaused(); +``` + +### pause + +*Called by the owner to pause, triggers stopped state.* + + +```solidity +function pause() public onlyOwner whenNotPaused; +``` + +### unpause + +*Called by the owner to unpause, returns to normal state.* + + +```solidity +function unpause() public onlyOwner whenPaused; +``` + +## Events +### Paused +*Emitted when the pause is triggered by the owner (`account`).* + + +```solidity +event Paused(address account); +``` + +### Unpaused +*Emitted when the pause is lifted by the owner (`account`).* + + +```solidity +event Unpaused(address account); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/README.md b/foundry/docs/src/contracts/openzeppelin/README.md new file mode 100644 index 000000000..0064bbdfb --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/README.md @@ -0,0 +1,15 @@ + + +# Contents +- [Address](Address.sol/library.Address.md) +- [Context](Context.sol/contract.Context.md) +- [ERC20](ERC20.sol/contract.ERC20.md) +- [ERC20Detailed](ERC20Detailed.sol/contract.ERC20Detailed.md) +- [IERC20_](IERC20_.sol/interface.IERC20_.md) +- [Initializable](Initializable.sol/contract.Initializable.md) +- [Ownable](Ownable.sol/contract.Ownable.md) +- [PausableOz](PausableOz.sol/contract.PausableOz.md) +- [ReentrancyGuard](ReentrancyGuard.sol/contract.ReentrancyGuard.md) +- [SafeERC20](SafeERC20.sol/library.SafeERC20.md) +- [SafeMath](SafeMath.sol/library.SafeMath.md) +- [SignedSafeMath](SignedSafeMath.sol/library.SignedSafeMath.md) diff --git a/foundry/docs/src/contracts/openzeppelin/ReentrancyGuard.sol/contract.ReentrancyGuard.md b/foundry/docs/src/contracts/openzeppelin/ReentrancyGuard.sol/contract.ReentrancyGuard.md new file mode 100644 index 000000000..2ce66a419 --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/ReentrancyGuard.sol/contract.ReentrancyGuard.md @@ -0,0 +1,54 @@ +# ReentrancyGuard +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/ReentrancyGuard.sol) + +**Author:** +Remco Bloemen , Eenae + +*If you mark a function `nonReentrant`, you should also +mark it `external`.* + + +## State Variables +### REENTRANCY_GUARD_FREE +*Constant for unlocked guard state - non-zero to prevent extra gas costs. +See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056* + + +```solidity +uint256 internal constant REENTRANCY_GUARD_FREE = 1; +``` + + +### REENTRANCY_GUARD_LOCKED +*Constant for locked guard state* + + +```solidity +uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; +``` + + +### reentrancyLock +*We use a single lock for the whole contract.* + + +```solidity +uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; +``` + + +## Functions +### nonReentrant + +*Prevents a contract from calling itself, directly or indirectly. +If you mark a function `nonReentrant`, you should also +mark it `external`. Calling one `nonReentrant` function from +another is not supported. Instead, you can implement a +`private` function doing the actual work, and an `external` +wrapper marked as `nonReentrant`.* + + +```solidity +modifier nonReentrant(); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/SafeERC20.sol/library.SafeERC20.md b/foundry/docs/src/contracts/openzeppelin/SafeERC20.sol/library.SafeERC20.md new file mode 100644 index 000000000..2f801868b --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/SafeERC20.sol/library.SafeERC20.md @@ -0,0 +1,64 @@ +# SafeERC20 +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/SafeERC20.sol) + +*Wrappers around ERC20 operations that throw on failure (when the token +contract returns false). Tokens that return no value (and instead revert or +throw on failure) are also supported, non-reverting calls are assumed to be +successful. +To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, +which allows you to call the safe operations as `token.safeTransfer(...)`, etc.* + + +## Functions +### safeTransfer + + +```solidity +function safeTransfer(IERC20 token, address to, uint256 value) internal; +``` + +### safeTransferFrom + + +```solidity +function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal; +``` + +### safeApprove + + +```solidity +function safeApprove(IERC20 token, address spender, uint256 value) internal; +``` + +### safeIncreaseAllowance + + +```solidity +function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal; +``` + +### safeDecreaseAllowance + + +```solidity +function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal; +``` + +### callOptionalReturn + +*Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement +on the return value: the return value is optional (but if data is returned, it must not be false).* + + +```solidity +function callOptionalReturn(IERC20 token, bytes memory data) private; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`token`|`IERC20`|The token targeted by the call.| +|`data`|`bytes`|The call data (encoded using abi.encode or one of its variants).| + + diff --git a/foundry/docs/src/contracts/openzeppelin/SafeMath.sol/library.SafeMath.md b/foundry/docs/src/contracts/openzeppelin/SafeMath.sol/library.SafeMath.md new file mode 100644 index 000000000..9c0cc2d30 --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/SafeMath.sol/library.SafeMath.md @@ -0,0 +1,155 @@ +# SafeMath +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/SafeMath.sol) + +*Wrappers over Solidity's arithmetic operations with added overflow +checks. +Arithmetic operations in Solidity wrap on overflow. This can easily result +in bugs, because programmers usually assume that an overflow raises an +error, which is the standard behavior in high level programming languages. +`SafeMath` restores this intuition by reverting the transaction when an +operation overflows. +Using this library instead of the unchecked operations eliminates an entire +class of bugs, so it's recommended to use it always.* + + +## Functions +### add + +*Returns the addition of two unsigned integers, reverting on +overflow. +Counterpart to Solidity's `+` operator. +Requirements: +- Addition cannot overflow.* + + +```solidity +function add(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### sub + +*Returns the subtraction of two unsigned integers, reverting on +overflow (when the result is negative). +Counterpart to Solidity's `-` operator. +Requirements: +- Subtraction cannot overflow.* + + +```solidity +function sub(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### sub + +*Returns the subtraction of two unsigned integers, reverting with custom message on +overflow (when the result is negative). +Counterpart to Solidity's `-` operator. +Requirements: +- Subtraction cannot overflow. +_Available since v2.4.0._* + + +```solidity +function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256); +``` + +### mul + +*Returns the multiplication of two unsigned integers, reverting on +overflow. +Counterpart to Solidity's `*` operator. +Requirements: +- Multiplication cannot overflow.* + + +```solidity +function mul(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### div + +*Returns the integer division of two unsigned integers. Reverts on +division by zero. The result is rounded towards zero. +Counterpart to Solidity's `/` operator. Note: this function uses a +`revert` opcode (which leaves remaining gas untouched) while Solidity +uses an invalid opcode to revert (consuming all remaining gas). +Requirements: +- The divisor cannot be zero.* + + +```solidity +function div(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### div + +*Returns the integer division of two unsigned integers. Reverts with custom message on +division by zero. The result is rounded towards zero. +Counterpart to Solidity's `/` operator. Note: this function uses a +`revert` opcode (which leaves remaining gas untouched) while Solidity +uses an invalid opcode to revert (consuming all remaining gas). +Requirements: +- The divisor cannot be zero. +_Available since v2.4.0._* + + +```solidity +function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256); +``` + +### divCeil + +*Integer division of two numbers, rounding up and truncating the quotient* + + +```solidity +function divCeil(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### divCeil + +*Integer division of two numbers, rounding up and truncating the quotient* + + +```solidity +function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256); +``` + +### mod + +*Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), +Reverts when dividing by zero. +Counterpart to Solidity's `%` operator. This function uses a `revert` +opcode (which leaves remaining gas untouched) while Solidity uses an +invalid opcode to revert (consuming all remaining gas). +Requirements: +- The divisor cannot be zero.* + + +```solidity +function mod(uint256 a, uint256 b) internal pure returns (uint256); +``` + +### mod + +*Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), +Reverts with custom message when dividing by zero. +Counterpart to Solidity's `%` operator. This function uses a `revert` +opcode (which leaves remaining gas untouched) while Solidity uses an +invalid opcode to revert (consuming all remaining gas). +Requirements: +- The divisor cannot be zero. +_Available since v2.4.0._* + + +```solidity +function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256); +``` + +### min256 + + +```solidity +function min256(uint256 _a, uint256 _b) internal pure returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/openzeppelin/SignedSafeMath.sol/library.SignedSafeMath.md b/foundry/docs/src/contracts/openzeppelin/SignedSafeMath.sol/library.SignedSafeMath.md new file mode 100644 index 000000000..d732884c5 --- /dev/null +++ b/foundry/docs/src/contracts/openzeppelin/SignedSafeMath.sol/library.SignedSafeMath.md @@ -0,0 +1,69 @@ +# SignedSafeMath +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/openzeppelin/SignedSafeMath.sol) + +*Signed math operations with safety checks that revert on error.* + + +## State Variables +### _INT256_MIN + +```solidity +int256 private constant _INT256_MIN = -2 ** 255; +``` + + +## Functions +### mul + +*Returns the multiplication of two signed integers, reverting on +overflow. +Counterpart to Solidity's `*` operator. +Requirements: +- Multiplication cannot overflow.* + + +```solidity +function mul(int256 a, int256 b) internal pure returns (int256); +``` + +### div + +*Returns the integer division of two signed integers. Reverts on +division by zero. The result is rounded towards zero. +Counterpart to Solidity's `/` operator. Note: this function uses a +`revert` opcode (which leaves remaining gas untouched) while Solidity +uses an invalid opcode to revert (consuming all remaining gas). +Requirements: +- The divisor cannot be zero.* + + +```solidity +function div(int256 a, int256 b) internal pure returns (int256); +``` + +### sub + +*Returns the subtraction of two signed integers, reverting on +overflow. +Counterpart to Solidity's `-` operator. +Requirements: +- Subtraction cannot overflow.* + + +```solidity +function sub(int256 a, int256 b) internal pure returns (int256); +``` + +### add + +*Returns the addition of two signed integers, reverting on +overflow. +Counterpart to Solidity's `+` operator. +Requirements: +- Addition cannot overflow.* + + +```solidity +function add(int256 a, int256 b) internal pure returns (int256); +``` + diff --git a/foundry/docs/src/contracts/proxy/Proxy.sol/contract.Proxy.md b/foundry/docs/src/contracts/proxy/Proxy.sol/contract.Proxy.md new file mode 100644 index 000000000..612f9b74f --- /dev/null +++ b/foundry/docs/src/contracts/proxy/Proxy.sol/contract.Proxy.md @@ -0,0 +1,142 @@ +# Proxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/proxy/Proxy.sol) + +The proxy performs delegated calls to the contract implementation +it is pointing to. This way upgradable contracts are possible on blockchain. +Delegating proxy contracts are widely used for both upgradeability and gas +savings. These proxies rely on a logic contract (also known as implementation +contract or master copy) that is called using delegatecall. This allows +proxies to keep a persistent state (storage and balance) while the code is +delegated to the logic contract. +Proxy contract is meant to be inherited and its internal functions +_setImplementation and _setProxyOwner to be called when upgrades become +neccessary. +The loan token (iToken) contract as well as the protocol contract act as +proxies, delegating all calls to underlying contracts. Therefore, if you +want to interact with them using web3, you need to use the ABIs from the +contracts containing the actual logic or the interface contract. +ABI for LoanToken contracts: LoanTokenLogicStandard +ABI for Protocol contract: ISovryn + +*UpgradableProxy is the contract that inherits Proxy and wraps these +functions.* + + +## State Variables +### KEY_IMPLEMENTATION + +```solidity +bytes32 private constant KEY_IMPLEMENTATION = keccak256("key.implementation"); +``` + + +### KEY_OWNER + +```solidity +bytes32 private constant KEY_OWNER = keccak256("key.proxy.owner"); +``` + + +## Functions +### constructor + +Set sender as an owner. + + +```solidity +constructor() public; +``` + +### onlyProxyOwner + +Throw error if called not by an owner. + + +```solidity +modifier onlyProxyOwner(); +``` + +### _setImplementation + +Set address of the implementation. + + +```solidity +function _setImplementation(address _implementation) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementation`|`address`|Address of the implementation.| + + +### getImplementation + +Return address of the implementation. + + +```solidity +function getImplementation() public view returns (address _implementation); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_implementation`|`address`|Address of the implementation.| + + +### _setProxyOwner + +Set address of the owner. + + +```solidity +function _setProxyOwner(address _owner) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|Address of the owner.| + + +### getProxyOwner + +Return address of the owner. + + +```solidity +function getProxyOwner() public view returns (address _owner); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|Address of the owner.| + + +### function + +Fallback function performs a delegate call +to the actual implementation address is pointing this proxy. +Returns whatever the implementation call returns. + + +```solidity +function() external payable; +``` + +## Events +### OwnershipTransferred + +```solidity +event OwnershipTransferred(address indexed _oldOwner, address indexed _newOwner); +``` + +### ImplementationChanged + +```solidity +event ImplementationChanged(address indexed _oldImplementation, address indexed _newImplementation); +``` + diff --git a/foundry/docs/src/contracts/proxy/README.md b/foundry/docs/src/contracts/proxy/README.md new file mode 100644 index 000000000..7a2e33580 --- /dev/null +++ b/foundry/docs/src/contracts/proxy/README.md @@ -0,0 +1,7 @@ + + +# Contents +- [TransparentUpgradableProxy](/contracts/proxy/TransparentUpgradableProxy) +- [modules](/contracts/proxy/modules) +- [Proxy](Proxy.sol/contract.Proxy.md) +- [UpgradableProxy](UpgradableProxy.sol/contract.UpgradableProxy.md) diff --git a/foundry/docs/src/contracts/proxy/TransparentUpgradableProxy/README.md b/foundry/docs/src/contracts/proxy/TransparentUpgradableProxy/README.md new file mode 100644 index 000000000..3ffbd20ca --- /dev/null +++ b/foundry/docs/src/contracts/proxy/TransparentUpgradableProxy/README.md @@ -0,0 +1,4 @@ + + +# Contents +- [TransparentUpgradableProxyAdmin](TransparentUpgradableProxyAdmin.sol/contract.TransparentUpgradableProxyAdmin.md) diff --git a/foundry/docs/src/contracts/proxy/TransparentUpgradableProxy/TransparentUpgradableProxyAdmin.sol/contract.TransparentUpgradableProxyAdmin.md b/foundry/docs/src/contracts/proxy/TransparentUpgradableProxy/TransparentUpgradableProxyAdmin.sol/contract.TransparentUpgradableProxyAdmin.md new file mode 100644 index 000000000..197751a7d --- /dev/null +++ b/foundry/docs/src/contracts/proxy/TransparentUpgradableProxy/TransparentUpgradableProxyAdmin.sol/contract.TransparentUpgradableProxyAdmin.md @@ -0,0 +1,9 @@ +# TransparentUpgradableProxyAdmin +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/proxy/TransparentUpgradableProxy/TransparentUpgradableProxyAdmin.sol) + +**Inherits:** +ProxyAdmin + +*implements openzeppelin transparent upgradability ProxyAdmin* + + diff --git a/foundry/docs/src/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md b/foundry/docs/src/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md new file mode 100644 index 000000000..fade069d9 --- /dev/null +++ b/foundry/docs/src/contracts/proxy/UpgradableProxy.sol/contract.UpgradableProxy.md @@ -0,0 +1,53 @@ +# UpgradableProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/proxy/UpgradableProxy.sol) + +**Inherits:** +[Proxy](/contracts/proxy/Proxy.sol/contract.Proxy.md) + +A disadvantage of the immutable ledger is that nobody can change the +source code of a smart contract after it’s been deployed. In order to fix +bugs or introduce new features, smart contracts need to be upgradable somehow. +Although it is not possible to upgrade the code of an already deployed smart +contract, it is possible to set-up a proxy contract architecture that will +allow to use new deployed contracts as if the main logic had been upgraded. +A proxy architecture pattern is such that all message calls go through a +Proxy contract that will redirect them to the latest deployed contract logic. +To upgrade, a new version of the contract is deployed, and the Proxy is +updated to reference the new contract address. + + +## Functions +### setImplementation + +Set address of the implementation. + +*Wrapper for _setImplementation that exposes the function +as public for owner to be able to set a new version of the +contract as current pointing implementation.* + + +```solidity +function setImplementation(address _implementation) public onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementation`|`address`|Address of the implementation.| + + +### setProxyOwner + +Set address of the owner. + + +```solidity +function setProxyOwner(address _owner) public onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|Address of the owner.| + + diff --git a/foundry/docs/src/contracts/proxy/modules/ModulesProxy.sol/contract.ModulesProxy.md b/foundry/docs/src/contracts/proxy/modules/ModulesProxy.sol/contract.ModulesProxy.md new file mode 100644 index 000000000..615c80db7 --- /dev/null +++ b/foundry/docs/src/contracts/proxy/modules/ModulesProxy.sol/contract.ModulesProxy.md @@ -0,0 +1,39 @@ +# ModulesProxy +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/proxy/modules/ModulesProxy.sol) + +**Inherits:** +[ModulesProxyRegistry](/contracts/proxy/modules/ModulesProxyRegistry.sol/contract.ModulesProxyRegistry.md) + +ModulesProxy serves as a storage processed by a set of logic contracts - modules +Modules functions are registered in the contract's slots generated per func sig +All the function calls except for own Proxy functions are delegated to +the registered functions +The ModulesProxy is designed as a universal solution for refactorig contracts +reaching a 24K size limit (EIP-170) +Upgradability is implemented at a module level to provide consistency +It does not allow to replace separate functions - only the whole module +meaning that if a module being registered contains other modules function signatures +then these modulea should be replaced completely - all the functions should be removed +to avoid leftovers or accidental replacements and therefore functional inconsistency. +A module is either a new non-overlapping with registered modules +or a complete replacement of another registered module +in which case all the old module functions are unregistered and then +the new module functions are registered +There is also a separate function to unregister a module which unregisters all the functions +There is no option to unregister a subset of module functions - one should use pausable functionality +to achieve this + + +## Functions +### function + +Fallback function delegates calls to modules. +Returns whatever the implementation call returns. +Has a hook to execute before delegating calls +To activate register a module with beforeFallback() function + + +```solidity +function() external payable; +``` + diff --git a/foundry/docs/src/contracts/proxy/modules/ModulesProxyRegistry.sol/contract.ModulesProxyRegistry.md b/foundry/docs/src/contracts/proxy/modules/ModulesProxyRegistry.sol/contract.ModulesProxyRegistry.md new file mode 100644 index 000000000..aa786fcaf --- /dev/null +++ b/foundry/docs/src/contracts/proxy/modules/ModulesProxyRegistry.sol/contract.ModulesProxyRegistry.md @@ -0,0 +1,314 @@ +# ModulesProxyRegistry +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/proxy/modules/ModulesProxyRegistry.sol) + +**Inherits:** +[IModulesProxyRegistry](/contracts/proxy/modules/interfaces/IModulesProxyRegistry.sol/contract.IModulesProxyRegistry.md), [ProxyOwnable](/contracts/utils/ProxyOwnable.sol/contract.ProxyOwnable.md) + +ModulesProxyRegistry provides modules registration/removing/replacing functionality to ModulesProxy +Designed to be inherited + + +## State Variables +### KEY_IMPLEMENTATION + +```solidity +bytes32 internal constant KEY_IMPLEMENTATION = keccak256("key.implementation"); +``` + + +## Functions +### constructor + +Constructor is internal to make contract abstract + + +```solidity +constructor() internal; +``` + +### addModule + +Add module functions. +Overriding functions is not allowed. To replace modules use replaceModule function. + + +```solidity +function addModule(address _impl) external onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_impl`|`address`|Module implementation address| + + +### addModules + +Add modules functions. + + +```solidity +function addModules(address[] calldata _implementations) external onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementations`|`address[]`|Modules implementation addresses| + + +### replaceModule + +Replace module - remove the previous, add the new one + + +```solidity +function replaceModule(address _oldModuleImpl, address _newModuleImpl) external onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_oldModuleImpl`|`address`|Module implementation address to remove| +|`_newModuleImpl`|`address`|Module implementation address to add| + + +### replaceModules + +Add modules functions. + + +```solidity +function replaceModules(address[] calldata _implementationsFrom, address[] calldata _implementationsTo) + external + onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementationsFrom`|`address[]`|Modules to replace| +|`_implementationsTo`|`address[]`|Replacing modules| + + +### removeModule + +To disable module - set all its functions implementation to address(0) + + +```solidity +function removeModule(address _impl) external onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_impl`|`address`|implementation address| + + +### removeModules + +Add modules functions. + + +```solidity +function removeModules(address[] calldata _implementations) external onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementations`|`address[]`|Modules implementation addresses| + + +### getFuncImplementation + + +```solidity +function getFuncImplementation(bytes4 _sig) external view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sig`|`bytes4`|Function signature to get impmementation address for| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|Function's contract implelementation address| + + +### canAddModule + +Verifies if no functions from the module already registered + + +```solidity +function canAddModule(address _impl) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_impl`|`address`|Module implementation address to verify| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|True if module can be added| + + +### canNotAddModules + +Multiple modules verification if there are functions from the modules already registered + + +```solidity +function canNotAddModules(address[] memory _implementations) public view returns (address[] memory); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementations`|`address[]`|modules implementation addresses to verify| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address[]`|addresses of registered modules| + + +### checkClashingFuncSelectors + +Used externally to verify module being added for clashing + + +```solidity +function checkClashingFuncSelectors(address _newModule) + external + view + returns ( + address[] memory clashingModules, + bytes4[] memory clashingModulesFuncSelectors, + bytes4[] memory clashingProxyRegistryFuncSelectors + ); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newModule`|`address`|module implementation which functions to verify| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`clashingModules`|`address[]`|Clashing functions signatures and corresponding modules (contracts) addresses| +|`clashingModulesFuncSelectors`|`bytes4[]`|| +|`clashingProxyRegistryFuncSelectors`|`bytes4[]`|| + + +### isModuleRegistered + +Verifies the deployed contract address is a registered module contract + + +```solidity +function isModuleRegistered(address _impl) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_impl`|`address`|deployment address to verify| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|true if _impl address is a registered module| + + +### _getFirstRegisteredModuleAddress + +INTERNAL FUNCTIONS ***************** + + +```solidity +function _getFirstRegisteredModuleAddress(address _impl) internal view returns (address); +``` + +### _getFuncImplementation + + +```solidity +function _getFuncImplementation(bytes4 _sig) internal view returns (address); +``` + +### _addModule + + +```solidity +function _addModule(address _impl) internal; +``` + +### _addModules + + +```solidity +function _addModules(address[] memory _implementations) internal; +``` + +### _removeModule + + +```solidity +function _removeModule(address _impl) internal onlyProxyOwner; +``` + +### _removeModules + + +```solidity +function _removeModules(address[] memory _implementations) internal; +``` + +### _replaceModule + + +```solidity +function _replaceModule(address _oldModuleImpl, address _newModuleImpl) internal; +``` + +### _setModuleFuncImplementation + + +```solidity +function _setModuleFuncImplementation(bytes4 _sig, address _impl) internal; +``` + +### _isFuncClashingWithProxyFunctions + + +```solidity +function _isFuncClashingWithProxyFunctions(bytes4 _sig) internal pure returns (bool); +``` + +### _canAddModule + + +```solidity +function _canAddModule(address _impl) internal view returns (bool); +``` + +### _getFunctionsList + + +```solidity +function _getFunctionsList() internal pure returns (bytes4[] memory); +``` + diff --git a/foundry/docs/src/contracts/proxy/modules/README.md b/foundry/docs/src/contracts/proxy/modules/README.md new file mode 100644 index 000000000..85cc2c76b --- /dev/null +++ b/foundry/docs/src/contracts/proxy/modules/README.md @@ -0,0 +1,6 @@ + + +# Contents +- [interfaces](/contracts/proxy/modules/interfaces) +- [ModulesProxy](ModulesProxy.sol/contract.ModulesProxy.md) +- [ModulesProxyRegistry](ModulesProxyRegistry.sol/contract.ModulesProxyRegistry.md) diff --git a/foundry/docs/src/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md b/foundry/docs/src/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md new file mode 100644 index 000000000..f32c83cdc --- /dev/null +++ b/foundry/docs/src/contracts/proxy/modules/interfaces/IFunctionsList.sol/interface.IFunctionsList.md @@ -0,0 +1,12 @@ +# IFunctionsList +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/proxy/modules/interfaces/IFunctionsList.sol) + + +## Functions +### getFunctionsList + + +```solidity +function getFunctionsList() external pure returns (bytes4[] memory functionSignatures); +``` + diff --git a/foundry/docs/src/contracts/proxy/modules/interfaces/IModulesProxyRegistry.sol/contract.IModulesProxyRegistry.md b/foundry/docs/src/contracts/proxy/modules/interfaces/IModulesProxyRegistry.sol/contract.IModulesProxyRegistry.md new file mode 100644 index 000000000..c68a9ec71 --- /dev/null +++ b/foundry/docs/src/contracts/proxy/modules/interfaces/IModulesProxyRegistry.sol/contract.IModulesProxyRegistry.md @@ -0,0 +1,218 @@ +# IModulesProxyRegistry +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/proxy/modules/interfaces/IModulesProxyRegistry.sol) + +ModulesProxyRegistry Interface + + +## Functions +### addModule + +Add module functions. +Overriding functions is not allowed. To replace modules use ReplaceModule function. + + +```solidity +function addModule(address _impl) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_impl`|`address`|Module implementation address| + + +### addModules + +Add modules functions. + + +```solidity +function addModules(address[] calldata _implementations) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementations`|`address[]`|Modules implementation addresses| + + +### replaceModule + +Replace module - remove the previous, add the new one + + +```solidity +function replaceModule(address _oldModuleImpl, address _newModuleImpl) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_oldModuleImpl`|`address`|Module implementation address to remove| +|`_newModuleImpl`|`address`|Module implementation address to add| + + +### replaceModules + +Add modules functions. + + +```solidity +function replaceModules(address[] calldata _implementationsFrom, address[] calldata _implementationsTo) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementationsFrom`|`address[]`|Modules to replace| +|`_implementationsTo`|`address[]`|Replacing modules| + + +### removeModule + +to disable module - set all its functions implementation to address(0) + + +```solidity +function removeModule(address _impl) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_impl`|`address`|implementation address| + + +### removeModules + +Add modules functions. + + +```solidity +function removeModules(address[] calldata _implementations) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementations`|`address[]`|Modules implementation addresses| + + +### getFuncImplementation + + +```solidity +function getFuncImplementation(bytes4 _sig) external view returns (address); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sig`|`bytes4`|function signature to get impmementation address for| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`address`|function's contract implelementation address| + + +### canAddModule + +verifies if no functions from the module deployed already registered + + +```solidity +function canAddModule(address _impl) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_impl`|`address`|module implementation address to verify| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|true if module can be added| + + +### canNotAddModules + +Multiple modules verification if no functions from the modules already registered + + +```solidity +function canNotAddModules(address[] calldata _implementations) external view returns (address[] memory modules); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_implementations`|`address[]`|modules implementation addresses to verify| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`modules`|`address[]`|True if all modules can be added, false otherwise| + + +### checkClashingFuncSelectors + +used externally to verify module being added for clashing + + +```solidity +function checkClashingFuncSelectors(address _newModule) + external + view + returns ( + address[] memory clashingModules, + bytes4[] memory clashingModulesFuncSelectors, + bytes4[] memory clashingProxyRegistryFuncSelectors + ); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_newModule`|`address`|module implementation which functions to verify| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`clashingModules`|`address[]`|clashing functions signatures and corresponding modules (contracts) addresses| +|`clashingModulesFuncSelectors`|`bytes4[]`|| +|`clashingProxyRegistryFuncSelectors`|`bytes4[]`|| + + +## Events +### AddModule + +```solidity +event AddModule(address indexed moduleAddress); +``` + +### ReplaceModule + +```solidity +event ReplaceModule(address indexed oldAddress, address indexed newAddress); +``` + +### RemoveModule + +```solidity +event RemoveModule(address indexed moduleAddress); +``` + +### SetModuleFuncImplementation + +```solidity +event SetModuleFuncImplementation( + bytes4 indexed _funcSig, address indexed _oldImplementation, address indexed _newImplementation +); +``` + diff --git a/foundry/docs/src/contracts/proxy/modules/interfaces/README.md b/foundry/docs/src/contracts/proxy/modules/interfaces/README.md new file mode 100644 index 000000000..f7b704039 --- /dev/null +++ b/foundry/docs/src/contracts/proxy/modules/interfaces/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [IFunctionsList](IFunctionsList.sol/interface.IFunctionsList.md) +- [IModulesProxyRegistry](IModulesProxyRegistry.sol/contract.IModulesProxyRegistry.md) diff --git a/foundry/docs/src/contracts/reentrancy/Mutex.sol/contract.Mutex.md b/foundry/docs/src/contracts/reentrancy/Mutex.sol/contract.Mutex.md new file mode 100644 index 000000000..70f012d3b --- /dev/null +++ b/foundry/docs/src/contracts/reentrancy/Mutex.sol/contract.Mutex.md @@ -0,0 +1,20 @@ +# Mutex +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/reentrancy/Mutex.sol) + + +## State Variables +### value + +```solidity +uint256 public value; +``` + + +## Functions +### incrementAndGetValue + + +```solidity +function incrementAndGetValue() external returns (uint256); +``` + diff --git a/foundry/docs/src/contracts/reentrancy/README.md b/foundry/docs/src/contracts/reentrancy/README.md new file mode 100644 index 000000000..9589a478e --- /dev/null +++ b/foundry/docs/src/contracts/reentrancy/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [Mutex](Mutex.sol/contract.Mutex.md) +- [SharedReentrancyGuard](SharedReentrancyGuard.sol/contract.SharedReentrancyGuard.md) diff --git a/foundry/docs/src/contracts/reentrancy/SharedReentrancyGuard.sol/contract.SharedReentrancyGuard.md b/foundry/docs/src/contracts/reentrancy/SharedReentrancyGuard.sol/contract.SharedReentrancyGuard.md new file mode 100644 index 000000000..4715582cc --- /dev/null +++ b/foundry/docs/src/contracts/reentrancy/SharedReentrancyGuard.sol/contract.SharedReentrancyGuard.md @@ -0,0 +1,20 @@ +# SharedReentrancyGuard +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/reentrancy/SharedReentrancyGuard.sol) + + +## State Variables +### MUTEX + +```solidity +Mutex private constant MUTEX = Mutex(0xba10edD6ABC7696Eae685839217BdcC42139612b); +``` + + +## Functions +### globallyNonReentrant + + +```solidity +modifier globallyNonReentrant(); +``` + diff --git a/foundry/docs/src/contracts/rsk/README.md b/foundry/docs/src/contracts/rsk/README.md new file mode 100644 index 000000000..754db9411 --- /dev/null +++ b/foundry/docs/src/contracts/rsk/README.md @@ -0,0 +1,4 @@ + + +# Contents +- [RSKAddrValidator](RSKAddrValidator.sol/library.RSKAddrValidator.md) diff --git a/foundry/docs/src/contracts/rsk/RSKAddrValidator.sol/library.RSKAddrValidator.md b/foundry/docs/src/contracts/rsk/RSKAddrValidator.sol/library.RSKAddrValidator.md new file mode 100644 index 000000000..666705127 --- /dev/null +++ b/foundry/docs/src/contracts/rsk/RSKAddrValidator.sol/library.RSKAddrValidator.md @@ -0,0 +1,19 @@ +# RSKAddrValidator +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/rsk/RSKAddrValidator.sol) + + +## Functions +### checkPKNotZero + + +```solidity +function checkPKNotZero(address addr) internal pure returns (bool); +``` + +### safeEquals + + +```solidity +function safeEquals(address addr1, address addr2) internal pure returns (bool); +``` + diff --git a/foundry/docs/src/contracts/swaps/README.md b/foundry/docs/src/contracts/swaps/README.md new file mode 100644 index 000000000..6d5100530 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [connectors](/contracts/swaps/connectors) +- [SwapsUser](SwapsUser.sol/contract.SwapsUser.md) diff --git a/foundry/docs/src/contracts/swaps/SwapsUser.sol/contract.SwapsUser.md b/foundry/docs/src/contracts/swaps/SwapsUser.sol/contract.SwapsUser.md new file mode 100644 index 000000000..227eb1f56 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/SwapsUser.sol/contract.SwapsUser.md @@ -0,0 +1,182 @@ +# SwapsUser +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/swaps/SwapsUser.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md), [SwapsEvents](/contracts/events/SwapsEvents.sol/contract.SwapsEvents.md), [FeesHelper](/contracts/mixins/FeesHelper.sol/contract.FeesHelper.md) + +Copyright 2017-2021, bZeroX, LLC . All Rights Reserved. +Licensed under the Apache License, Version 2.0. + + +## Functions +### _loanSwap + +Internal loan swap. + + +```solidity +function _loanSwap( + bytes32 loanId, + address sourceToken, + address destToken, + address user, + uint256 minSourceTokenAmount, + uint256 maxSourceTokenAmount, + uint256 requiredDestTokenAmount, + bool bypassFee, + bytes memory loanDataBytes +) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 sourceToDestSwapRate); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`loanId`|`bytes32`|The ID of the loan.| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of destination tokens.| +|`user`|`address`|The user address.| +|`minSourceTokenAmount`|`uint256`|The minimum amount of source tokens to swap.| +|`maxSourceTokenAmount`|`uint256`|The maximum amount of source tokens to swap.| +|`requiredDestTokenAmount`|`uint256`|The required amount of destination tokens.| +|`bypassFee`|`bool`|To bypass or not the fee.| +|`loanDataBytes`|`bytes`|The payload for the call. These loan DataBytes are additional loan data (not in use for token swaps).| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`destTokenAmountReceived`|`uint256`|destTokenAmountReceived| +|`sourceTokenAmountUsed`|`uint256`|sourceTokenAmountUsed| +|`sourceToDestSwapRate`|`uint256`|sourceToDestSwapRate| + + +### _swapsCall + +Will revert if swap size too large. +Will revert if disagreement found. + +Calculate amount of source and destination tokens. + +*Wrapper for _swapsCall_internal function.* + + +```solidity +function _swapsCall( + address[5] memory addrs, + uint256[3] memory vals, + bytes32 loanId, + bool miscBool, + bytes memory loanDataBytes, + bool isSwapExternal +) internal returns (uint256, uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`addrs`|`address[5]`|The array of addresses.| +|`vals`|`uint256[3]`|The array of values.| +|`loanId`|`bytes32`|The Id of the associated loan.| +|`miscBool`|`bool`|True/false to bypassFee.| +|`loanDataBytes`|`bytes`|Additional loan data (not in use yet).| +|`isSwapExternal`|`bool`|| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|destTokenAmountReceived The amount of destination tokens received.| +|``|`uint256`|sourceTokenAmountUsed The amount of source tokens used.| + + +### _swapsCall_internal + +addrs[0]: sourceToken +addrs[1]: destToken +addrs[2]: receiver +addrs[3]: returnToSender +addrs[4]: user +vals[0]: minSourceTokenAmount +vals[1]: maxSourceTokenAmount +vals[2]: requiredDestTokenAmount +bypassFee +condition: vals[0] will always be used as sourceAmount +user +sourceToken (feeToken) +pairToken (used to check if there is any special rebates or not) -- to pay fee reward +Condition: unknown sourceAmount will be used. +There's no minimum destTokenAmount, but all of vals[0] +(minSourceTokenAmount) must be spent. +There's a minimum destTokenAmount required, but +sourceTokenAmountUsed won't be greater +than vals[1] (maxSourceTokenAmount) +user +loanId, +destToken (feeToken) +pairToken (used to check if there is any special rebates or not) -- to pay fee reward + +Calculate amount of source and destination tokens. + +*Calls swapsImpl::internalSwap* + + +```solidity +function _swapsCall_internal(address[5] memory addrs, uint256[3] memory vals) + internal + returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`addrs`|`address[5]`|The array of addresses.| +|`vals`|`uint256[3]`|The array of values.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`destTokenAmountReceived`|`uint256`|The amount of destination tokens received.| +|`sourceTokenAmountUsed`|`uint256`|The amount of source tokens used.| + + +### _swapsExpectedReturn + +Calculate expected amount of destination tokens. + +*Calls swapsImpl::internalExpectedReturn* + + +```solidity +function _swapsExpectedReturn(address sourceToken, address destToken, uint256 sourceTokenAmount) + internal + view + returns (uint256 destTokenAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceToken`|`address`|The address of the source tokens.| +|`destToken`|`address`|The address of the destination tokens.| +|`sourceTokenAmount`|`uint256`|The amount of the source tokens.| + + +### _checkSwapSize + +Verify that the amount of tokens are under the swap limit. + +*Calls priceFeeds::amountInEth* + + +```solidity +function _checkSwapSize(address tokenAddress, uint256 amount) internal view; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokenAddress`|`address`|The address of the token to calculate price.| +|`amount`|`uint256`|The amount of tokens to calculate price.| + + diff --git a/foundry/docs/src/contracts/swaps/connectors/README.md b/foundry/docs/src/contracts/swaps/connectors/README.md new file mode 100644 index 000000000..a98ff120b --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/README.md @@ -0,0 +1,7 @@ + + +# Contents +- [interfaces](/contracts/swaps/connectors/interfaces) +- [testnet](/contracts/swaps/connectors/testnet) +- [SwapsImplSovrynSwap](SwapsImplSovrynSwap.sol/contract.SwapsImplSovrynSwap.md) +- [SwapsImplSovrynSwapLib](SwapsImplSovrynSwapLib.sol/library.SwapsImplSovrynSwapLib.md) diff --git a/foundry/docs/src/contracts/swaps/connectors/SwapsImplSovrynSwap.sol/contract.SwapsImplSovrynSwap.md b/foundry/docs/src/contracts/swaps/connectors/SwapsImplSovrynSwap.sol/contract.SwapsImplSovrynSwap.md new file mode 100644 index 000000000..fe7f7b886 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/SwapsImplSovrynSwap.sol/contract.SwapsImplSovrynSwap.md @@ -0,0 +1,230 @@ +# SwapsImplSovrynSwap +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/swaps/connectors/SwapsImplSovrynSwap.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the implementation of swap process and rate +calculations for Sovryn network. + +*WARNING: This contract is deprecated, all public functions are moved to the protocol modules.* + + +## Functions +### constructor + +bytes32 contractName = hex"42616e636f724e6574776f726b"; /// "SovrynSwapNetwork" + + +```solidity +constructor() internal; +``` + +### getContractHexName + +Get the hex name of a contract. + + +```solidity +function getContractHexName(string memory source) public pure returns (bytes32 result); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`source`|`string`|The name of the contract.| + + +### getSovrynSwapNetworkContract + +Look up the Sovryn swap network contract registered at the given address. + + +```solidity +function getSovrynSwapNetworkContract(address sovrynSwapRegistryAddress) public view returns (ISovrynSwapNetwork); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sovrynSwapRegistryAddress`|`address`|The address of the registry.| + + +### internalSwap + +State variable sovrynSwapContractRegistryAddress is part of +State.sol and set in ProtocolSettings.sol and this function +needs to work without delegate call as well -> therefore pass it. +Swap the source token for the destination token on the oracle based AMM. +On loan opening: minSourceTokenAmount = maxSourceTokenAmount and requiredDestTokenAmount = 0 +-> swap the minSourceTokenAmount +On loan rollover: (swap interest) minSourceTokenAmount = 0, maxSourceTokenAmount = complete collateral and requiredDestTokenAmount > 0 +-> amount of required source tokens to swap is estimated (want to fill requiredDestTokenAmount, not more). maxSourceTokenAMount is not exceeded. +On loan closure: minSourceTokenAmount <= maxSourceTokenAmount and requiredDestTokenAmount >= 0 +-> same as on rollover. minimum amount is not considered at all. + + +```solidity +function internalSwap( + address sourceTokenAddress, + address destTokenAddress, + address receiverAddress, + address returnToSenderAddress, + uint256 minSourceTokenAmount, + uint256 maxSourceTokenAmount, + uint256 requiredDestTokenAmount +) public payable returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source tokens.| +|`destTokenAddress`|`address`|The address of the destination tokens.| +|`receiverAddress`|`address`|The address who will received the swap token results| +|`returnToSenderAddress`|`address`|The address to return unspent tokens to (when called by the protocol, it's always the protocol contract).| +|`minSourceTokenAmount`|`uint256`|The minimum amount of source tokens to swapped (only considered if requiredDestTokens == 0).| +|`maxSourceTokenAmount`|`uint256`|The maximum amount of source tokens to swapped.| +|`requiredDestTokenAmount`|`uint256`|The required amount of destination tokens.| + + +### allowTransfer + +If the required amount of destination tokens is passed, we need to +calculate the estimated amount of source tokens regardless of the +minimum source token amount (name is misleading). +sovrynSwapNetwork.rateByPath does not return a rate, but instead the amount of destination tokens returned. + +Check whether the existing allowance suffices to transfer +the needed amount of tokens. +If not, allows the transfer of an arbitrary amount of tokens. + +*Note: the kyber connector uses .call() to interact with kyber +to avoid bubbling up. here we allow bubbling up. +If the sender is not the protocol (calling with delegatecall), +return the remainder to the specified address.* + +*Note: for the case that the swap is used without the +protocol. Not sure if it should, though. needs to be discussed. +Send unused source token back.* + + +```solidity +function allowTransfer(uint256 tokenAmount, address tokenAddress, address sovrynSwapNetwork) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokenAmount`|`uint256`|The amount to transfer.| +|`tokenAddress`|`address`|The address of the token to transfer.| +|`sovrynSwapNetwork`|`address`|The address of the sovrynSwap network contract.| + + +### estimateSourceTokenAmount + +Calculate the number of source tokens to provide in order to +obtain the required destination amount. + + +```solidity +function estimateSourceTokenAmount( + address sourceTokenAddress, + address destTokenAddress, + uint256 requiredDestTokenAmount, + uint256 maxSourceTokenAmount +) internal view returns (uint256 estimatedSourceAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token address.| +|`destTokenAddress`|`address`|The address of the destination token address.| +|`requiredDestTokenAmount`|`uint256`|The number of destination tokens needed.| +|`maxSourceTokenAmount`|`uint256`|The maximum number of source tokens to spend.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`estimatedSourceAmount`|`uint256`|The estimated amount of source tokens needed. Minimum: minSourceTokenAmount, maximum: maxSourceTokenAmount| + + +### internalExpectedRate + +Compute the expected rate for the maxSourceTokenAmount -> if spending less, we can't get a worse rate. +Compute the source tokens needed to get the required amount with the worst case rate. +If the actual rate is exactly the same as the worst case rate, we get rounding issues. So, add a small buffer. +buffer = min(estimatedSourceAmount/1000 , sourceBuffer) with sourceBuffer = 10000 +Never spend more than the maximum. + +Get the expected rate for 1 source token when exchanging the +given amount of source tokens. + + +```solidity +function internalExpectedRate( + address sourceTokenAddress, + address destTokenAddress, + uint256 sourceTokenAmount, + address sovrynSwapContractRegistryAddress +) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token contract.| +|`destTokenAddress`|`address`|The address of the destination token contract.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens to get the rate for.| +|`sovrynSwapContractRegistryAddress`|`address`|| + + +### internalExpectedReturn + +Is returning the total amount of destination tokens. +Return the rate for 1 token with 18 decimals. + +Get the expected return amount when exchanging the given +amount of source tokens. + +Right now, this function is being called directly by _swapsExpectedReturn from the protocol +So, this function is not using getConversionPath function since it will try to read the defaultPath storage which is stored in the protocol's slot, and it will cause an issue for direct call. +Instead, this function is accepting additional parameters called defaultPath which value can be declared by the caller (protocol in this case). + + +```solidity +function internalExpectedReturn( + address sourceTokenAddress, + address destTokenAddress, + uint256 sourceTokenAmount, + address sovrynSwapContractRegistry, + IERC20[] memory defaultPath +) public view returns (uint256 expectedReturn); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token contract.| +|`destTokenAddress`|`address`|The address of the destination token contract.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens to get the return for.| +|`sovrynSwapContractRegistry`|`address`|The sovryn swap contract reigstry address.| +|`defaultPath`|`IERC20[]`|The default path for specific pairs.| + + +### getConversionPath + +Is returning the total amount of destination tokens. + + +```solidity +function getConversionPath(address sourceTokenAddress, address destTokenAddress, ISovrynSwapNetwork sovrynSwapNetwork) + private + view + returns (IERC20[] memory path); +``` + diff --git a/foundry/docs/src/contracts/swaps/connectors/SwapsImplSovrynSwapLib.sol/library.SwapsImplSovrynSwapLib.md b/foundry/docs/src/contracts/swaps/connectors/SwapsImplSovrynSwapLib.sol/library.SwapsImplSovrynSwapLib.md new file mode 100644 index 000000000..19f168374 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/SwapsImplSovrynSwapLib.sol/library.SwapsImplSovrynSwapLib.md @@ -0,0 +1,212 @@ +# SwapsImplSovrynSwapLib +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/swaps/connectors/SwapsImplSovrynSwapLib.sol) + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the implementation of swap process and rate +calculations for Sovryn network. + + +## Functions +### getContractHexName + +bytes32 contractName = hex"42616e636f724e6574776f726b"; /// "SovrynSwapNetwork" +Get the hex name of a contract. + + +```solidity +function getContractHexName(string memory source) public pure returns (bytes32 result); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`source`|`string`|The name of the contract.| + + +### getSovrynSwapNetworkContract + +Look up the Sovryn swap network contract registered at the given address. + + +```solidity +function getSovrynSwapNetworkContract(address sovrynSwapRegistryAddress) public view returns (ISovrynSwapNetwork); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sovrynSwapRegistryAddress`|`address`|The address of the registry.| + + +### swap + +State variable sovrynSwapContractRegistryAddress is part of +State.sol and set in ProtocolSettings.sol and this function +needs to work without delegate call as well -> therefore pass it. +Swap the source token for the destination token on the oracle based AMM. +On loan opening: minSourceTokenAmount = maxSourceTokenAmount and requiredDestTokenAmount = 0 +-> swap the minSourceTokenAmount +On loan rollover: (swap interest) minSourceTokenAmount = 0, maxSourceTokenAmount = complete collateral and requiredDestTokenAmount > 0 +-> amount of required source tokens to swap is estimated (want to fill requiredDestTokenAmount, not more). maxSourceTokenAMount is not exceeded. +On loan closure: minSourceTokenAmount <= maxSourceTokenAmount and requiredDestTokenAmount >= 0 +-> same as on rollover. minimum amount is not considered at all. + + +```solidity +function swap(SwapParams memory params) + public + returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`params`|`SwapParams`|SwapParams struct sourceTokenAddress The address of the source tokens. destTokenAddress The address of the destination tokens. receiverAddress The address who will received the swap token results returnToSenderAddress The address to return unspent tokens to (when called by the protocol, it's always the protocol contract). minSourceTokenAmount The minimum amount of source tokens to swapped (only considered if requiredDestTokens == 0). maxSourceTokenAmount The maximum amount of source tokens to swapped. requiredDestTokenAmount The required amount of destination tokens.| + + +### _allowTransfer + +If the required amount of destination tokens is passed, we need to +calculate the estimated amount of source tokens regardless of the +minimum source token amount (name is misleading). +sovrynSwapNetwork.rateByPath does not return a rate, but instead the amount of destination tokens returned. + +Check whether the existing allowance suffices to transfer +the needed amount of tokens. +If not, allows the transfer of an arbitrary amount of tokens. + +*Note: the kyber connector uses .call() to interact with kyber +to avoid bubbling up. here we allow bubbling up. +If the sender is not the protocol (calling with delegatecall), +return the remainder to the specified address.* + +*Note: for the case that the swap is used without the +protocol. Not sure if it should, though. needs to be discussed. +Send unused source token back.* + + +```solidity +function _allowTransfer(uint256 tokenAmount, address tokenAddress, address sovrynSwapNetwork) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`tokenAmount`|`uint256`|The amount to transfer.| +|`tokenAddress`|`address`|The address of the token to transfer.| +|`sovrynSwapNetwork`|`address`|The address of the sovrynSwap network contract.| + + +### _estimateSourceTokenAmount + +Calculate the number of source tokens to provide in order to +obtain the required destination amount. + + +```solidity +function _estimateSourceTokenAmount( + address sourceTokenAddress, + address destTokenAddress, + uint256 requiredDestTokenAmount, + uint256 maxSourceTokenAmount +) internal view returns (uint256 estimatedSourceAmount); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token address.| +|`destTokenAddress`|`address`|The address of the destination token address.| +|`requiredDestTokenAmount`|`uint256`|The number of destination tokens needed.| +|`maxSourceTokenAmount`|`uint256`|The maximum number of source tokens to spend.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`estimatedSourceAmount`|`uint256`|The estimated amount of source tokens needed. Minimum: minSourceTokenAmount, maximum: maxSourceTokenAmount| + + +### getExpectedRate + +Compute the expected rate for the maxSourceTokenAmount -> if spending less, we can't get a worse rate. +Compute the source tokens needed to get the required amount with the worst case rate. +If the actual rate is exactly the same as the worst case rate, we get rounding issues. So, add a small buffer. +buffer = min(estimatedSourceAmount/1000 , sourceBuffer) with sourceBuffer = 10000 +Never spend more than the maximum. + +Get the expected rate for 1 source token when exchanging the +given amount of source tokens. + + +```solidity +function getExpectedRate(address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) + public + view + returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token contract.| +|`destTokenAddress`|`address`|The address of the destination token contract.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens to get the rate for.| + + +### getExpectedReturn + +Is returning the total amount of destination tokens. +Return the rate for 1 token with 18 decimals. + +Get the expected return amount when exchanging the given +amount of source tokens. + +Right now, this function is being called directly by _swapsExpectedReturn from the protocol +So, this function is not using _getConversionPath function since it will try to read the defaultPath storage which is stored in the protocol's slot, and it will cause an issue for direct call. +Instead, this function is accepting additional parameters called defaultPath which value can be declared by the caller (protocol in this case). + + +```solidity +function getExpectedReturn(address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) + public + view + returns (uint256 expectedReturn); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source token contract.| +|`destTokenAddress`|`address`|The address of the destination token contract.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens to get the return for.| + + +### _getConversionPath + +Is returning the total amount of destination tokens. + + +```solidity +function _getConversionPath(address sourceTokenAddress, address destTokenAddress, ISovrynSwapNetwork sovrynSwapNetwork) + private + view + returns (IERC20[] memory path); +``` + +## Structs +### SwapParams + +```solidity +struct SwapParams { + address sourceTokenAddress; + address destTokenAddress; + address receiverAddress; + address returnToSenderAddress; + uint256 minSourceTokenAmount; + uint256 maxSourceTokenAmount; + uint256 requiredDestTokenAmount; +} +``` + diff --git a/foundry/docs/src/contracts/swaps/connectors/interfaces/IContractRegistry.sol/contract.IContractRegistry.md b/foundry/docs/src/contracts/swaps/connectors/interfaces/IContractRegistry.sol/contract.IContractRegistry.md new file mode 100644 index 000000000..eb0bc8914 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/interfaces/IContractRegistry.sol/contract.IContractRegistry.md @@ -0,0 +1,12 @@ +# IContractRegistry +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/swaps/connectors/interfaces/IContractRegistry.sol) + + +## Functions +### addressOf + + +```solidity +function addressOf(bytes32 contractName) public view returns (address); +``` + diff --git a/foundry/docs/src/contracts/swaps/connectors/interfaces/ISovrynSwapNetwork.sol/contract.ISovrynSwapNetwork.md b/foundry/docs/src/contracts/swaps/connectors/interfaces/ISovrynSwapNetwork.sol/contract.ISovrynSwapNetwork.md new file mode 100644 index 000000000..a17b93629 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/interfaces/ISovrynSwapNetwork.sol/contract.ISovrynSwapNetwork.md @@ -0,0 +1,33 @@ +# ISovrynSwapNetwork +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/swaps/connectors/interfaces/ISovrynSwapNetwork.sol) + + +## Functions +### convertByPath + + +```solidity +function convertByPath( + IERC20[] calldata _path, + uint256 _amount, + uint256 _minReturn, + address _beneficiary, + address _affiliateAccount, + uint256 _affiliateFee +) external payable returns (uint256); +``` + +### rateByPath + + +```solidity +function rateByPath(IERC20[] calldata _path, uint256 _amount) external view returns (uint256); +``` + +### conversionPath + + +```solidity +function conversionPath(IERC20 _sourceToken, IERC20 _targetToken) external view returns (IERC20[] memory); +``` + diff --git a/foundry/docs/src/contracts/swaps/connectors/interfaces/README.md b/foundry/docs/src/contracts/swaps/connectors/interfaces/README.md new file mode 100644 index 000000000..4c84376d7 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/interfaces/README.md @@ -0,0 +1,5 @@ + + +# Contents +- [IContractRegistry](IContractRegistry.sol/contract.IContractRegistry.md) +- [ISovrynSwapNetwork](ISovrynSwapNetwork.sol/contract.ISovrynSwapNetwork.md) diff --git a/foundry/docs/src/contracts/swaps/connectors/testnet/README.md b/foundry/docs/src/contracts/swaps/connectors/testnet/README.md new file mode 100644 index 000000000..0d464a1d5 --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/testnet/README.md @@ -0,0 +1,4 @@ + + +# Contents +- [SwapsImplLocal](SwapsImplLocal.sol/contract.SwapsImplLocal.md) diff --git a/foundry/docs/src/contracts/swaps/connectors/testnet/SwapsImplLocal.sol/contract.SwapsImplLocal.md b/foundry/docs/src/contracts/swaps/connectors/testnet/SwapsImplLocal.sol/contract.SwapsImplLocal.md new file mode 100644 index 000000000..b5b285d1e --- /dev/null +++ b/foundry/docs/src/contracts/swaps/connectors/testnet/SwapsImplLocal.sol/contract.SwapsImplLocal.md @@ -0,0 +1,115 @@ +# SwapsImplLocal +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/swaps/connectors/testnet/SwapsImplLocal.sol) + +**Inherits:** +[State](/contracts/core/State.sol/contract.State.md) + +Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. +Licensed under the Apache License, Version 2.0. + +This contract code comes from bZx. bZx is a protocol for tokenized +margin trading and lending https://bzx.network similar to the dYdX protocol. +This contract contains the implementation of swap process and rate calculations. + + +## Functions +### internalSwap + +Swap two tokens. + + +```solidity +function internalSwap( + address sourceTokenAddress, + address destTokenAddress, + address, + address returnToSenderAddress, + uint256 minSourceTokenAmount, + uint256 maxSourceTokenAmount, + uint256 requiredDestTokenAmount +) public payable returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source tokens.| +|`destTokenAddress`|`address`|The address of the destiny tokens.| +|``|`address`|| +|`returnToSenderAddress`|`address`|| +|`minSourceTokenAmount`|`uint256`|| +|`maxSourceTokenAmount`|`uint256`|| +|`requiredDestTokenAmount`|`uint256`|| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`destTokenAmountReceived`|`uint256`|The amount of destiny tokens sent.| +|`sourceTokenAmountUsed`|`uint256`|The amount of source tokens spent.| + + +### internalExpectedRate + +Send unused source token back. + +Calculate the expected price rate of swapping a given amount +of tokens. + + +```solidity +function internalExpectedRate( + address sourceTokenAddress, + address destTokenAddress, + uint256 sourceTokenAmount, + address unused +) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source tokens.| +|`destTokenAddress`|`address`|The address of the destiny tokens.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens.| +|`unused`|`address`|Fourth parameter ignored.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|precision The expected price rate.| + + +### internalExpectedReturn + +Calculate the expected return of swapping a given amount +of tokens. + + +```solidity +function internalExpectedReturn( + address sourceTokenAddress, + address destTokenAddress, + uint256 sourceTokenAmount, + address unused, + IERC20[] memory defaultPath +) public view returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`sourceTokenAddress`|`address`|The address of the source tokens.| +|`destTokenAddress`|`address`|The address of the destiny tokens.| +|`sourceTokenAmount`|`uint256`|The amount of source tokens.| +|`unused`|`address`|Fourth parameter ignored.| +|`defaultPath`|`IERC20[]`|defaultPath for swap.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|precision The expected return.| + + diff --git a/foundry/docs/src/contracts/token/IApproveAndCall.sol/interface.IApproveAndCall.md b/foundry/docs/src/contracts/token/IApproveAndCall.sol/interface.IApproveAndCall.md new file mode 100644 index 000000000..8e18eb3fb --- /dev/null +++ b/foundry/docs/src/contracts/token/IApproveAndCall.sol/interface.IApproveAndCall.md @@ -0,0 +1,25 @@ +# IApproveAndCall +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/token/IApproveAndCall.sol) + +*Interfaces are used to cast a contract address into a callable instance.* + + +## Functions +### receiveApproval + +Receives approval from SOV token. + + +```solidity +function receiveApproval(address _sender, uint256 _amount, address _token, bytes calldata _data) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_sender`|`address`|The sender of SOV.approveAndCall function.| +|`_amount`|`uint256`|The amount was approved.| +|`_token`|`address`|The address of token.| +|`_data`|`bytes`|The data will be used for low level call.| + + diff --git a/foundry/docs/src/contracts/token/OsSOV.sol/contract.OsSOV.md b/foundry/docs/src/contracts/token/OsSOV.sol/contract.OsSOV.md new file mode 100644 index 000000000..c17811ee0 --- /dev/null +++ b/foundry/docs/src/contracts/token/OsSOV.sol/contract.OsSOV.md @@ -0,0 +1,217 @@ +# OsSOV +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/token/OsSOV.sol) + +**Inherits:** +ERC20Capped, AccessControl, [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md), [Initializable](/contracts/openzeppelin/Initializable.sol/contract.Initializable.md) + +This contract accounts for all holders' balances. + +*This contract represents a token with dynamic supply. +The owner of the token contract can mint/burn tokens to/from any account +based upon previous governance voting and approval.* + + +## State Variables +### _NAME + +```solidity +string private constant _NAME = "BitcoinOS Sovryn Transition Token"; +``` + + +### _SYMBOL + +```solidity +string private constant _SYMBOL = "osSOV"; +``` + + +### _DECIMALS + +```solidity +uint8 private constant _DECIMALS = 18; +``` + + +### AUTHORISED_MINTER_ROLE + +```solidity +bytes32 public constant AUTHORISED_MINTER_ROLE = keccak256("AUTHORISED_MINTER_ROLE"); +``` + + +## Functions +### onlyMinter + + +```solidity +modifier onlyMinter(address _address); +``` + +### constructor + +*_disableInitializers locks the logic contract, preventing any future reinitialization. This cannot be part of an initializer call. +Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized +to any version. It is recommended to use this to lock implementation contracts that are designed to be called +through proxies.* + +*initializing Owner with address(1) because 0 address is not allowed* + + +```solidity +constructor() ERC20(_NAME, _SYMBOL) ERC20Capped(100_000_000 ether); +``` + +### initialize + + +```solidity +function initialize(address _owner, address _defaultAdmin, address _authorizedMinter) external initializer; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|Address for AccessControl OWNER_ROLE to use in onlyOwner() modifier| +|`_defaultAdmin`|`address`|Address for AcccessControl DEFAULT_ADMIN_ROLE to manage roles: assign and revoke| +|`_authorizedMinter`|`address`|Address of the minter - Staking Rewards contract| + + +### setDefaultAdminRole + + +```solidity +function setDefaultAdminRole(address _adminRole) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_adminRole`|`address`|Address for AcccessControl DEFAULT_ADMIN_ROLE to manage roles: assign and revoke| + + +### setAuthorisedMinterRole + + +```solidity +function setAuthorisedMinterRole(address _authorizedMinter) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_authorizedMinter`|`address`|Address of the minter - should be Staking Rewards contract| + + +### mint + +*Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). +Relies on the `_update` mechanism +Emits a {Transfer} event with `from` set to the zero address. +NOTE: This function is not override, {_update} should be overridden instead.* + + +```solidity +function mint(address _to, uint256 _amount) public onlyMinter(msg.sender); +``` + +### transfer + +*See [IERC20-transfer](/contracts/farm/LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md#transfer). +Requirements: +- non-transferable* + + +```solidity +function transfer(address, uint256) public pure override returns (bool); +``` + +### approve + +*See [IERC20-approve](/contracts/farm/LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md#approve). +NOTE: If `value` is the maximum `uint256`, the allowance is not updated on +`transferFrom`. This is semantically equivalent to an infinite approval. +- non-transferable via transferFrom* + + +```solidity +function approve(address, uint256) public override returns (bool); +``` + +### receive + +*Token is non-receivable* + + +```solidity +receive() external payable; +``` + +### name + +*Returns the name of the token.* + + +```solidity +function name() public pure override returns (string memory); +``` + +### symbol + + +```solidity +function symbol() public pure override returns (string memory); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`string`|Returns the symbol of the token, usually a shorter version of the name.| + + +### decimals + + +```solidity +function decimals() public pure override returns (uint8); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint8`|Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5.05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the default value returned by this function, unless it's overridden. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including [IERC20-balanceOf](/contracts/farm/LiquidityMiningConfigToken.sol/contract.LiquidityMiningConfigToken.md#balanceof) and {IERC20-transfer}.| + + +## Errors +### NonTransferable +*The token is non transferable.* + + +```solidity +error NonTransferable(); +``` + +### NonApprovable +*The token is non transferable via transferForm - approval is not allowed.* + + +```solidity +error NonApprovable(); +``` + +### NonReceivable +*The token is non receivable* + + +```solidity +error NonReceivable(); +``` + +### NotAllowedZeroAddressForParam +*address passed cannot be zero* + + +```solidity +error NotAllowedZeroAddressForParam(string param); +``` + diff --git a/foundry/docs/src/contracts/token/README.md b/foundry/docs/src/contracts/token/README.md new file mode 100644 index 000000000..75ffbc654 --- /dev/null +++ b/foundry/docs/src/contracts/token/README.md @@ -0,0 +1,6 @@ + + +# Contents +- [IApproveAndCall](IApproveAndCall.sol/interface.IApproveAndCall.md) +- [OsSOV](OsSOV.sol/contract.OsSOV.md) +- [SOV](SOV.sol/contract.SOV.md) diff --git a/foundry/docs/src/contracts/token/SOV.sol/contract.SOV.md b/foundry/docs/src/contracts/token/SOV.sol/contract.SOV.md new file mode 100644 index 000000000..aa5305cfd --- /dev/null +++ b/foundry/docs/src/contracts/token/SOV.sol/contract.SOV.md @@ -0,0 +1,91 @@ +# SOV +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/token/SOV.sol) + +**Inherits:** +[ERC20](/contracts/openzeppelin/ERC20.sol/contract.ERC20.md), [ERC20Detailed](/contracts/openzeppelin/ERC20Detailed.sol/contract.ERC20Detailed.md), [Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + +This contract accounts for all holders' balances. + +*This contract represents a token with dynamic supply. +The owner of the token contract can mint/burn tokens to/from any account +based upon previous governance voting and approval.* + + +## State Variables +### NAME + +```solidity +string constant NAME = "Sovryn Token"; +``` + + +### SYMBOL + +```solidity +string constant SYMBOL = "SOV"; +``` + + +### DECIMALS + +```solidity +uint8 constant DECIMALS = 18; +``` + + +## Functions +### constructor + +Constructor called on deployment, initiates the contract. + +*On deployment, some amount of tokens will be minted for the owner.* + + +```solidity +constructor(uint256 _initialAmount) public ERC20Detailed(NAME, SYMBOL, DECIMALS); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_initialAmount`|`uint256`|The amount of tokens to be minted on contract creation.| + + +### mint + +Creates new tokens and sends them to the recipient. + +*Don't create more than 2^96/10 tokens before updating the governance first.* + + +```solidity +function mint(address _account, uint256 _amount) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_account`|`address`|The recipient address to get the minted tokens.| +|`_amount`|`uint256`|The amount of tokens to be minted.| + + +### approveAndCall + +Approves and then calls the receiving contract. +Useful to encapsulate sending tokens to a contract in one call. +Solidity has no native way to send tokens to contracts. +ERC-20 tokens require approval to be spent by third parties, such as a contract in this case. + + +```solidity +function approveAndCall(address _spender, uint256 _amount, bytes memory _data) public; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_spender`|`address`|The contract address to spend the tokens.| +|`_amount`|`uint256`|The amount of tokens to be sent.| +|`_data`|`bytes`|Parameters for the contract call, such as endpoint signature.| + + diff --git a/foundry/docs/src/contracts/utils/AdminRole.sol/contract.AdminRole.md b/foundry/docs/src/contracts/utils/AdminRole.sol/contract.AdminRole.md new file mode 100644 index 000000000..2a708d3d8 --- /dev/null +++ b/foundry/docs/src/contracts/utils/AdminRole.sol/contract.AdminRole.md @@ -0,0 +1,71 @@ +# AdminRole +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/utils/AdminRole.sol) + +**Inherits:** +[Ownable](/contracts/openzeppelin/Ownable.sol/contract.Ownable.md) + + +## State Variables +### admins +*user => flag whether user has admin role.* + + +```solidity +mapping(address => bool) public admins; +``` + + +## Functions +### onlyAuthorized + +*Throws if called by any account other than the owner or admin. +or on our own overriding sovrynOwnable.* + + +```solidity +modifier onlyAuthorized(); +``` + +### addAdmin + +Add account to ACL. + + +```solidity +function addAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to grant permissions.| + + +### removeAdmin + +Remove account from ACL. + + +```solidity +function removeAdmin(address _admin) public onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_admin`|`address`|The addresses of the account to revoke permissions.| + + +## Events +### AdminAdded + +```solidity +event AdminAdded(address admin); +``` + +### AdminRemoved + +```solidity +event AdminRemoved(address admin); +``` + diff --git a/foundry/docs/src/contracts/utils/PausableRole.sol/contract.PausableRole.md b/foundry/docs/src/contracts/utils/PausableRole.sol/contract.PausableRole.md new file mode 100644 index 000000000..54ef607ef --- /dev/null +++ b/foundry/docs/src/contracts/utils/PausableRole.sol/contract.PausableRole.md @@ -0,0 +1,66 @@ +# PausableRole +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/utils/PausableRole.sol) + +**Inherits:** +[PausableOz](/contracts/openzeppelin/PausableOz.sol/contract.PausableOz.md) + + +## State Variables +### pauser + +```solidity +address public pauser; +``` + + +## Functions +### onlyPauserOrOwner + +*Modifier to make a function callable only when the caller is pauser or owner* + + +```solidity +modifier onlyPauserOrOwner(); +``` + +### setPauser + +Set the pauser address. +only pauser can perform this action. + + +```solidity +function setPauser(address newPauser) external onlyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`newPauser`|`address`|The new address of the pauser.| + + +### pause + +*Called by the owner to pause, triggers stopped state.* + + +```solidity +function pause() public onlyPauserOrOwner whenNotPaused; +``` + +### unpause + +*Called by the owner to unpause, returns to normal state.* + + +```solidity +function unpause() public onlyPauserOrOwner whenPaused; +``` + +## Events +### SetPauser + +```solidity +event SetPauser(address indexed sender, address indexed oldPauser, address indexed newPauser); +``` + diff --git a/foundry/docs/src/contracts/utils/ProxyOwnable.sol/contract.ProxyOwnable.md b/foundry/docs/src/contracts/utils/ProxyOwnable.sol/contract.ProxyOwnable.md new file mode 100644 index 000000000..4f5304477 --- /dev/null +++ b/foundry/docs/src/contracts/utils/ProxyOwnable.sol/contract.ProxyOwnable.md @@ -0,0 +1,93 @@ +# ProxyOwnable +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/utils/ProxyOwnable.sol) + +Based on OpenZeppelin's Ownable contract: +https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + +*Contract module which provides a basic access control mechanism, where +there is an account (an owner) that can be granted exclusive access to +specific functions. +This module is used through inheritance. It will make available the modifier +`onlyOwner`, which can be applied to your functions to restrict their use to +the owner.* + + +## State Variables +### KEY_OWNER + +```solidity +bytes32 private constant KEY_OWNER = keccak256("key.proxy.owner"); +``` + + +## Functions +### constructor + +*Initializes the contract setting the deployer as the initial owner.* + + +```solidity +constructor() internal; +``` + +### onlyProxyOwner + +*Throws if called by any account other than the owner.* + + +```solidity +modifier onlyProxyOwner(); +``` + +### _setProxyOwner + +Set address of the owner. + + +```solidity +function _setProxyOwner(address _owner) internal; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|Address of the owner.| + + +### setProxyOwner + +Set address of the owner (only owner can call this function) + + +```solidity +function setProxyOwner(address _owner) public onlyProxyOwner; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|Address of the owner.| + + +### getProxyOwner + +Return address of the owner. + + +```solidity +function getProxyOwner() public view returns (address _owner); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`_owner`|`address`|Address of the owner.| + + +## Events +### ProxyOwnershipTransferred + +```solidity +event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner); +``` + diff --git a/foundry/docs/src/contracts/utils/README.md b/foundry/docs/src/contracts/utils/README.md new file mode 100644 index 000000000..051fb5a54 --- /dev/null +++ b/foundry/docs/src/contracts/utils/README.md @@ -0,0 +1,7 @@ + + +# Contents +- [AdminRole](AdminRole.sol/contract.AdminRole.md) +- [PausableRole](PausableRole.sol/contract.PausableRole.md) +- [ProxyOwnable](ProxyOwnable.sol/contract.ProxyOwnable.md) +- [Utils](Utils.sol/library.Utils.md) diff --git a/foundry/docs/src/contracts/utils/Utils.sol/library.Utils.md b/foundry/docs/src/contracts/utils/Utils.sol/library.Utils.md new file mode 100644 index 000000000..3eb118d93 --- /dev/null +++ b/foundry/docs/src/contracts/utils/Utils.sol/library.Utils.md @@ -0,0 +1,12 @@ +# Utils +[Git Source](https://github.com/DistributedCollective/Sovryn-smart-contracts/blob/94f13d57265df5aa5e3e27b26f74b7e829502d36/contracts/utils/Utils.sol) + + +## Functions +### stringToBytes32 + + +```solidity +function stringToBytes32(string memory source) internal pure returns (bytes32 result); +``` + diff --git a/package.json b/package.json index 2f9323108..dc4a8d15d 100644 --- a/package.json +++ b/package.json @@ -82,6 +82,9 @@ "contract-size": "yarn run hardhat size-contracts", "coverage": "npx hardhat coverage", "doc": "yarn docgen", + "doc:forge": "forge doc --build", + "doc:serve": "cd foundry/docs && mdbook serve --open", + "doc:forge-all": "forge doc --build && cd foundry/docs && mdbook serve --open", "lint": "npm run lint-sol && npm run lint-js", "lint-sol": "solhint contracts/{*,**/*,**/**/*,**/**/**/*,**/**/**/**/*}.sol", "lint-js": "eslint . --ext .js",