Smart Contracts
Overview
Buttonwood V1 consists of two contract packages: Core (the protocol's fundamental logic) and Periphery (user-facing helpers and vaults).
Contract Properties
| Contract | Upgradeable | Pausable | Permissions | Notes |
|---|---|---|---|---|
| OriginationPoolScheduler | Yes (UUPS) | Yes | Yes | |
| OriginationPool | No | Yes | Yes | ERC20 receipt tokens |
| GeneralManager | Yes (UUPS) | Yes | Yes | |
| LoanManager | No | No | No | Flash-swaps via Consol |
| MortgageNFT | No | No | No | ERC721 |
| OrderPool | No | No | Yes | |
| SubConsol | No | No | Yes | ERC20 (not rebasing) |
| USDX | No | No | Yes | Rebasing |
| Consol | No | No | Yes | Rebasing |
| ForfeitedAssetsPool | No | Yes | Yes | ERC20 (not rebasing) |
| ConversionQueue | No | No | Yes | LenderQueue + MortgageQueue |
| UsdxQueue | No | Yes | Yes | LenderQueue |
| ForfeitedAssetsQueue | No | Yes | Yes | LenderQueue |
| PythPriceOracle | No | No | No | Pyth pull-oracle |
| PythInterestRateOracle | No | No | No | Pyth pull-oracle |
Core Contracts
Token Contracts
| Contract | Description |
|---|---|
| USDX | Unified USD-pegged vault wrapping multiple stablecoins with configurable scaling factors into a standard 18-decimal rebasing token |
| Consol | The protocol's main rebasing treasury token — backed by USDX, ForfeitedAssetsPool, and SubConsol tokens. Provides flash swap functionality for efficient asset swapping. Withdrawal restricted to authorized queues. |
| SubConsol | Collateral-specific vault that accepts a single collateral type, mints tokens based on principal borrowed, and can deploy collateral to yield strategies for additional returns. Not rebasing. |
| RebasingERC20 | Abstract shares-based ERC20 where balances adjust based on underlying asset value — enables passive yield accrual |
| MultiTokenVault | Abstract vault accepting multiple ERC20 deposits, minting a single rebasing token. Provides relative token caps and registry. |
Lending & Borrowing
| Contract | Description |
|---|---|
| GeneralManager | Central upgradeable orchestrator. Validates and routes mortgage requests through OriginationPools, coordinates oracles, manages collateral types and terms, handles balance sheet expansions. |
| LoanManager | Manages full mortgage lifecycle — creation (depositing collateral into SubConsols), payment processing with automatic late fees, redemption, refinancing, foreclosure, and conversions |
| MortgageNFT | ERC-721 representing ownership of a mortgage position. Manages user-chosen MortgageId labels. |
| OriginationPool | Non-upgradeable lending pool. Accepts USDX deposits (Deposit phase), flash-deploys for origination receiving Consol repayment (Deploy phase), allows proportional USDX+Consol redemption (Redemption phase). Withdrawals never affected by pause. |
| OriginationPoolScheduler | Creates new OriginationPools on a weekly schedule. Manages pool configurations including limits, growth rates, and multipliers. |
| OrderPool | Order book holding PurchaseOrders for collateral. Authorized fulfillers process orders by providing collateral in exchange for USDX, while expired orders are deleted and NFTs burned. |
Queues & Processing
| Contract | Description |
|---|---|
| ConversionQueue | Double-queue: lenders deposit Consol to get collateral with a premium; borrowers submit mortgages to be converted when prices trigger. Processes by liquidating portions of qualified mortgages at market prices with lump-sum interest rewarded to withdrawers. |
| UsdxQueue | FIFO withdrawal queue — users deposit Consol and receive USDX. Permissionless processing with gas fee collection. |
| ForfeitedAssetsQueue | FIFO withdrawal queue — users deposit Consol to burn ForfeitedAssetsPool tokens for underlying foreclosed collateral. Value received may exceed Consol deposited. |
| MortgageQueue | Sorted linked-list of mortgage positions ordered by trigger price (lowest to highest) for efficient conversion processing |
| LenderQueue | Abstract base for FIFO withdrawal queues with gas fees, minimum amounts, and cancellation logic |
| QueueProcessor | Processes items across the various queues |
Oracles
| Contract | Description |
|---|---|
| PythPriceOracle | Pull-oracle for real-time collateral/USD prices. Validates freshness (max 60s) and confidence thresholds. |
| PythInterestRateOracle | Reads 3yr and 5yr US Treasury rates from Pyth, multiplies by 2, adds 100 bps (+100 bps more if no payment plan). Reverts if age > 60s or confidence > 100 bps. |
| StaticInterestRateOracle | Fallback fixed interest rate oracle |
Other
| Contract | Description |
|---|---|
| ForfeitedAssetsPool | Holds collateral from foreclosed mortgages, issues liability tokens. Users burn Consol to redeem proportional foreclosed collateral at a discount, removing bad debt from the protocol. |
Periphery Contracts
| Contract | Description |
|---|---|
| Router | Entry point for all user transactions — handles multi-step flows (wrap, approve, deposit) |
| RolloverVault | Automated vault that re-invests lender capital across pool epochs |
| FulfillmentVault | Vault providing liquidity for order fulfillment on the chain's trading venue |
| LiquidityVault | Abstract base for vault share token mechanics |
Contract Interactions
┌────────────────┐
│ Router │ ◄── User entry point
└───────┬────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────────┐ ┌─────────────┐ ┌──────────────┐
│GeneralManager│ │ USDX │ │ Origination │
│ │ │ │ │ Pool │
└──────┬───────┘ └──────┬──────┘ └──────┬───────┘
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌─────────────┐ ┌──────────────┐
│ LoanManager │ │ Consol │◄│ OrderPool │
└──────┬───────┘ └──────┬──────┘ └──────────────┘
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐ ┌─────────────┐
│ MortgageNFT │ │ SubConsol │ │ UsdxQueue │
└──────────────┘ │ (escrow) │ ├─────────────┤
└──────┬───────┘ │ForfeitedAsQ │
│ ├─────────────┤
▼ │Conversion Q │
┌──────────────┐ └─────────────┘
│ Conversion │
│ Queue │
└──────────────┘
Access Control
The protocol uses role-based access control across multiple contracts. See the Glossary — Roles section for a complete reference of all roles, their intended holders, and applicable contracts.
Key roles:
- Default Admin (Governance) — Manage supported tokens, set caps, assign roles, upgrade contracts
- Withdraw Role — Authorized contracts that can withdraw/flash-swap from Consol
- Pause Role (Governance + automated safety) — Emergency pause of deposits, deployments, and operations
- Fulfillment Role (Market maker) — Sell collateral to OrderPool and receive USDX
- Deploy Role (GeneralManager) — Flash-loan USDX from OriginationPools
Key Interfaces
| Interface | Purpose |
|---|---|
| IInterestRateOracle | Dynamic interest rates based on term length and payment structure |
| IPriceOracle | Real-time collateral pricing in USDX terms |
| IConsolFlashSwap | Flash swap callback for temporarily borrowing from Consol |
| IOriginationPoolDeployCallback | Callback for origination pool fund deployment (flash-lending) |
| IYieldStrategy | Yield-generating strategies for SubConsol collateral |
| INFTMetadataGenerator | Dynamic metadata generation for Mortgage NFTs |
Deployment
The contracts are chain-agnostic and deploy to any EVM chain carrying supported collateral and a price feed; deployment to Robinhood Chain is forthcoming. The protocol uses deterministic deployment via Foundry scripts for reproducible addresses, and per-chain addresses live in the @repo/deployments address book.
Core Contracts
Reference for every contract in the core package (buttonwood-protocol/cash), generated from the contract source. Each contract lists its state variables, functions, events, and errors.
Consol
Inherits: IConsol, MultiTokenVault, ReentrancyGuard
Title: Consol
Author: @SocksNFlops
A rebasing ERC20 token that is backed by a pool of tokens, notably usdx and a forfeited assets pool. Include a redemption pool for withdrawing usdx.
State Variables
forfeitedAssetsPool
Get the address of the forfeited assets pool.
address public forfeitedAssetsPool
Functions
constructor
Constructor
constructor(
string memory name_,
string memory symbol_,
uint8 decimalsOffset_,
address admin_,
address forfeitedAssetsPool_
) MultiTokenVault(name_, symbol_, decimalsOffset_, admin_);
Parameters
| Name | Type | Description |
|---|---|---|
name_ | string | The name of the token |
symbol_ | string | The symbol of the token |
decimalsOffset_ | uint8 | The number of decimals to pad the internal shares with to avoid precision loss |
admin_ | address | The address of the admin |
forfeitedAssetsPool_ | address | The address of the forfeited assets pool |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual override(MultiTokenVault) returns (bool);
setForfeitedAssetsPool
Set the address of the forfeited assets pool.
function setForfeitedAssetsPool(address forfeitedAssetsPool_) external override onlyRole(Roles.SUPPORTED_TOKEN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
forfeitedAssetsPool_ | address | The address of the forfeited assets pool |
withdraw
Withdraw tokens from the MultiTokenVault and burn an equivalent amount of the MultiTokenVault token.
function withdraw(address token, uint256 amount)
public
virtual
override(IMultiTokenVault, MultiTokenVault)
onlyRole(Roles.WITHDRAW_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to withdraw |
amount | uint256 | The amount of tokens to withdraw |
flashSwap
Flash swap tokens. Caller must implement the IConsolFlashSwap interface.
function flashSwap(address inputToken, address outputToken, uint256 amount, bytes calldata data)
external
override
onlyRole(Roles.WITHDRAW_ROLE)
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token |
outputToken | address | The address of the output token |
amount | uint256 | The amount of tokens to swap |
data | bytes | The data to pass into the callback |
_totalSupply
Checks that the forfeited assets pool is set before returning the total supply
function _totalSupply() internal view virtual override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total supply of the Consol token |
ConversionQueue
Inherits: LenderQueue, MortgageQueue, IConversionQueue
Title: ConversionQueue
Author: SocksNFlops
The ConversionQueue contract is responsible for converting mortgages by reducing the principal and collateral as a result of a withdrawal request
State Variables
nativeWrapper
Get the native token wrapper contract (whype/weth/etc).
address public immutable override nativeWrapper
generalManager
Get the GeneralManager contract.
address public immutable override generalManager
decimals
The number of decimals of the collateral
uint8 public immutable override decimals
Functions
constructor
Constructor
constructor(
address asset_,
uint8 decimals_,
address consol_,
address nativeWrapper_,
address generalManager_,
address admin_
) LenderQueue(asset_, consol_, admin_);
Parameters
| Name | Type | Description |
|---|---|---|
asset_ | address | The address of the asset to convert |
decimals_ | uint8 | The number of decimals of the asset |
consol_ | address | The address of the Consol contract |
nativeWrapper_ | address | The address of the native wrapper contract |
generalManager_ | address | The address of the GeneralManager contract |
admin_ | address | The address of the admin |
supportsInterface
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(LenderQueue, MortgageQueue)
returns (bool);
convertingPrice
The current price of the collateral in USD
function convertingPrice() public view override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The price of the collateral in USD |
_calculateCollateralToUse
Calculates the collateral to use out of a mortgage position for a withdrawal request
function _calculateCollateralToUse(MortgagePosition memory mortgagePosition, uint256 amountToUse)
internal
view
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
mortgagePosition | MortgagePosition | The mortgage position to calculate the collateral to use for |
amountToUse | uint256 | The amount of principal to use for the withdrawal request |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The collateral to use for the withdrawal request |
enqueueMortgage
Enqueues a mortgage position into the conversion queue. If the mortgage position is already in the queue, it will be removed and enqueued again with a potentially new price.
function enqueueMortgage(uint256 mortgageTokenId, uint256 hintPrevId)
external
payable
override
whenNotPaused
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
mortgageTokenId | uint256 | The tokenId of the mortgage position |
hintPrevId | uint256 | The hintPrevId of the mortgage position |
processWithdrawalRequests
Process the requests from the front of the USDX withdrawal queue. Callable by anyone by contracts with the PROCESSOR_ROLE.
function processWithdrawalRequests(uint256 iterations, address receiver)
external
override(ILenderQueue, LenderQueue)
nonReentrant
whenNotPaused
onlyRole(Roles.PROCESSOR_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
iterations | uint256 | The number of iterations to process. Each iteration returns collected gas fees. |
receiver | address | The address to receive the gas fees |
dequeueMortgage
Dequeues a mortgage position from the conversion queue. Only callable on an inactive mortgage position.
function dequeueMortgage(uint256 mortgageTokenId) external override;
Parameters
| Name | Type | Description |
|---|---|---|
mortgageTokenId | uint256 | The tokenId of the mortgage position |
ForfeitedAssetsPool
Inherits: IForfeitedAssetsPool, ERC165, AccessControl, ERC20
Title: The Forfeited Assets Pool contract
Author: SocksNFlops
The Forfeited Assets Pool is a contract that holds assets seized from foreclosed mortgages. They can be purchased for Consol that is burned in exchange.
In order to minimize smart contract risk, we are hedging towards immutability.
State Variables
assets
The set of assets in the forfeited assets pool
EnumerableSet.AddressSet private assets
paused
Get the paused state of the contract
bool public override paused
Functions
constructor
Constructor
constructor(string memory name_, string memory symbol_, address _admin) ERC20(name_, symbol_);
Parameters
| Name | Type | Description |
|---|---|---|
name_ | string | The name of the token |
symbol_ | string | The symbol of the token |
_admin | address | The address of the admin |
whenNotPaused
Modifier to check if the contract is paused
modifier whenNotPaused() ;
supportsInterface
function supportsInterface(bytes4 interfaceId) public view override(ERC165, AccessControl) returns (bool);
addAsset
Add an asset to the forfeited assets pool. Only callable by admin role.
function addAsset(address asset) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | The address of the asset to add |
removeAsset
Remove an asset from the forfeited assets pool. Only callable by admin role.
function removeAsset(address asset) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | The address of the asset to remove |
getAsset
Get the list of assets in the forfeited assets pool
function getAsset(uint256 index) external view override returns (address);
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the asset to get |
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the asset at the given index |
totalAssets
Get the total amount of assets in the forfeited assets pool
function totalAssets() external view override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total amount of assets in the forfeited assets pool |
depositAsset
Deposits an asset into the forfeited assets pool and updates the foreclosed liabilities. Only callable by permissioned depositors.
function depositAsset(address asset, uint256 amount, uint256 liability)
external
override
whenNotPaused
onlyRole(Roles.DEPOSITOR_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | The address of the asset to deposit |
amount | uint256 | The amount of the asset to deposit |
liability | uint256 | The liability to add to the foreclosed liabilities |
burn
Purchase assets from the forfeited assets pool in proportion to the amount of Consol burned. redemptionPercentage = (amount / foreclosedLiabilities)
function burn(address receiver, uint256 liability)
external
override
whenNotPaused
returns (address[] memory redeemedAssets, uint256[] memory redeemedAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address | The address to send the assets to |
liability | uint256 | The amount of liabilities to burn in order to purchase assets from the forfeited assets pool. |
Returns
| Name | Type | Description |
|---|---|---|
redeemedAssets | address[] | The list of assets purchased |
redeemedAmounts | uint256[] | The amount of assets purchased |
setPaused
Pause or unpause the contract
function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
pause | bool | The new paused state |
ForfeitedAssetsQueue
Inherits: LenderQueue
Title: ForfeitedAssetsQueue
Author: @SocksNFlops
Queue for withdrawing assets from the ForfeitedAssetsPool contract.
Functions
constructor
Constructor
constructor(address asset_, address consol_, address admin_) LenderQueue(asset_, consol_, admin_);
Parameters
| Name | Type | Description |
|---|---|---|
asset_ | address | The address of the forfeited assets pool |
consol_ | address | The address of the Consol contract |
admin_ | address | The address of the admin |
processWithdrawalRequests
function processWithdrawalRequests(uint256 iterations, address receiver)
external
virtual
override
nonReentrant
whenNotPaused
onlyRole(Roles.PROCESSOR_ROLE);
GeneralManager
Inherits: Initializable, ERC165Upgradeable, AccessControlUpgradeable, UUPSUpgradeable, IGeneralManager, ReentrancyGuard
Title: GeneralManager
Author: SocksNFlops
The GeneralManager contract manages the origination of mortgage positions using origination pools
State Variables
GeneralManagerStorageLocation
The storage location of the GeneralManager contract
keccak256(abi.encode(uint256(keccak256("buttonwood.storage.GeneralManager")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant GeneralManagerStorageLocation =
0xa0fde9a47799f0a64e9adfc0ccfed9fa7d54162399ca936d199d08c2d005ad00
Functions
_getGeneralManagerStorage
Gets the storage location of the GeneralManager contract
function _getGeneralManagerStorage() private pure returns (GeneralManagerStorage storage $);
Returns
| Name | Type | Description |
|---|---|---|
$ | GeneralManagerStorage | The storage location of the GeneralManager contract |
__GeneralManager_init
Initializes the GeneralManager contract and calls parent initializers
function __GeneralManager_init(
address usdx_,
address consol_,
uint16 penaltyRate_,
uint16 refinanceRate_,
uint16 conversionPremiumRate_,
uint16 priceSpread_,
address insuranceFund_,
address interestRateOracle_
) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
usdx_ | address | The address of the USDX token |
consol_ | address | The address of the Consol token |
penaltyRate_ | uint16 | The penalty rate |
refinanceRate_ | uint16 | The refinancing rate |
conversionPremiumRate_ | uint16 | The conversion premium rate |
priceSpread_ | uint16 | The price spread |
insuranceFund_ | address | The address of the insurance fund |
interestRateOracle_ | address | The address of the interest rate oracle |
__GeneralManager_init_unchained
Initializes only the GeneralManager contract
function __GeneralManager_init_unchained(
address usdx_,
address consol_,
uint16 penaltyRate_,
uint16 refinanceRate_,
uint16 conversionPremiumRate_,
uint16 priceSpread_,
address insuranceFund_,
address interestRateOracle_
) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
usdx_ | address | The address of the USDX token |
consol_ | address | The address of the Consol token |
penaltyRate_ | uint16 | The penalty rate |
refinanceRate_ | uint16 | The refinancing rate |
conversionPremiumRate_ | uint16 | The conversion premium rate |
priceSpread_ | uint16 | The price spread |
insuranceFund_ | address | The address of the insurance fund |
interestRateOracle_ | address | The address of the interest rate oracle |
initialize
Initializes the GeneralManager contract
function initialize(
address usdx_,
address consol_,
uint16 penaltyRate_,
uint16 refinanceRate_,
uint16 conversionPremiumRate_,
uint16 priceSpread_,
address insuranceFund_,
address interestRateOracle_
) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
usdx_ | address | The address of the USDX token |
consol_ | address | The address of the Consol token |
penaltyRate_ | uint16 | The penalty rate |
refinanceRate_ | uint16 | The refinancing rate |
conversionPremiumRate_ | uint16 | The conversion premium rate |
priceSpread_ | uint16 | The price spread |
insuranceFund_ | address | The address of the insurance fund |
interestRateOracle_ | address | The address of the interest rate oracle |
constructor
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
_authorizeUpgrade
Function that should revert when msg.sender is not authorized to upgrade the contract. Called by
{upgradeToAndCall}.
Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
function _authorizeUpgrade(address) internal onlyOwner {}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
whenNotPaused
Modifier to check if the contract is paused
modifier whenNotPaused() ;
onlyOrderPool
Modifier to check if the caller is the order pool
modifier onlyOrderPool() ;
onlyRegisteredOriginationPool
Modifier to check if the caller is an origination pool
modifier onlyRegisteredOriginationPool() ;
_addConversionQueues
Appends the conversionQueueList to the recorded conversion queues for a mortgage position
function _addConversionQueues(uint256 tokenId, address[] memory conversionQueueList) internal;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
conversionQueueList | address[] | The list of conversion queues to update |
_calculateRequiredGasFee
Calculates the required gas fee for the caller
function _calculateRequiredGasFee(bool usingOrderPool, address[] memory conversionQueueList)
internal
view
returns (uint256 requiredGasFee);
Parameters
| Name | Type | Description |
|---|---|---|
usingOrderPool | bool | Whether the caller is using the order pool |
conversionQueueList | address[] | The list of conversion queues to calculate the required gas fee for |
Returns
| Name | Type | Description |
|---|---|---|
requiredGasFee | uint256 | The required gas fee |
_checkSufficientGas
Checks if the caller sent enough value to cover the required gas fee
function _checkSufficientGas(uint256 requiredGasFee) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
requiredGasFee | uint256 | The required gas fee |
_refundSurplusGas
Refunds the surplus gas to the caller
function _refundSurplusGas(uint256 requiredGasFee) internal;
Parameters
| Name | Type | Description |
|---|---|---|
requiredGasFee | uint256 | The required gas fee |
_validateMortgageOwner
Validates that the caller is the owner of the mortgage
function _validateMortgageOwner(uint256 tokenId) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
_validateTotalPeriods
Validates that the total periods is supported for the collateral
function _validateTotalPeriods(address collateral, uint8 totalPeriods) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The collateral address |
totalPeriods | uint8 | The total periods |
onlyMortgageOwner
Modifier to check if the caller is the owner of the mortgage
modifier onlyMortgageOwner(uint256 tokenId) ;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
_validateBorrowCaps
Validates that the amount being borrowed exceeds the minimum cap and does not exceed the maximum cap
function _validateBorrowCaps(MortgageParams memory mortgageParams) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
mortgageParams | MortgageParams | The mortgage parameters |
_validateOriginationPools
Validates that the origination pools are supported
function _validateOriginationPools(address[] memory originationPools) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
originationPools | address[] | The origination pools |
_validateConversionQueues
Validates that the conversion queues have the CONVERSION_ROLE role
function _validateConversionQueues(address[] memory conversionQueueList) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
conversionQueueList | address[] | The list of conversion queues to validate |
_replaceNFTRole
Revokes the NFT role of an address and grants it to a new address
function _replaceNFTRole(address oldRoleHolder, address newRoleHolder) internal;
Parameters
| Name | Type | Description |
|---|---|---|
oldRoleHolder | address | The address to remove the NFT role from |
newRoleHolder | address | The address to grant the NFT role to |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId)
public
view
override(AccessControlUpgradeable, ERC165Upgradeable)
returns (bool);
usdx
Returns the USDX token address
function usdx() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The USDX token address |
consol
Returns the Consol token address
function consol() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The Consol token address |
setPenaltyRate
Sets the penalty rate for a mortgage (in basis points)
function setPenaltyRate(uint16 penaltyRate_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
penaltyRate_ | uint16 | The penalty rate |
penaltyRate
Returns the penalty rate for a mortgage (in basis points)
Takes in a mortgage position to allow upgraded implementations to take into account the position's details.
function penaltyRate(MortgagePosition memory) external view returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | MortgagePosition |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint16 | The penalty rate |
setRefinanceRate
Sets the refinance rate for a mortgage (in basis points)
function setRefinanceRate(uint16 refinanceRate_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
refinanceRate_ | uint16 | The refinance rate |
refinanceRate
Returns the refinance rate (in basis points).
Takes in a mortgage position to allow upgraded implementations to take into account the position's details.
function refinanceRate(MortgagePosition memory) external view returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | MortgagePosition |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint16 | The refinance rate |
setInsuranceFund
Sets the insurance fund address
function setInsuranceFund(address insuranceFund_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
insuranceFund_ | address | The insurance fund address |
insuranceFund
Returns the insurance fund address
function insuranceFund() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The insurance fund address |
setInterestRateOracle
Sets the interest rate oracle address
function setInterestRateOracle(address interestRateOracle_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
interestRateOracle_ | address | The interest rate oracle address |
interestRateOracle
Returns the interest rate oracle address
function interestRateOracle() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The interest rate oracle address |
interestRate
Returns the interest rate (in basis points)
function interestRate(address collateral, uint8 totalPeriods, bool hasPaymentPlan) public view returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
totalPeriods | uint8 | The total number of periods for the mortgage |
hasPaymentPlan | bool | Whether the mortgage has a payment plan |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint16 | The interest rate |
conversionPremiumRate
Returns the conversion premium rate (in basis points)
function conversionPremiumRate(address, uint8, bool) public view returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | address | |
<none> | uint8 | |
<none> | bool |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint16 | The conversion premium rate |
setConversionPremiumRate
Sets the conversion premium rate (in basis points)
function setConversionPremiumRate(uint16 conversionPremiumRate_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
conversionPremiumRate_ | uint16 | The conversion premium rate |
setOriginationPoolScheduler
Sets the origination pool scheduler address
function setOriginationPoolScheduler(address originationPoolScheduler_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
originationPoolScheduler_ | address | The origination pool scheduler address |
originationPoolScheduler
Returns the origination pool scheduler address
function originationPoolScheduler() public view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The origination pool scheduler address |
setLoanManager
Sets the loan manager address
function setLoanManager(address loanManager_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
loanManager_ | address | The loan manager address |
loanManager
Returns the loan manager address
function loanManager() public view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The loan manager address |
mortgageNFT
Returns the mortgage NFT address
function mortgageNFT() public view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The mortgage NFT address |
setOrderPool
Sets the order pool address
function setOrderPool(address orderPool_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
orderPool_ | address | The order pool address |
orderPool
Returns the order pool address
function orderPool() public view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The order pool address |
updateSupportedMortgagePeriodTerms
Updates the supported mortgage period terms for a collateral.
function updateSupportedMortgagePeriodTerms(address collateral, uint8 mortgagePeriods, bool isSupported)
external
onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
mortgagePeriods | uint8 | |
isSupported | bool | Whether the mortgage period term is supported |
isSupportedMortgagePeriodTerms
Returns whether a mortgage period term is supported
function isSupportedMortgagePeriodTerms(address collateral, uint8 mortgagePeriods) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
mortgagePeriods | uint8 | The mortgage period |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | Whether the mortgage period term is supported |
setPriceOracle
Sets the address of the price oracle
function setPriceOracle(address collateral, address priceOracle) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
priceOracle | address | The address of the price oracle |
priceOracles
The address of the price oracle for the collateral
function priceOracles(address collateral) external view returns (address);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the price oracle |
setMinimumCap
Sets the minimum request size of a mortgage for a given collateral. Requests cannot borrow less than this amount.
function setMinimumCap(address collateral, uint256 minimumCap_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
minimumCap_ | uint256 | The minimum cap |
minimumCap
Returns the minimum request size of a mortgage for a given collateral. Requests cannot borrow less than this amount.
function minimumCap(address collateral) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The minimum cap |
setMaximumCap
Sets the maximum request size of a mortgage for a given collateral. Requests cannot borrow more than this amount.
function setMaximumCap(address collateral, uint256 maximumCap_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
maximumCap_ | uint256 | The maximum cap |
maximumCap
Returns the maximum request size of a mortgage for a given collateral. Requests cannot borrow more than this amount.
function maximumCap(address collateral) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The maximum cap |
setPriceSpread
Sets the price spread to incentivize the fulfiller to fill orders
function setPriceSpread(uint16 priceSpread_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
priceSpread_ | uint16 | The price spread |
priceSpread
The price spread to incentivize the fulfiller to fill orders
function priceSpread() external view returns (uint16);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint16 | priceSpread The price spread |
conversionQueues
Returns the conversion queues a given mortgage position is registered with
function conversionQueues(uint256 tokenId) public view returns (address[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | The conversion queues |
_calculateCost
Calculates the cost of the collateral
function _calculateCost(address collateral, uint256 collateralAmount)
internal
view
returns (uint256 cost, uint8 collateralDecimals);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral token |
collateralAmount | uint256 | The amount of collateral to calculate the cost for |
Returns
| Name | Type | Description |
|---|---|---|
cost | uint256 | The cost of the collateral |
collateralDecimals | uint8 | The decimals of the collateral token |
_prepareOrder
Prepares the mortgageParams and orderAmounts for an order
function _prepareOrder(
uint256 tokenId,
BaseRequest calldata baseRequest,
address collateral,
address subConsol,
bool hasPaymentPlan
)
internal
view
returns (MortgageParams memory mortgageParams, OrderAmounts memory orderAmounts, uint256[] memory borrowAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage NFT |
baseRequest | BaseRequest | The base request for the mortgage |
collateral | address | The address of the collateral token |
subConsol | address | The address of the subConsol contract |
hasPaymentPlan | bool | Whether the mortgage has a payment plan |
Returns
| Name | Type | Description |
|---|---|---|
mortgageParams | MortgageParams | The mortgage parameters |
orderAmounts | OrderAmounts | The order amounts |
borrowAmounts | uint256[] | The amounts being borrowed from each origination pool |
_sendOrder
Sends completed order to the order pool
function _sendOrder(
uint256[] memory borrowAmounts,
MortgageParams memory mortgageParams,
OrderAmounts memory orderAmounts,
BaseRequest calldata baseRequest,
address[] memory conversionQueueList,
uint256 requiredGasFee,
bool expansion
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
borrowAmounts | uint256[] | The amounts being borrowed from each origination pool |
mortgageParams | MortgageParams | The mortgage parameters |
orderAmounts | OrderAmounts | The order amounts |
baseRequest | BaseRequest | The base request for the mortgage |
conversionQueueList | address[] | The addresses of the conversion queues to use |
requiredGasFee | uint256 | The required gas fee |
expansion | bool | Whether the request is a new mortgage creation or a balance sheet expansion |
_sendRequest
Sends a request to the order pool
function _sendRequest(
BaseRequest calldata baseRequest,
uint256 tokenId,
address collateral,
address subConsol,
address[] memory conversionQueueList,
uint256 requiredGasFee,
bool hasPaymentPlan,
bool expansion
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
baseRequest | BaseRequest | The base request for the mortgage |
tokenId | uint256 | The ID of the mortgage NFT |
collateral | address | The address of the collateral token |
subConsol | address | The address of the subConsol contract |
conversionQueueList | address[] | The addresses of the conversion queues to use |
requiredGasFee | uint256 | The required gas fee |
hasPaymentPlan | bool | Whether the mortgage has a payment plan |
expansion | bool | Whether the request is a new mortgage creation or a balance sheet expansion |
requestMortgageCreation
Requests a new mortgage creation
function requestMortgageCreation(CreationRequest calldata creationRequest)
external
payable
whenNotPaused
nonReentrant
returns (uint256 tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
creationRequest | CreationRequest | The parameters of the mortgage creation being requested |
Returns
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage NFT that was created |
requestBalanceSheetExpansion
Requests to expand the balance sheet of a mortgage position by adding additional principal and collateral to the mortgage position. Only callable by whitelisted addresses.
function requestBalanceSheetExpansion(ExpansionRequest calldata expansionRequest)
external
payable
onlyRole(Roles.EXPANSION_ROLE)
whenNotPaused
nonReentrant
onlyMortgageOwner(expansionRequest.tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
expansionRequest | ExpansionRequest | The parameters of the balance sheet expansion being requested |
burnMortgageNFT
Burns a mortgage NFT
function burnMortgageNFT(uint256 tokenId) external onlyRole(Roles.NFT_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage NFT to burn |
originate
Originates a mortgage position. Only callable by the OrderPool.
function originate(OriginationParameters calldata originationParameters)
external
payable
onlyOrderPool
whenNotPaused
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
originationParameters | OriginationParameters | The parameters for originating a mortgage creation or balance sheet expansion |
originationPoolDeployCallback
Called to msg.sender after transferring to the recipient from IOriginationPool#deploy.
amount = amountBorrowed
returnAmount = amountBorrowed + originationFee
function originationPoolDeployCallback(uint256, uint256 returnAmount, bytes calldata data)
external
onlyRegisteredOriginationPool;
Parameters
| Name | Type | Description |
|---|---|---|
<none> | uint256 | |
returnAmount | uint256 | The amount of consol to return to the origination pool |
data | bytes | Any data passed through by the caller via the IOriginationPool#deploy call |
_enqueueMortgage
Enqueues a mortgage position into a conversion queue
function _enqueueMortgage(uint256 tokenId, address[] memory conversionQueueList, uint256[] memory hintPrevIds)
internal;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage NFT |
conversionQueueList | address[] | The list of conversion queues |
hintPrevIds | uint256[] | The IDs of the previous mortgage position in the respective conversion queue |
enqueueMortgage
Enqueues a mortgage position into a conversion queue
function enqueueMortgage(uint256 tokenId, address[] memory conversionQueueList, uint256[] memory hintPrevIds)
external
payable
whenNotPaused
nonReentrant
onlyMortgageOwner(tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
conversionQueueList | address[] | The list of conversion queues to use |
hintPrevIds | uint256[] | The hint for the previous mortgage position in the conversion queue |
convert
Converts a mortgage position
function convert(uint256 tokenId, uint256 amount, uint256 collateralAmount, address receiver)
external
onlyRole(Roles.CONVERSION_ROLE)
whenNotPaused
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
amount | uint256 | The amount of the principal being coverted |
collateralAmount | uint256 | The amount of the collateral being withdrawn during the conversion |
receiver | address | The address receiving the converted collateral |
setPaused
Pause or unpause the contract
function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
pause | bool | The new paused state |
paused
Get the paused state of the contract
function paused() public view override returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | The paused state of the contract |
Structs
GeneralManagerStorage
Storage structure for GeneralManager contract
Uses ERC-7201 namespaced storage pattern
Note: storage-location: erc7201:buttonwood.storage.GeneralManager
struct GeneralManagerStorage {
address _usdx;
address _consol;
uint16 _penaltyRate;
uint16 _refinanceRate;
uint16 _conversionPremiumRate;
uint16 _priceSpread;
address _insuranceFund;
address _interestRateOracle;
address _originationPoolScheduler;
address _loanManager;
address _orderPool;
mapping(address => mapping(uint8 => bool)) _supportedMortgagePeriodTerms;
mapping(address => address) _priceOracles;
mapping(address => uint256) _minimumCaps;
mapping(address => uint256) _maximumCaps;
mapping(uint256 => address[]) _conversionQueues;
mapping(uint256 => mapping(address => bool)) _mortgageEnqueued;
bool _paused;
}
Properties
| Name | Type | Description |
|---|---|---|
_usdx | address | Address of the USDX token contract |
_consol | address | Address of the Consol token contract |
_penaltyRate | uint16 | Late payment penalty rate in basis points (BPS) |
_refinanceRate | uint16 | Refinancing fee rate in basis points (BPS) |
_conversionPremiumRate | uint16 | Conversion premium rate in basis points (BPS) |
_priceSpread | uint16 | Price spread in basis points (BPS) |
_insuranceFund | address | Address of the insurance fund |
_interestRateOracle | address | Address of the interest rate oracle contract |
_originationPoolScheduler | address | Address of the origination pool scheduler contract |
_loanManager | address | Address of the loan manager contract |
_orderPool | address | Address of the order pool contract |
_supportedMortgagePeriodTerms | mapping(address => mapping(uint8 => bool)) | Mapping of collateral address to period term to supported status |
_priceOracles | mapping(address => address) | Mapping of collateral address to price oracle address |
_minimumCaps | mapping(address => uint256) | Mapping of collateral address to minimum cap |
_maximumCaps | mapping(address => uint256) | Mapping of collateral address to maximum cap |
_conversionQueues | mapping(uint256 => address[]) | Mapping of collateral address to conversion queues |
_mortgageEnqueued | mapping(uint256 => mapping(address => bool)) | Mapping of tokenId to conversion queue to enqueued status |
_paused | bool | Whether the contract is paused |
LenderQueue
Inherits: Context, ERC165, AccessControl, ILenderQueue, ReentrancyGuard
Title: LenderQueue
Author: @SocksNFlops
Queue for withdrawing assets from the Consol contract.
State Variables
consol
Get the Consol contract.
address public immutable override consol
asset
Get the asset of the LenderQueue.
address public immutable override asset
withdrawalGasFee
Get the gas fee for a withdrawal.
uint256 public override withdrawalGasFee
withdrawalQueueHead
Get the head of the withdrawal queue. The index of the request at the front of the queue.
uint256 public override withdrawalQueueHead
withdrawalRequests
The withdrawal queue (in mapping form)
mapping(uint256 => WithdrawalRequest) internal withdrawalRequests
withdrawalQueueLength
Get the length of the withdrawal queue (number of requests in withdrawalRequests that have not been processed yet)
uint256 public override withdrawalQueueLength
minimumWithdrawalAmount
Get the minimum amount of tokens that can be withdrawn.
uint256 public override minimumWithdrawalAmount
paused
Get the paused state of the contract
bool public paused
Functions
whenNotPaused
Modifier to check if the contract is paused
modifier whenNotPaused() ;
constructor
Constructor
constructor(address asset_, address consol_, address admin_) ;
Parameters
| Name | Type | Description |
|---|---|---|
asset_ | address | The address of the asset to withdraw |
consol_ | address | The address of the Consol contract |
admin_ | address | The address of the admin |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC165) returns (bool);
setWithdrawalGasFee
Set the gas fee for a withdrawal.
function setWithdrawalGasFee(uint256 gasFee) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
gasFee | uint256 | The gas fee for a withdrawal |
withdrawNativeGas
Withdraws accumulated native gas fees. Only callable by the admin.
function withdrawNativeGas(uint256 amount) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE) nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of native gas fees to withdraw |
setMinimumWithdrawalAmount
Set the minimum amount of tokens that can be withdrawn.
function setMinimumWithdrawalAmount(uint256 newMinimumWithdrawalAmount)
external
override
onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newMinimumWithdrawalAmount | uint256 | The new minimum amount of tokens that can be withdrawn |
requestWithdrawal
Request a withdrawal of tokens from the LenderQueue contract.
function requestWithdrawal(uint256 amount) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of tokens to withdraw |
withdrawalQueue
Get the withdrawal request at a given index. The index is absolute, not relative to the withdrawal queue head.
function withdrawalQueue(uint256 index) external view override returns (WithdrawalRequest memory);
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the withdrawal request |
Returns
| Name | Type | Description |
|---|---|---|
<none> | WithdrawalRequest | withdrawalRequest The withdrawal request at the given index |
processWithdrawalRequests
Process the requests from the front of the USDX withdrawal queue. Callable by anyone by contracts with the PROCESSOR_ROLE.
function processWithdrawalRequests(uint256 iterations, address receiver) external virtual override;
Parameters
| Name | Type | Description |
|---|---|---|
iterations | uint256 | The number of iterations to process. Each iteration returns collected gas fees. |
receiver | address | The address to receive the gas fees |
cancelWithdrawal
Cancel a withdrawal request. Only callable by owner of the request. Does not refund the gas fee.
function cancelWithdrawal(uint256 index) external override;
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the withdrawal request to cancel |
setPaused
Pause or unpause the contract
function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
pause | bool | The new paused state |
LoanManager
Inherits: ILoanManager, ERC165, Context
Title: The LoanManager contract
Author: SocksNFlops
The LoanManager implementation contract
In order to minimize smart contract risk, we are hedging towards immutability.
State Variables
consol
Returns the Consol token address
address public immutable override consol
generalManager
Returns the general manager address
address public immutable override generalManager
nft
Returns the mortgage NFT address
address public immutable override nft
mortgagePositions
The mapping of tokenIds to mortgage positions
mapping(uint256 => MortgagePosition) private mortgagePositions
Functions
constructor
Constructor
constructor(
string memory nftName,
string memory nftSymbol,
address _nftMetadataGenerator,
address _consol,
address _generalManager
) ;
Parameters
| Name | Type | Description |
|---|---|---|
nftName | string | The name of the NFT |
nftSymbol | string | The symbol of the NFT |
_nftMetadataGenerator | address | The address of the NFT metadata generator |
_consol | address | The address of the Consol contract |
_generalManager | address | The address of the GeneralManager contract |
_applyPendingMissedPayments
Calculates the number of missed payments and penalty amount for a mortgage position and updates them in memory (not storage)
function _applyPendingMissedPayments(MortgagePosition memory mortgagePosition)
internal
view
returns (MortgagePosition memory outputMortgagePosition, uint256 penaltyAmount, uint8 additionalPaymentsMissed);
Parameters
| Name | Type | Description |
|---|---|---|
mortgagePosition | MortgagePosition | The mortgage position to calculate the missed payments and penalty amount for |
Returns
| Name | Type | Description |
|---|---|---|
outputMortgagePosition | MortgagePosition | The updated mortgage position |
penaltyAmount | uint256 | The penalty amount |
additionalPaymentsMissed | uint8 | The number of missed payments |
_imposePenalty
Applies pending missed payments to a mortgage position and emits a penalty imposed event if a penalty was imposed
function _imposePenalty(uint256 tokenId) internal;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
imposePenaltyBefore
Modifier to apply penalties to a mortgage position before it is fetched and used or returned
modifier imposePenaltyBefore(uint256 tokenId) ;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
onlyGeneralManager
Modifier to check if the caller is the general manager
modifier onlyGeneralManager() ;
_validateMortgageOwner
Validates that the caller is the owner of the mortgage
function _validateMortgageOwner(uint256 tokenId) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
onlyMortgageOwner
Modifier to check if the caller is the owner of the mortgage
modifier onlyMortgageOwner(uint256 tokenId) ;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
_validateMortgageExistsAndActive
Validates that the mortgage position exists and is active
function _validateMortgageExistsAndActive(uint256 tokenId) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
mortgageExistsAndActive
Modifier to check if the mortgage position exists and is active
modifier mortgageExistsAndActive(uint256 tokenId) ;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position |
_withdrawSubConsol
Withdraws the SubConsol from the Consol contract
function _withdrawSubConsol(address subConsol, uint256 amount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
subConsol | address | The address of the subConsol contract |
amount | uint256 | The amount of SubConsol to withdraw |
_subConsolWithdrawCollateral
Withdraws the collateral from the subConsol
function _subConsolWithdrawCollateral(
address subConsol,
address receiver,
uint256 collateralAmount,
uint256 amount,
bool async
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
subConsol | address | The address of the subConsol contract |
receiver | address | The address of the receiver |
collateralAmount | uint256 | The amount of collateral to withdraw |
amount | uint256 | The amount of SubConsol to burn |
async | bool | Whether to withdraw the collateral asynchronously |
_consolTransferFrom
Transfers Consol from one address to another
function _consolTransferFrom(address from, address to, uint256 amount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | The address of the sender |
to | address | The address of the recipient |
amount | uint256 | The amount of Consol to transfer |
_depositCollateralToConsolForGeneralManager
Deposits the collateral -> subConsol -> Consol into the general manager
function _depositCollateralToConsolForGeneralManager(
address collateral,
address subConsol,
uint256 collateralAmount,
uint256 amount
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral |
subConsol | address | The address of the subConsol |
collateralAmount | uint256 | The amount of collateral to deposit |
amount | uint256 | The amount of subConsol to deposit |
_forfeitConsol
Forfeits the Consol in the LoanManager contract
function _forfeitConsol() internal;
_validateMinimumAmountBorrowed
Validates that the amount borrowed is above a minimum threshold
function _validateMinimumAmountBorrowed(uint256 amountBorrowed) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amountBorrowed | uint256 | The amount borrowed |
supportsInterface
function supportsInterface(bytes4 interfaceId) public view override returns (bool);
createMortgage
Creates a new mortgage position
function createMortgage(MortgageParams memory mortgageParams) external override onlyGeneralManager;
Parameters
| Name | Type | Description |
|---|---|---|
mortgageParams | MortgageParams | The parameters for the mortgage position |
getMortgagePosition
Returns the mortgage position for a given tokenId
function getMortgagePosition(uint256 tokenId)
external
view
override
returns (MortgagePosition memory outputMortgagePosition);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
Returns
| Name | Type | Description |
|---|---|---|
outputMortgagePosition | MortgagePosition | The mortgage position |
imposePenalty
Imposes applicable penalties to a mortgage position
function imposePenalty(uint256 tokenId)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
periodPay
Pays the monthly payment for a mortgage position
function periodPay(uint256 tokenId, uint256 amount)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
amount | uint256 | The amount to pay |
penaltyPay
Pays the penalty for a mortgage position
function penaltyPay(uint256 tokenId, uint256 amount)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
amount | uint256 | The amount to pay |
redeemMortgage
Redeems a mortgage position
function redeemMortgage(uint256 tokenId, bool async)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId)
onlyMortgageOwner(tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
async | bool | Whether to allow redemption to be asynchronous |
refinanceMortgage
Refinances a mortgage position
function refinanceMortgage(uint256 tokenId, uint8 totalPeriods)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId)
onlyMortgageOwner(tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
totalPeriods | uint8 | The total number of periods that the mortgage is being refinanced to. |
forecloseMortgage
Forecloses a mortgage position
function forecloseMortgage(uint256 tokenId)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
flashSwapCallback
Called to msg.sender after transferring to the recipient from IConsol#flashSwap.
Used to facilitate foreclosures
function flashSwapCallback(address inputToken, address outputToken, uint256 amount, bytes calldata data) external;
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token |
outputToken | address | The address of the output token |
amount | uint256 | The amount of tokens to swap |
data | bytes | The data to pass into the callback |
convertMortgage
Converts a mortgage position
function convertMortgage(
uint256 tokenId,
uint256 currentPrice,
uint256 amount,
uint256 collateralAmount,
address receiver
) external override mortgageExistsAndActive(tokenId) imposePenaltyBefore(tokenId) onlyGeneralManager;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
currentPrice | uint256 | The current price of the collateral |
amount | uint256 | The amount of the principal being coverted |
collateralAmount | uint256 | The amount of the collateral being withdrawn during the conversion |
receiver | address | The address receiving the converted assets |
expandBalanceSheet
Expands the balance sheet of a mortgage position by adding addtional principal and collateral to the mortgage position
function expandBalanceSheet(uint256 tokenId, uint256 amountIn, uint256 collateralAmountIn, uint16 newInterestRate)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId)
onlyGeneralManager;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the mortgage position |
amountIn | uint256 | The amount of the principal being added to the mortgage position |
collateralAmountIn | uint256 | The amount of collateral being added to the mortgage position |
newInterestRate | uint16 | The new interest rate of the mortgage position |
MortgageNFT
Inherits: IMortgageNFT, ERC721
Title: The MortgageNFT contract
Author: SocksNFlops
The MortgageNFT contract is a non-fungible token that represents ownership of a mortgage position in LoanManager
State Variables
generalManager
Returns the general manager address
address public immutable override generalManager
nftMetadataGenerator
Returns the NFT metadata generator address
address public immutable override nftMetadataGenerator
getMortgageId
mapping(uint256 => string) public override getMortgageId
getTokenId
mapping(string => uint256) public override getTokenId
lastTokenIdCreated
Returns the last tokenId created
uint256 public override lastTokenIdCreated
Functions
constructor
Constructor
constructor(string memory name, string memory symbol, address generalManager_, address nftMetadataGenerator_)
ERC721(name, symbol);
Parameters
| Name | Type | Description |
|---|---|---|
name | string | The name of the NFT |
symbol | string | The symbol of the NFT |
generalManager_ | address | The address of the general manager |
nftMetadataGenerator_ | address | The address of the NFT metadata generator |
mortgageIdNotTaken
Modifier to check if the mortgage ID is already taken
modifier mortgageIdNotTaken(string memory mortgageId) ;
Parameters
| Name | Type | Description |
|---|---|---|
mortgageId | string | The mortgage ID to check |
onlyGeneralManager
Modifier to check if the caller is the general manager
modifier onlyGeneralManager() ;
mint
Mints a new mortgage NFT. Only the general manager can mint new NFTs.
function mint(address to, string memory mortgageId)
external
mortgageIdNotTaken(mortgageId)
onlyGeneralManager
returns (uint256 tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | The address to mint the NFT to |
mortgageId | string | The ID of the mortgage |
Returns
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the minted NFT |
burn
Burns a mortgage NFT. Only the general manager can burn NFTs.
function burn(uint256 tokenId) external onlyGeneralManager;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The ID of the mortgage position to burn |
ownerOf
Gets the owner of a mortgage position by its mortgage ID
function ownerOf(string memory mortgageId) external view returns (address owner);
Parameters
| Name | Type | Description |
|---|---|---|
mortgageId | string | The ID of the mortgage |
Returns
| Name | Type | Description |
|---|---|---|
owner | address | The owner of the mortgage position |
tokenURI
function tokenURI(uint256 tokenId) public view override returns (string memory);
MortgageQueue
Inherits: Context, ERC165, AccessControl, IMortgageQueue
Title: MortgageQueue
Author: SocksNFlops
The MortgageQueue contract is responsible for managing the queue of mortgage positions by sorting them by a specified trigger price
State Variables
mortgageHead
Storage Variables
uint256 public override mortgageHead
mortgageTail
The tokenId of the MortgagePosition at the tail of the queue.
uint256 public override mortgageTail
mortgageSize
The number of nodes in the queue.
uint256 public override mortgageSize
mortgageGasFee
The gas fee for enqueueing a mortgage into the queue.
uint256 public override mortgageGasFee
_mortgageNodes
The mapping of tokenIds to mortgage nodes
mapping(uint256 tokenId => MortgageNode) internal _mortgageNodes
Functions
constructor
Constructor
constructor() ;
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC165) returns (bool);
mortgageNodes
The node for the corresponding tokenId (if it exists).
function mortgageNodes(uint256 tokenId) external view override returns (MortgageNode memory mortgageNode);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the MortgagePosition to get the node for. |
Returns
| Name | Type | Description |
|---|---|---|
mortgageNode | MortgageNode | The node for the corresponding tokenId. |
setMortgageGasFee
Sets the gas fee for enqueueing a mortgage into the queue.
function setMortgageGasFee(uint256 mortgageGasFee_) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
mortgageGasFee_ | uint256 | The gas fee for enqueueing a mortgage into the queue. |
_insertMortgage
Inserts a mortgage position into the queue
function _insertMortgage(uint256 tokenId, uint256 triggerPrice, uint256 hintPrevId) internal;
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the MortgagePosition to insert. |
triggerPrice | uint256 | The trigger price of the MortgagePosition to insert. |
hintPrevId | uint256 | The tokenId of the "hint" previous node that is close and before the new node. If 0 is provided, it will start from the head. |
_removeMortgage
Removes a mortgage position from the queue
function _removeMortgage(uint256 tokenId) internal returns (uint256 gasFee);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the MortgagePosition to remove. |
Returns
| Name | Type | Description |
|---|---|---|
gasFee | uint256 | The gas fee collected from the removed mortgageNode |
_popMortgage
Pops the current node from the queue and returns the next node
function _popMortgage(uint256 tokenId) internal returns (uint256 nextId, uint256 gasFee);
Parameters
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the node to pop. |
Returns
| Name | Type | Description |
|---|---|---|
nextId | uint256 | The tokenId of the next node in the queue. |
gasFee | uint256 | The gas fee collected from the removed mortgageNode |
_findFirstTriggered
Finds the first mortgage position in the queue that has a trigger price less than or equal to the input trigger price
function _findFirstTriggered(uint256 triggerPrice) internal view returns (uint256 tokenId);
Parameters
| Name | Type | Description |
|---|---|---|
triggerPrice | uint256 | The trigger price to find the first MortgagePosition for. |
Returns
| Name | Type | Description |
|---|---|---|
tokenId | uint256 | The tokenId of the first MortgagePosition in the Conversion Queue that has a trigger price less than or equal to the input trigger price. |
MultiTokenVault
Inherits: Context, ERC165, AccessControl, RebasingERC20, IMultiTokenVault
Title: MultiTokenVault
Author: SocksNFlops
MultiTokenVault is a contract that allows users to deposit multiple tokens and mint a single token in return. Assumes all supported tokens have the same UOA.
State Variables
supportedTokens
The set of supported tokens
EnumerableSet.AddressSet internal supportedTokens
maximumCap
mapping(address => uint256) public maximumCap
Functions
constructor
Constructor
constructor(string memory name_, string memory symbol_, uint8 decimalsOffset_, address admin_)
RebasingERC20(name_, symbol_, decimalsOffset_);
Parameters
| Name | Type | Description |
|---|---|---|
name_ | string | The name of the MultiTokenVault |
symbol_ | string | The symbol of the MultiTokenVault |
decimalsOffset_ | uint8 | The decimals offset |
admin_ | address | The admin address |
enforceCaps
Enforces the maximum cap for a token
modifier enforceCaps(address token) ;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The token to enforce the cap for |
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC165) returns (bool);
addSupportedToken
Add a supported token to the MultiTokenVault
function addSupportedToken(address token) public virtual override onlyRole(Roles.SUPPORTED_TOKEN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to add |
removeSupportedToken
Remove a supported token from the MultiTokenVault
function removeSupportedToken(address token) public virtual override onlyRole(Roles.SUPPORTED_TOKEN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to remove |
getSupportedTokens
Get the list of supported tokens
function getSupportedTokens() external view override returns (address[] memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | The list of supported tokens |
isTokenSupported
Check if a token is supported
function isTokenSupported(address token) public view override returns (bool isSupported);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to check |
Returns
| Name | Type | Description |
|---|---|---|
isSupported | bool | True if the token is supported, false otherwise |
setMaximumCap
Set the absolute maximum cap for an underlying token.
function setMaximumCap(address token, uint256 _maximumCap) external override onlyRole(Roles.SUPPORTED_TOKEN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to set the cap for |
_maximumCap | uint256 | The new maximum cap for the token denominated in the UOA. Default is type(uint256).max. |
convertAmount
Calculates the amount of tokens minted/burned in a deposit/withdraw operation
function convertAmount(address, uint256 amount) public view virtual override returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | address | |
amount | uint256 | The amount of tokens to deposit/withdraw |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The mint/burn amount |
convertUnderlying
Calculates the amount of underlying tokens required to deposit/withdraw a given amount of tokens
function convertUnderlying(address, uint256 amount) public view virtual override returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | address | |
amount | uint256 | The amount of tokens minted/burned as a result of the deposit/withdraw operation |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The amount of underlying tokens required to deposit/withdraw the given amount of tokens |
deposit
Deposit tokens into the MultiTokenVault and mint an equivalent amount of the MultiTokenVault token.
function deposit(address token, uint256 amount) public virtual override enforceCaps(token);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to deposit |
amount | uint256 | The amount of tokens to deposit |
withdraw
Withdraw tokens from the MultiTokenVault and burn an equivalent amount of the MultiTokenVault token.
function withdraw(address token, uint256 amount) public virtual override;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to withdraw |
amount | uint256 | The amount of tokens to withdraw |
forfeit
Forfeit tokens from the MultiTokenVault. Redistributes the forfeited tokens to the existing holders.
function forfeit(uint256 amount) public virtual override;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of tokens to forfeit |
burnExcessShares
Given shares and an amount, this will burn shares until the amount is reached.
This is achieved by burning all of the shares and minting the amount. Will no-op if attempting to mint more than the shares correspond to.
function burnExcessShares(uint256 shares, uint256 amount) public virtual override;
Parameters
| Name | Type | Description |
|---|---|---|
shares | uint256 | The amount of shares to burn |
amount | uint256 | The amount of tokens to mint |
_totalSupply
Calculates the total supply of the MultiTokenVault by summing up the balances of all supported tokens
function _totalSupply() internal view virtual override returns (uint256 totalSupply);
Returns
| Name | Type | Description |
|---|---|---|
totalSupply | uint256 | The total supply of the MultiTokenVault |
OrderPool
Inherits: Context, ERC165, AccessControl, IOrderPool, ReentrancyGuard
Title: PurchasePool
Author: SocksNFlops
PurchasePool is a contract that stores a collection of PurchaseOrders for fulfilling collateral purchases for mortgages.
State Variables
nativeWrapper
Get the native token wrapper contract (whype/weth/etc).
address public immutable override nativeWrapper
generalManager
Returns the affiliated general manager address that is allowed to submit purchase orders.
address public immutable override generalManager
usdx
Returns the USDX token address
address public immutable override usdx
consol
Returns the Consol token address
address public immutable override consol
gasFee
Returns the gas fee for adding a PurchaseOrder to the OrderPool
uint256 public override gasFee
maximumOrderDuration
Returns the maximum duration for a PurchaseOrder
uint256 public override maximumOrderDuration
_orders
Internal mapping of purchase orders
mapping(uint256 => PurchaseOrder) private _orders
orderCount
Returns the total number of PurchaseOrder (current and past) placed in the order pool. Used to index the orders mapping.
uint256 public override orderCount
Functions
onlyGeneralManager
Modifier to check if the caller is the general manager
modifier onlyGeneralManager() ;
constructor
Constructor for the OrderPool
constructor(address nativeWrapper_, address generalManager_, address admin_) ;
Parameters
| Name | Type | Description |
|---|---|---|
nativeWrapper_ | address | The address of the native wrapper contract |
generalManager_ | address | The address of the GeneralManager |
admin_ | address | The address of the admin |
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC165) returns (bool);
setGasFee
Sets the gas fee for adding a PurchaseOrder to the OrderPool. Only callable by the admin role.
function setGasFee(uint256 gasFee_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
gasFee_ | uint256 | The new value of the gas fee |
setMaximumOrderDuration
Sets the maximum duration for a PurchaseOrder. Only callable by the admin role.
function setMaximumOrderDuration(uint256 maximumOrderDuration_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
maximumOrderDuration_ | uint256 | The new value of the maximum duration |
orders
Returns the purchase order at the given index
function orders(uint256 index) external view returns (PurchaseOrder memory);
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the purchase order |
Returns
| Name | Type | Description |
|---|---|---|
<none> | PurchaseOrder | The purchase order |
_calculateMortgageGasFee
Calculates the mortgage gas fee for a list of conversion queues
function _calculateMortgageGasFee(address[] memory conversionQueues) internal view returns (uint256 mortgageGasFee);
Parameters
| Name | Type | Description |
|---|---|---|
conversionQueues | address[] | The list of conversion queues to calculate the mortgage gas fee for |
Returns
| Name | Type | Description |
|---|---|---|
mortgageGasFee | uint256 | The total mortgage gas fee |
sendOrder
Adds a PurchaseOrder to the OrderPool. Only callable by the general manager.
function sendOrder(
address[] memory originationPools,
uint256[] memory borrowAmounts,
address[] memory conversionQueues,
OrderAmounts memory orderAmounts,
MortgageParams memory mortgageParams,
uint256 expiration,
bool expansion
) external payable onlyGeneralManager nonReentrant returns (uint256 index);
Parameters
| Name | Type | Description |
|---|---|---|
originationPools | address[] | The addresses of the origination pools to deploy funds from |
borrowAmounts | uint256[] | The amounts being borrowed from each origination pool |
conversionQueues | address[] | The addresses of the conversion queues to use |
orderAmounts | OrderAmounts | The amounts being collected from the borrower |
mortgageParams | MortgageParams | The parameters for the mortgage being created |
expiration | uint256 | The expiration timestamp of the order |
expansion | bool | Whether the mortgage is a balance sheet expansion of an existing position |
Returns
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the PurchaseOrder |
_sendCollectedAssets
Helper function for sending collected assets to the general manager or refunding to the borrower
function _sendCollectedAssets(address receiver, PurchaseOrder memory order) internal;
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address | The address to send the assets to |
order | PurchaseOrder | The order being processed |
_processOrder
Processes an order at a given internal index
function _processOrder(uint256 index, uint256[] memory hintPrevIds) internal returns (uint256 collectedGasFee);
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the order |
hintPrevIds | uint256[] | List of hints for identifying the previous mortgage position in the respective conversion queue. |
Returns
| Name | Type | Description |
|---|---|---|
collectedGasFee | uint256 | The amount of gas fee collected |
processOrders
Processes the purchase orders at the given indices by fulfilling them or removing expired orders. Only callable by the FULFILLMENT_ROLE.
function processOrders(uint256[] memory indices, uint256[][] memory hintPrevIdsList)
external
onlyRole(Roles.FULFILLMENT_ROLE)
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
indices | uint256[] | The indices of the purchase orders to process |
hintPrevIdsList | uint256[][] | The list of hintPrevIds for each purchase order. Each hintPrevIds is a list of hint of the previous mortgage position in the respective conversion queue. |
OriginationPool
Inherits: IOriginationPool, ERC165, AccessControl, ERC20, ReentrancyGuard
Title: The OriginationPool contract
Author: SocksNFlops
The OriginationPool allows lending USDX to be used for origination of mortgage positions, earning yield in the form of Consol.
In order to minimize smart contract risk, we are hedging towards immutability.
State Variables
consol
The Consol token address
address public immutable consol
usdx
The USDX token address
address public immutable usdx
depositPhaseTimestamp
The deposit phase timestamp
uint256 public immutable depositPhaseTimestamp
deployPhaseTimestamp
The deploy phase timestamp
uint256 public immutable deployPhaseTimestamp
redemptionPhaseTimestamp
The redemption phase timestamp
uint256 public immutable redemptionPhaseTimestamp
poolLimit
Fetches the pool deposit limit
uint256 public immutable poolLimit
poolMultiplierBps
Fetches the pool multiplier in basis points
uint16 public immutable poolMultiplierBps
amountDeployed
Fetches the amount of USD tokens deployed from the pool
uint256 public amountDeployed
paused
Get the paused state of the contract
bool public paused
Functions
constructor
Constructor
constructor(
string memory namePrefix,
string memory symbolPrefix,
uint256 epoch,
address consol_,
address usdx_,
uint256 deployPhaseTimestamp_,
uint256 redemptionPhaseTimestamp_,
uint256 poolLimit_,
uint16 poolMultiplierBps_
) ERC20(string.concat(namePrefix, " - ", epoch.toString()), string.concat(symbolPrefix, "-", epoch.toString()));
Parameters
| Name | Type | Description |
|---|---|---|
namePrefix | string | The prefix for the name of the pool |
symbolPrefix | string | The prefix for the symbol of the pool |
epoch | uint256 | The epoch of the pool |
consol_ | address | The address of the consol contract |
usdx_ | address | The address of the USDX token |
deployPhaseTimestamp_ | uint256 | The timestamp of the deploy phase |
redemptionPhaseTimestamp_ | uint256 | The timestamp of the redemption phase |
poolLimit_ | uint256 | The pool limit |
poolMultiplierBps_ | uint16 | The pool multiplier in basis points |
whenNotPaused
Modifier to check if the contract is paused
modifier whenNotPaused() ;
onlyPhase
Modifier to check if the current phase is the given phase
modifier onlyPhase(OriginationPoolPhase phase) ;
Parameters
| Name | Type | Description |
|---|---|---|
phase | OriginationPoolPhase | The phase to check |
supportsInterface
function supportsInterface(bytes4 interfaceId) public view override(AccessControl, ERC165) returns (bool);
setPaused
Pause or unpause the contract
function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
pause | bool | The new paused state |
currentPhase
Fetches the current phase of the Origination Pool
function currentPhase() public view override returns (OriginationPoolPhase);
Returns
| Name | Type | Description |
|---|---|---|
<none> | OriginationPoolPhase | The current phase |
calculateReturnAmount
Calculates the return amount of Consol for a given amount of USDX by applying the pool multiplier
function calculateReturnAmount(uint256 amount) public view override returns (uint256 returnAmount);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of USDX to calculate the return amount for |
Returns
| Name | Type | Description |
|---|---|---|
returnAmount | uint256 | The return amount of Consol |
deposit
Deposit USDX into the pool
function deposit(uint256 amount)
external
override
whenNotPaused
onlyPhase(OriginationPoolPhase.DEPOSIT)
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of USDX to deposit |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | mintAmount The amount of receipt tokens minted to the user |
deploy
Deploy USDX in the pool and convert it to Consol. Only callable by contracts implementing IOriginationPoolDeployCallback
function deploy(uint256 amount, bytes calldata data)
external
override
whenNotPaused
onlyPhase(OriginationPoolPhase.DEPLOY)
onlyRole(Roles.DEPLOY_ROLE)
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of USDX to deploy |
data | bytes | The calldata to pass into the callback |
redeem
Redeem USDX + Consol from the pool from receipt tokens
function redeem(uint256 amount) external override onlyPhase(OriginationPoolPhase.REDEMPTION);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of receipt tokens to burn in exchange for USDX + Consol |
OriginationPoolScheduler
Inherits: Initializable, ERC165Upgradeable, AccessControlUpgradeable, UUPSUpgradeable, IOriginationPoolScheduler
Title: OriginationPoolScheduler
Author: SocksNFlops
The OriginationPoolScheduler contract manages the creation and configuration of origination pools
State Variables
OriginationPoolSchedulerStorageLocation
The storage location of the OriginationPoolScheduler contract
keccak256(abi.encode(uint256(keccak256("buttonwood.storage.OriginationPoolScheduler")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OriginationPoolSchedulerStorageLocation =
0x51ba61e21d0a5bc73e422280ccd2621682937c38ec72703c8f08348fe6a50f00
Functions
_getOriginationPoolSchedulerStorage
Gets the storage location of the OriginationPoolScheduler contract
function _getOriginationPoolSchedulerStorage() private pure returns (OriginationPoolSchedulerStorage storage $);
Returns
| Name | Type | Description |
|---|---|---|
$ | OriginationPoolSchedulerStorage | The storage location of the OriginationPoolScheduler contract |
__OriginationPoolScheduler_init
Initializes the OriginationPoolScheduler contract and calls parent initializers
function __OriginationPoolScheduler_init(address generalManager_, address oPoolAdmin_) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
generalManager_ | address | The address of the general manager |
oPoolAdmin_ | address | The address of the oPool admin |
__OriginationPoolScheduler_init_unchained
Initializes the OriginationPoolScheduler contract only
function __OriginationPoolScheduler_init_unchained(address generalManager_, address oPoolAdmin_)
internal
onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
generalManager_ | address | The address of the general manager |
oPoolAdmin_ | address | The address of the oPool admin |
initialize
Initializes the OriginationPoolScheduler contract
function initialize(address generalManager_, address oPoolAdmin_) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
generalManager_ | address | The address of the general manager |
oPoolAdmin_ | address | The address of the oPool admin |
constructor
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
whenNotPaused
Modifier to check if the contract is paused
modifier whenNotPaused() ;
_authorizeUpgrade
Authorizes the upgrade of the contract. Only the admin can authorize the upgrade
function _authorizeUpgrade(address newImplementation) internal virtual override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | The address of the new implementation |
_getRawEpoch
Gets the raw internal epoch needed for calculating timestamps
function _getRawEpoch() internal view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The raw epoch |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId)
public
view
override(AccessControlUpgradeable, ERC165Upgradeable)
returns (bool);
setGeneralManager
Set the general manager address
function setGeneralManager(address newGeneralManager) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newGeneralManager | address | The address of the new general manager |
generalManager
Get the general manager address
function generalManager() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the general manager |
setOpoolAdmin
Set the admin address that is assigned to the origination pools on deployment
function setOpoolAdmin(address newOpoolAdmin) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newOpoolAdmin | address | The address of the new origination pool admin |
oPoolAdmin
Get the admin address that is assigned to the origination pools on deployment
function oPoolAdmin() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the origination pool admin |
configLength
Get the number of origination pool configs
function configLength() public view override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The number of origination pool configs |
configIdAt
Get the origination pool config ID at the given index
function configIdAt(uint256 index) public view override returns (OPoolConfigId oPoolConfigId);
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the origination pool config to get the ID for |
Returns
| Name | Type | Description |
|---|---|---|
oPoolConfigId | OPoolConfigId | The ID of the origination pool config |
configAt
Get the origination pool config at the given index
function configAt(uint256 index) public view override returns (OriginationPoolConfig memory);
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the origination pool config to get |
Returns
| Name | Type | Description |
|---|---|---|
<none> | OriginationPoolConfig | config The origination pool config |
lastConfigDeployment
Get the last deployment address from the given config index
function lastConfigDeployment(uint256 index)
public
view
override
returns (LastDeploymentRecord memory lastDeploymentRecord);
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the origination pool config to get the last deployment address from |
Returns
| Name | Type | Description |
|---|---|---|
lastDeploymentRecord | LastDeploymentRecord | The last deployment record |
lastConfigDeployment
Get the last deployment address from the given config ID
function lastConfigDeployment(OPoolConfigId oPoolConfigId)
public
view
override
returns (LastDeploymentRecord memory lastDeploymentRecord);
Parameters
| Name | Type | Description |
|---|---|---|
oPoolConfigId | OPoolConfigId | The ID of the origination pool config to get the last deployment address from |
Returns
| Name | Type | Description |
|---|---|---|
lastDeploymentRecord | LastDeploymentRecord | The last deployment record |
addConfig
Add a new origination pool config
function addConfig(OriginationPoolConfig memory config) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
config | OriginationPoolConfig | The origination pool config to add |
removeConfig
Remove an origination pool config
function removeConfig(OriginationPoolConfig memory config) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
config | OriginationPoolConfig | The origination pool config to remove |
currentEpoch
Get the current epoch. Indexed from 1
function currentEpoch() public view override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | currentEpoch The current epoch |
_updateRegistration
Updates the registration of an origination pool
function _updateRegistration(address originationPool, bool registered) internal;
Parameters
| Name | Type | Description |
|---|---|---|
originationPool | address | The address of the origination pool |
registered | bool | Whether the origination pool is registered |
_getOriginationPoolBytecode
Generates the bytecode for an origination pool
function _getOriginationPoolBytecode(
OriginationPoolConfig memory config,
LastDeploymentRecord memory lastDeploymentRecord,
uint256 currEpoch
) internal view returns (bytes memory bytecode);
Parameters
| Name | Type | Description |
|---|---|---|
config | OriginationPoolConfig | The config for the origination pool |
lastDeploymentRecord | LastDeploymentRecord | The last deployment record for the origination pool |
currEpoch | uint256 | The current epoch |
Returns
| Name | Type | Description |
|---|---|---|
bytecode | bytes | The bytecode for the origination pool |
_deployOriginationPool
Deploys an origination pool
function _deployOriginationPool(
OriginationPoolConfig memory config,
LastDeploymentRecord memory lastDeploymentRecord,
address _generalManager,
address _oPoolAdmin,
uint256 currEpoch
) internal returns (address originationPool);
Parameters
| Name | Type | Description |
|---|---|---|
config | OriginationPoolConfig | The config for the origination pool |
lastDeploymentRecord | LastDeploymentRecord | The last deployment record for the origination pool |
_generalManager | address | The address of the general manager |
_oPoolAdmin | address | The address of the oPool admin |
currEpoch | uint256 | The current epoch |
Returns
| Name | Type | Description |
|---|---|---|
originationPool | address | The address of the deployed origination pool |
_calculatePoolLimit
Calculates the pool limit for an origination pool
function _calculatePoolLimit(
LastDeploymentRecord memory lastDeploymentRecord,
uint256 defaultPoolLimit,
uint16 poolLimitGrowthRateBps,
uint256 currEpoch
) internal view returns (uint256 poolLimit);
Parameters
| Name | Type | Description |
|---|---|---|
lastDeploymentRecord | LastDeploymentRecord | The last deployment record for the origination pool |
defaultPoolLimit | uint256 | The default pool limit |
poolLimitGrowthRateBps | uint16 | The pool limit growth rate in basis points |
currEpoch | uint256 | The current epoch |
Returns
| Name | Type | Description |
|---|---|---|
poolLimit | uint256 | The pool limit |
deployOriginationPool
Deploy a new origination pool
function deployOriginationPool(OPoolConfigId oPoolConfigId)
external
whenNotPaused
returns (address deploymentAddress);
Parameters
| Name | Type | Description |
|---|---|---|
oPoolConfigId | OPoolConfigId | The ID of the origination pool config to deploy |
Returns
| Name | Type | Description |
|---|---|---|
deploymentAddress | address | The address of the deployed origination pool |
predictOriginationPool
Predict the origination pool address for the given config ID and current epoch. If already deployed, will return the already deployed address.
function predictOriginationPool(OPoolConfigId oPoolConfigId) external view returns (address deploymentAddress);
Parameters
| Name | Type | Description |
|---|---|---|
oPoolConfigId | OPoolConfigId | The ID of the origination pool config to predict the address for |
Returns
| Name | Type | Description |
|---|---|---|
deploymentAddress | address | The predicted deployment address |
isRegistered
Check if an origination pool is registered (deployed by the scheduler)
function isRegistered(address originationPool) external view override returns (bool registered);
Parameters
| Name | Type | Description |
|---|---|---|
originationPool | address | The address of the origination pool to check |
Returns
| Name | Type | Description |
|---|---|---|
registered | bool | Whether the origination pool is registered |
updateRegistration
Update the registration of an origination pool
function updateRegistration(address originationPool, bool registered)
external
override
onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
originationPool | address | The address of the origination pool to update the registration for |
registered | bool | Whether the origination pool is registered |
setPaused
Pause or unpause the contract
function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
pause | bool | The new paused state |
paused
Get the paused state of the contract
function paused() public view override returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | The paused state of the contract |
Structs
OriginationPoolSchedulerStorage
The storage for the OriginationPoolScheduler contract
Note: storage-location: erc7201:buttonwood.storage.OriginationPoolScheduler
struct OriginationPoolSchedulerStorage {
address _generalManager;
address _oPoolAdmin;
uint256 _epochCountStart;
OPoolConfigId[] _oPoolConfigIds;
mapping(OPoolConfigId => uint256) _oPoolConfigIndexes;
mapping(OPoolConfigId => OriginationPoolConfig) _oPoolConfigs;
mapping(OPoolConfigId => LastDeploymentRecord) _oPoolLastDeploymentRecords;
mapping(address => bool) _oPoolRegistry;
bool _paused;
}
Properties
| Name | Type | Description |
|---|---|---|
_generalManager | address | The address of the general manager |
_oPoolAdmin | address | The address of the oPool admin |
_epochCountStart | uint256 | The epoch count start (helps start that count from 0 for the current epoch) |
_oPoolConfigIds | OPoolConfigId[] | Array of supported oPool config ids |
_oPoolConfigIndexes | mapping(OPoolConfigId => uint256) | Mapping of ids to their index in the _oPoolConfigIds array |
_oPoolConfigs | mapping(OPoolConfigId => OriginationPoolConfig) | Mapping of ids to the oPool configs |
_oPoolLastDeploymentRecords | mapping(OPoolConfigId => LastDeploymentRecord) | Mapping of ids to the last deployed origination pool with that config |
_oPoolRegistry | mapping(address => bool) | Mapping of origination pool addresses to a boolean indicating if they are registered |
_paused | bool | Whether the contract is paused |
PythInterestRateOracle
Inherits: IInterestRateOracle
Title: PythInterestRateOracle
Author: SocksNFlops
The PythInterestRateOracle contract is a contract that tracks the interest rate of US treasuries to determine the interest rate for new Mortgages being originated.
State Variables
PERCENT_DECIMALS
The number of decimals for percentages
int8 public constant PERCENT_DECIMALS = 2
BPS_DECIMALS
The number of decimals for basis points
int8 public constant BPS_DECIMALS = 4
MAX_CONFIDENCE_BPS
The maximum confidence in basis points
uint32 public constant MAX_CONFIDENCE_BPS = 100
MAX_AGE
The maximum age of a price in seconds
uint32 public constant MAX_AGE = 60 seconds
THREE_YEAR_PYTH_PRICE_ID
The Pyth price ID for 3-year US treasuries
bytes32 public constant THREE_YEAR_PYTH_PRICE_ID = 0x25ac38864cd1802a9441e82d4b3e0a4eed9938a1849b8d2dcd788e631e3b288c
FIVE_YEAR_PYTH_PRICE_ID
The Pyth price ID for 5-year US treasuries
bytes32 public constant FIVE_YEAR_PYTH_PRICE_ID = 0x7d220b081152db0d74a93d3ce383c61d0ec5250c6dd2b2cdb2d1e4b8919e1a6e
PAYMENT_PLAN_SPREAD
The spread for mortgages with a payment plan
uint16 public constant PAYMENT_PLAN_SPREAD = 100
NO_PAYMENT_PLAN_SPREAD
The spread for mortgages without a payment plan
uint16 public constant NO_PAYMENT_PLAN_SPREAD = 200
pyth
The Pyth contract
IPyth public immutable pyth
Functions
constructor
Constructor
constructor(address pyth_) ;
Parameters
| Name | Type | Description |
|---|---|---|
pyth_ | address | The address of the Pyth contract |
interestRate
Returns the interest rate (in basis points) for a given total periods and amortization status
2x the 3-year treasury yield + 100 BPS spread (for mortgages with a payment plan)
2x the 3-year treasury yield + 200 BPS spread (for mortgages without a payment plan)
function interestRate(uint8 totalPeriods, bool hasPaymentPlan) external view override returns (uint16 rate);
Parameters
| Name | Type | Description |
|---|---|---|
totalPeriods | uint8 | The total number of periods for the mortgage |
hasPaymentPlan | bool | Whether the mortgage has a payment plan |
Returns
| Name | Type | Description |
|---|---|---|
rate | uint16 | The interest rate |
Errors
MaxAgeExceeded
The error thrown when the age of a price is greater than the maximum age
error MaxAgeExceeded(uint256 age, uint256 maxAge);
Parameters
| Name | Type | Description |
|---|---|---|
age | uint256 | The age of the price |
maxAge | uint256 | The maximum age |
MaxConfidenceExceeded
The error thrown when the confidence of a price is greater than the maximum confidence
error MaxConfidenceExceeded(uint256 confidence, uint256 maxConfidence);
Parameters
| Name | Type | Description |
|---|---|---|
confidence | uint256 | The confidence of the price |
maxConfidence | uint256 | The maximum confidence |
InvalidTotalPeriods
The error thrown when the total periods are invalid and not supported by the InterestRateOracle
error InvalidTotalPeriods(uint8 totalPeriods);
Parameters
| Name | Type | Description |
|---|---|---|
totalPeriods | uint8 | The total periods |
PythPriceOracle
Inherits: IPriceOracle
Title: PythPriceOracle
Author: SocksNFlops
The PythPriceOracle contract is a contract that tracks the price of a given asset to determine the trigger price for conversions.
State Variables
USD_DECIMALS
The number of decimals for USD
int8 public constant USD_DECIMALS = 18
MAX_AGE
The maximum age of a price in seconds
uint32 public constant MAX_AGE = 60 seconds
pyth
The Pyth contract
IPyth public immutable pyth
pythPriceId
The Pyth price ID
bytes32 public immutable pythPriceId
maxConfidence
The maximum confidence
uint256 public immutable maxConfidence
collateralDecimals
The number of decimals for the collateral
uint8 public immutable collateralDecimals
Functions
constructor
Constructor
constructor(address pyth_, bytes32 priceId_, uint256 maxConfidence_, uint8 collateralDecimals_) ;
Parameters
| Name | Type | Description |
|---|---|---|
pyth_ | address | The address of the Pyth contract |
priceId_ | bytes32 | The Pyth price ID |
maxConfidence_ | uint256 | The maximum confidence |
collateralDecimals_ | uint8 | The number of decimals for the collateral |
price
Returns the price of the collateral in USDX
function price() public view override returns (uint256 assetPrice);
Returns
| Name | Type | Description |
|---|---|---|
assetPrice | uint256 | The price of the collateral in USDX (18 decimals) |
cost
Returns the cost of the collateral in USDX
function cost(uint256 collateralAmount) public view override returns (uint256 totalCost, uint8 _collateralDecimals);
Parameters
| Name | Type | Description |
|---|---|---|
collateralAmount | uint256 | The amount of collateral to calculate the cost of |
Returns
| Name | Type | Description |
|---|---|---|
totalCost | uint256 | The cost of the collateral in USDX (18 decimals) |
_collateralDecimals | uint8 | The collateral decimals |
Errors
MaxAgeExceeded
The error thrown when the age of a price is greater than the maximum age
error MaxAgeExceeded(uint256 age, uint256 maxAge);
Parameters
| Name | Type | Description |
|---|---|---|
age | uint256 | The age of the price |
maxAge | uint256 | The maximum age |
MaxConfidenceExceeded
The error thrown when the confidence of a price is greater than the maximum confidence
error MaxConfidenceExceeded(uint256 confidence, uint256 maxConfidence);
Parameters
| Name | Type | Description |
|---|---|---|
confidence | uint256 | The confidence of the price |
maxConfidence | uint256 | The maximum confidence |
QueueProcessor
Inherits: IProcessor, Context
Title: QueueProcessor
Author: SocksNFlops
The QueueProcessor contract is a contract that processes withdrawal requests from LenderQueues, enforcing any ordering restrictions between the queues.
Functions
process
Processes the withdrawal requests from a source
function process(address queue, uint256 iterations) external override;
Parameters
| Name | Type | Description |
|---|---|---|
queue | address | |
iterations | uint256 | The number of iterations to process |
isBlocked
Checks if the source is blocked by another source
function isBlocked(address) external pure override returns (address blocker, bool blocked);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | address |
Returns
| Name | Type | Description |
|---|---|---|
blocker | address | Another source that is blocking the source |
blocked | bool | Whether the source is blocked by another source |
RebasingERC20
Inherits: Context, IRebasingERC20, IERC20Metadata, IERC20Errors, ERC20Permit
Title: RebasingERC20
Author: Socks&Flops
Implementation of the {IRebasingERC20} interface.
State Variables
sharesOf
mapping(address account => uint256 shares) public override sharesOf
totalShares
The total amount of the shares token
uint256 public override totalShares
decimalsOffset
The decimals offset. The number of decimals to offset the shares by. Used to protect against inflation attacks.
uint8 public immutable override decimalsOffset
Functions
constructor
Constructor
constructor(string memory name_, string memory symbol_, uint8 decimalsOffset_)
ERC20(name_, symbol_)
ERC20Permit(name_);
Parameters
| Name | Type | Description |
|---|---|---|
name_ | string | The name of the token |
symbol_ | string | The symbol of the token |
decimalsOffset_ | uint8 | The number of decimals to pad the internal shares with to avoid precision loss |
_totalSupply
Internal function to get the total supply of the token
function _totalSupply() internal view virtual returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total supply of the token |
totalSupply
Returns the value of tokens in existence.
function totalSupply() public view virtual override(ERC20, IERC20) returns (uint256);
convertToAssets
Converts the amount of shares to the corresponding amount of underlying token
function convertToAssets(uint256 shares) public view virtual returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
shares | uint256 | The amount of shares |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The corresponding amount of underlying token |
convertToShares
Converts the amount of underlying token to the corresponding amount of shares
function convertToShares(uint256 assets) public view virtual returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
assets | uint256 | The amount of underlying token |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The corresponding amount of shares |
balanceOf
Returns the value of tokens owned by account.
function balanceOf(address account) public view virtual override(ERC20, IERC20) returns (uint256);
_update
Modification of OZ:ERC20:_update. Manipulates shares instead of fixed balances
function _update(address from, address to, uint256 value) internal virtual override;
StaticInterestRateOracle
Inherits: IInterestRateOracle
Title: StaticInterestRateOracle
Author: SocksNFlops
The StaticInterestRateOracle contract is a contract that returns a static interest rate for new Mortgages being originated.
State Variables
BPS_DECIMALS
The number of decimals for basis points
int8 public constant BPS_DECIMALS = 4
PAYMENT_PLAN_SPREAD
The spread for mortgages with a payment plan
uint16 public constant PAYMENT_PLAN_SPREAD = 100
NO_PAYMENT_PLAN_SPREAD
The spread for mortgages without a payment plan
uint16 public constant NO_PAYMENT_PLAN_SPREAD = 200
baseRate
The base rate (excluding spread)
uint16 public immutable baseRate
Functions
constructor
Constructor
constructor(uint16 baseRate_) ;
Parameters
| Name | Type | Description |
|---|---|---|
baseRate_ | uint16 | The base rate (excluding spread) |
interestRate
Returns the interest rate (in basis points) for a given total periods and amortization status
treasuryRate + 100 BPS spread (for mortgages with a payment plan)
treasuryRate + 200 BPS spread (for mortgages without a payment plan)
function interestRate(uint8 totalPeriods, bool hasPaymentPlan) external view override returns (uint16 rate);
Parameters
| Name | Type | Description |
|---|---|---|
totalPeriods | uint8 | The total number of periods for the mortgage |
hasPaymentPlan | bool | Whether the mortgage has a payment plan |
Returns
| Name | Type | Description |
|---|---|---|
rate | uint16 | The interest rate |
Errors
InvalidTotalPeriods
The error thrown when the total periods are invalid and not supported by the InterestRateOracle
error InvalidTotalPeriods(uint8 totalPeriods);
Parameters
| Name | Type | Description |
|---|---|---|
totalPeriods | uint8 | The total periods |
SubConsol
Inherits: Context, ERC165, AccessControl, ERC20, ISubConsol
Title: SubConsol
Author: SocksNFlops
SubConsol is a contract that allows users to deposit collateral and mint an input into Consol
State Variables
collateral
Get the collateral token
address public immutable override collateral
yieldStrategy
Get the yield strategy
address public override yieldStrategy
yieldAmount
Get the amount of yield in the yield strategy
uint256 public override yieldAmount
Functions
constructor
Constructor
constructor(string memory name_, string memory symbol_, address admin_, address collateral_) ERC20(name_, symbol_);
Parameters
| Name | Type | Description |
|---|---|---|
name_ | string | The name of the token |
symbol_ | string | The symbol of the token |
admin_ | address | The address of the admin |
collateral_ | address | The address of the collateral |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC165) returns (bool);
setYieldStrategy
Set the yield strategy
function setYieldStrategy(address yieldStrategy_) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
yieldStrategy_ | address | The address of the yield strategy |
depositCollateral
Deposit collateral into the Consol contract while minting a specified amount of SubConsol
function depositCollateral(uint256 collateralAmount, uint256 mintAmount)
external
override
onlyRole(Roles.ACCOUNTING_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
collateralAmount | uint256 | The amount of collateral to deposit |
mintAmount | uint256 | The amount of SubConsol to mint |
_withdrawCollateral
Internal function to withdraw collateral from the contract
function _withdrawCollateral(address to, uint256 collateralAmount, uint256 burnAmount)
internal
onlyRole(Roles.ACCOUNTING_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | The address to send the collateral to |
collateralAmount | uint256 | The amount of collateral to withdraw |
burnAmount | uint256 | The amount of tokens to burn |
withdrawCollateral
Withdraw collateral from the Consol contract while burning a specified amount of SubConsol
function withdrawCollateral(address to, uint256 collateralAmount, uint256 burnAmount) public override;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | The address to send the collateral to |
collateralAmount | uint256 | The amount of collateral to withdraw |
burnAmount | uint256 | The amount of SubConsol to burn |
withdrawCollateralAsync
Withdraw collateral from the SubConsol contract asynchronously (from the yield strategy if necessary)
function withdrawCollateralAsync(address to, uint256 collateralAmount, uint256 burnAmount) external override;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | The address to send the collateral to |
collateralAmount | uint256 | The amount of collateral to withdraw |
burnAmount | uint256 | The amount of SubConsol to burn |
depositToYieldStrategy
Deposit collateral into the yield strategy
function depositToYieldStrategy(uint256 collateralAmount) external override onlyRole(Roles.PORTFOLIO_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
collateralAmount | uint256 | The amount of collateral to deposit |
withdrawFromYieldStrategy
Withdraw collateral from the yield strategy
function withdrawFromYieldStrategy(uint256 collateralAmount) external override onlyRole(Roles.PORTFOLIO_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
collateralAmount | uint256 | The amount of collateral to withdraw |
USDX
Inherits: IUSDX, MultiTokenVault
Title: USDX
Author: SocksNFlops
USDX is a wrapper token for USD-pegged tokens.
State Variables
tokenScalars
mapping(address token => TokenScalars scalars) public override tokenScalars
Functions
constructor
Constructor
constructor(string memory name_, string memory symbol_, uint8 decimalsOffset_, address admin_)
MultiTokenVault(name_, symbol_, decimalsOffset_, admin_);
Parameters
| Name | Type | Description |
|---|---|---|
name_ | string | The name of the token |
symbol_ | string | The symbol of the token |
decimalsOffset_ | uint8 | The number of decimals to pad the internal shares with to avoid precision loss |
admin_ | address | The address of the admin |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual override(MultiTokenVault) returns (bool);
addSupportedToken
Add a supported token to the MultiTokenVault
function addSupportedToken(address token)
public
override(MultiTokenVault, IMultiTokenVault)
onlyRole(Roles.SUPPORTED_TOKEN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to add |
addSupportedToken
Add a supported token to the MultiTokenVault with specified scalar values
function addSupportedToken(address token, uint256 scalarNumerator, uint256 scalarDenominator)
external
override
onlyRole(Roles.SUPPORTED_TOKEN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to add |
scalarNumerator | uint256 | The scalar numerator for the token |
scalarDenominator | uint256 | The scalar denominator for the token |
removeSupportedToken
Remove a supported token from the MultiTokenVault
function removeSupportedToken(address token)
public
override(MultiTokenVault, IMultiTokenVault)
onlyRole(Roles.SUPPORTED_TOKEN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to remove |
convertAmount
Calculates the amount of tokens minted/burned in a deposit/withdraw operation
function convertAmount(address token, uint256 amount)
public
view
virtual
override(MultiTokenVault, IMultiTokenVault)
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to deposit/withdraw |
amount | uint256 | The amount of tokens to deposit/withdraw |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The mint/burn amount |
convertUnderlying
Calculates the amount of underlying tokens required to deposit/withdraw a given amount of tokens
function convertUnderlying(address token, uint256 amount)
public
view
virtual
override(MultiTokenVault, IMultiTokenVault)
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The address of the token to deposit/withdraw |
amount | uint256 | The amount of tokens minted/burned as a result of the deposit/withdraw operation |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The amount of underlying tokens required to deposit/withdraw the given amount of tokens |
_totalSupply
Internal function to get the total supply of the token. Calculated by summing up the balances of all supported tokens and scaling them by the token scalars.
function _totalSupply() internal view virtual override returns (uint256 totalSupply);
Returns
| Name | Type | Description |
|---|---|---|
totalSupply | uint256 | The total supply of the token |
burn
Burn a specified amount of USDX for a proportional amount of each supported token
function burn(uint256 amount) public;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of USDX to burn |
UsdxQueue
Inherits: LenderQueue
Title: UsdxQueue
Author: @SocksNFlops
Queue for withdrawing assets from the Consol contract.
Functions
constructor
Constructor
constructor(address asset_, address consol_, address admin_) LenderQueue(asset_, consol_, admin_);
Parameters
| Name | Type | Description |
|---|---|---|
asset_ | address | The address of the asset |
consol_ | address | The address of the Consol contract |
admin_ | address | The address of the admin |
processWithdrawalRequests
function processWithdrawalRequests(uint256 iterations, address receiver)
external
virtual
override
nonReentrant
whenNotPaused
onlyRole(Roles.PROCESSOR_ROLE);
Periphery Contracts
Reference for every contract in the periphery package (buttonwood-protocol/v1-periphery), generated from the contract source.
FulfillmentVault
Inherits: LiquidityVault, IFulfillmentVault
Title: FulfillmentVault
Author: @SocksNFlops
The FulfillmentVault contract used to fulfill orders on the protocol
State Variables
FulfillmentVaultStorageLocation
The storage location of the FulfillmentVault contract
keccak256(abi.encode(uint256(keccak256("buttonwood.storage.FulfillmentVault")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant FulfillmentVaultStorageLocation =
0x4b57f16710661390ada38fe64129442a589f51d339ba23973c82ad806b168200
Functions
receive
Allow the contract to receive network native tokens (HYPE bridged from Core)
receive() external payable;
_getFulfillmentVaultStorage
Gets the storage location of the FulfillmentVault contract
function _getFulfillmentVaultStorage() private pure returns (FulfillmentVaultStorage storage $);
Returns
| Name | Type | Description |
|---|---|---|
$ | FulfillmentVaultStorage | The storage location of the FulfillmentVault contract |
__FulfillmentVault_init
Initializes the FulfillmentVault contract and calls parent initializers
function __FulfillmentVault_init(
string memory name,
string memory symbol,
uint8 _decimals,
uint8 _decimalsOffset,
address _wrappedNativeToken,
address _generalManager
) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
name | string | The name of the fulfillment vault |
symbol | string | The symbol of the fulfillment vault |
_decimals | uint8 | The decimals of the fulfillment vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_wrappedNativeToken | address | The address of the wrapped native token |
_generalManager | address | The address of the general manager |
__FulfillmentVault_init_unchained
Initializes the FulfillmentVault contract only
function __FulfillmentVault_init_unchained(address _wrappedNativeToken, address _generalManager)
internal
onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
_wrappedNativeToken | address | The address of the wrapped native token |
_generalManager | address | The address of the general manager |
initialize
Initializes the FulfillmentVault contract
function initialize(
string memory name,
string memory symbol,
uint8 _decimals,
uint8 _decimalsOffset,
address _wrappedNativeToken,
address _generalManager,
address admin
) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
name | string | The name of the fulfillment vault |
symbol | string | The symbol of the fulfillment vault |
_decimals | uint8 | The decimals of the fulfillment vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_wrappedNativeToken | address | The address of the wrapped native token |
_generalManager | address | The address of the general manager |
admin | address | The address of the admin for the fulfillment vault |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId) public view override(LiquidityVault) returns (bool);
_totalAssets
Both depositable and redeemable assets are the same asset, so we override totalAssets to return the balance of only the redeemable asset.
function _totalAssets() internal view override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total assets of the vault |
wrappedNativeToken
Gets the address of the wrapped native token
function wrappedNativeToken() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the wrapped native token (i.e., whype: 0x555...) |
generalManager
Gets the address of the general manager
function generalManager() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the general manager |
orderPool
Gets the address of the order pool
function orderPool() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the order pool |
usdx
Gets the address of the USDX token
function usdx() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the USDX token |
nonce
Gets the ongoing nonce that generates distinct cloid values for exchanges on core
function nonce() public view override returns (uint128);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint128 | The ongoing nonce |
approveAssetToOrderPool
Approves an asset to the order pool
Does not need a keeper role or paused-state
function approveAssetToOrderPool(address asset) external;
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | The address of the asset to approve |
wrapHype
Wraps entire hype balance of the fulfillment vault into whype
Does not need a keeper role or paused-state
function wrapHype() external;
unwrapHype
Unwraps entire whype balance of the fulfillment vault into hype
Does not need a keeper role or paused-state
function unwrapHype() external;
bridgeAssetFromCoreToEvm
Bridges an asset from core to evm
function bridgeAssetFromCoreToEvm(uint64 assetIndex, uint256 amount)
external
override
onlyRole(KEEPER_ROLE)
whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
assetIndex | uint64 | The index of the asset to bridge |
amount | uint256 | The amount of asset to bridge (in evm units) |
burnUsdx
Burns USDX into usdTokens for the purpose of transferring them to core
function burnUsdx(uint256 amount) external override onlyRole(KEEPER_ROLE) whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of USDX to burn |
withdrawUsdTokenFromUsdx
Withdraws usdToken from usdx
function withdrawUsdTokenFromUsdx(address usdToken, uint256 amount)
external
override
onlyRole(KEEPER_ROLE)
whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
usdToken | address | The address of the usdToken to withdraw |
amount | uint256 | The amount of usdToken to withdraw |
depositUsdTokenToUsdx
Deposits usdToken into usdx
function depositUsdTokenToUsdx(address usdToken, uint256 amount) external override onlyRole(KEEPER_ROLE) whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
usdToken | address | The address of the usdToken to deposit |
amount | uint256 | The amount of usdToken to deposit |
bridgeAssetFromEvmToCore
Bridges assets from evm to core
function bridgeAssetFromEvmToCore(address asset, uint256 amount) external override onlyRole(KEEPER_ROLE) whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | The address of the asset to bridge |
amount | uint256 | The amount of asset to bridge |
tradeOnCore
Trades tokens on core
function tradeOnCore(uint32 spotId, bool isBuy, uint64 limitPx, uint64 sz)
external
override
onlyRole(KEEPER_ROLE)
whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
spotId | uint32 | The spotId of the asset to trade (identifies the trading pair) |
isBuy | bool | Whether to buy or sell |
limitPx | uint64 | The limit price. Note, This is is (weiUnits - szUnits). For USDT0 and USDC, weiUnits is 1e6. |
sz | uint64 | The size of the trade. Note, this is in szUnits. For USDT0 and USDC, szUnits is 1e2. |
fillOrder
Fills an order from the order pool
function fillOrder(uint256 index, uint256[] memory hintPrevIds) external override onlyRole(KEEPER_ROLE) whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
index | uint256 | The index of the order to fill |
hintPrevIds | uint256[] | The hint prev ids for the relevant mortgage queues. |
Structs
FulfillmentVaultStorage
The storage for the FulfillmentVault contract
Note: storage-location: erc7201:buttonwood.storage.FulfillmentVault
struct FulfillmentVaultStorage {
address _wrappedNativeToken;
address _generalManager;
address _usdx;
uint128 _nonce;
}
Properties
| Name | Type | Description |
|---|---|---|
_wrappedNativeToken | address | The address of the wrapped native token |
_generalManager | address | The address of the general manager |
_usdx | address | The address of the USDX token |
_nonce | uint128 | The ongoing nonce that generates distinct cloid values for exchanges on core |
LiquidityVault
Inherits: ILiquidityVault, ERC165Upgradeable, AccessControlUpgradeable, PausableUpgradeable, UUPSUpgradeable, ERC20Upgradeable
Title: LiquidityVault
Author: @SocksNFlops
The base liquidity vault contract used by FulfillmentVault and RolloverVault
State Variables
KEEPER_ROLE
The role for the keeper
bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE")
WHITELIST_ROLE
bytes32 public constant WHITELIST_ROLE = keccak256("WHITELIST_ROLE")
LiquidityVaultStorageLocation
The storage location of the LiquidityVault contract
keccak256(abi.encode(uint256(keccak256("buttonwood.storage.LiquidityVault")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant LiquidityVaultStorageLocation =
0x279d7268e134fe9470212f64c617da0df55170c0eafa03169b80558ce404b000
Functions
_getLiquidityVaultStorage
Gets the storage location of the LiquidityVault contract
function _getLiquidityVaultStorage() private pure returns (LiquidityVaultStorage storage $);
Returns
| Name | Type | Description |
|---|---|---|
$ | LiquidityVaultStorage | The storage location of the LiquidityVault contract |
__LiquidityVault_init
Initializes the LiquidityVault contract and calls parent initializers
function __LiquidityVault_init(
string memory name,
string memory symbol,
uint8 _decimals,
uint8 _decimalsOffset,
address[] memory _depositableAssets,
address[] memory _redeemableAssets
) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
name | string | The name of the liquidity vault |
symbol | string | The symbol of the liquidity vault |
_decimals | uint8 | The decimals of the liquidity vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_depositableAssets | address[] | The addresses of the depositable assets |
_redeemableAssets | address[] | The addresses of the redeemable assets |
__LiquidityVault_init_unchained
Initializes the LiquidityVault contract only
function __LiquidityVault_init_unchained(
uint8 _decimals,
uint8 _decimalsOffset,
address[] memory _depositableAssets,
address[] memory _redeemableAssets
) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
_decimals | uint8 | The decimals of the liquidity vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_depositableAssets | address[] | The addresses of the depositable assets |
_redeemableAssets | address[] | The addresses of the redeemable assets |
initialize
Initializes the LiquidityVault contract
function initialize(
string memory name,
string memory symbol,
uint8 _decimals,
uint8 _decimalsOffset,
address[] memory _depositableAssets,
address[] memory _redeemableAssets,
address admin
) external virtual initializer;
Parameters
| Name | Type | Description |
|---|---|---|
name | string | The name of the liquidity vault |
symbol | string | The symbol of the liquidity vault |
_decimals | uint8 | The decimals of the liquidity vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_depositableAssets | address[] | The addresses of the depositable assets |
_redeemableAssets | address[] | The addresses of the redeemable assets |
admin | address | The address of the admin for the liquidity vault |
constructor
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlUpgradeable, ERC165Upgradeable)
returns (bool);
_authorizeUpgrade
Function that should revert when msg.sender is not authorized to upgrade the contract. Called by
{upgradeToAndCall}.
Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
function _authorizeUpgrade(address) internal onlyOwner {}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyRole(DEFAULT_ADMIN_ROLE);
checkWhitelistEnforced
When whitelist is enforced, the sender must have the WHITELIST_ROLE. Otherwise, WHITELIST_ROLE is not required.
modifier checkWhitelistEnforced() ;
whitelistEnforced
Whether the whitelist is enforced.
function whitelistEnforced() public view virtual override returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | Whether the whitelist is enforced. |
setWhitelistEnforced
Enforces the whitelist.
function setWhitelistEnforced(bool enforced) external virtual override onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
enforced | bool | Whether the whitelist is enforced. |
decimals
Returns the decimals places of the token.
function decimals() public view virtual override returns (uint8);
decimalsOffset
The decimals offset. The number of decimals to offset the shares by. Used to protect against inflation attacks.
function decimalsOffset() public view virtual override returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | The decimals offset |
depositableAssets
The address of the depositable asset.
function depositableAssets() public view virtual override returns (address[] memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | The address of the depositable asset. |
redeemableAssets
The addresses of the redeemable assets.
function redeemableAssets() public view virtual override returns (address[] memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | The addresses of the redeemable assets. |
_updateAssets
Updates the assets of the vault
function _updateAssets(address asset, bool isRedeemable, bool add) internal;
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | The address of the asset to update |
isRedeemable | bool | Whether the asset is redeemable |
add | bool | Whether to add the asset or remove the asset |
_totalAssets
Calculates the total assets of the vault
function _totalAssets() internal view virtual returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total assets of the vault |
totalAssets
The total assets of the vault
function totalAssets() public view virtual override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total assets of the vault |
_convertToShares
Internal conversion function (from assets to shares) with support for rounding direction.
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
assets | uint256 | The amount of assets to convert to shares |
rounding | Math.Rounding | The rounding direction |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The amount of shares |
_convertToAssets
Internal conversion function (from shares to assets) with support for rounding direction.
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
shares | uint256 | The amount of shares to convert to assets |
rounding | Math.Rounding | The rounding direction |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256[] | The amount of assets |
setPaused
Sets the paused state of the vault.
function setPaused(bool paused) external virtual override onlyRole(KEEPER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
paused | bool | The paused state of the vault. |
deposit
Deposits the specified amount of depositable asset into the vault.
function deposit(address depositableAsset, uint256 assets)
external
virtual
override
whenNotPaused
checkWhitelistEnforced;
Parameters
| Name | Type | Description |
|---|---|---|
depositableAsset | address | The address of the depositable asset to deposit. |
assets | uint256 | The amount of depositable asset to deposit. |
redeem
Redeems the specified amount of shares for the redeemable asset.
No whitelist enforcement for redeeming. This prevents funds from being locked in the vault.
function redeem(uint256 shares) external virtual override whenNotPaused;
Parameters
| Name | Type | Description |
|---|---|---|
shares | uint256 | The amount of shares to redeem. |
Structs
LiquidityVaultStorage
The storage for the LiquidityVault contract
Note: storage-location: erc7201:buttonwood.storage.LiquidityVault
struct LiquidityVaultStorage {
uint8 _decimals;
uint8 _decimalsOffset;
address[] _depositableAssets;
mapping(address => uint256) _depositableAssetIndex;
address[] _redeemableAssets;
mapping(address => uint256) _redeemableAssetIndex;
bool _whitelistEnforced;
}
Properties
| Name | Type | Description |
|---|---|---|
_decimals | uint8 | The decimals of the vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_depositableAssets | address[] | The addresses of the depositable assets |
_depositableAssetIndex | mapping(address => uint256) | The index of the depositable assets (one-indexed) |
_redeemableAssets | address[] | The addresses of the redeemable assets |
_redeemableAssetIndex | mapping(address => uint256) | The index of the redeemable assets (one-indexed) |
_whitelistEnforced | bool | Whether the whitelist is enforced |
RolloverVault
Inherits: LiquidityVault, IRolloverVault
Title: FulfillmentVault
Author: @SocksNFlops
The RolloverVault contract used to automatically rotate unused assets into origination pools.
State Variables
RolloverVaultStorageLocation
The storage location of the RolloverVault contract
keccak256(abi.encode(uint256(keccak256("buttonwood.storage.RolloverVault")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant RolloverVaultStorageLocation =
0x3f3d57a95a7cc1b3218bff2f60330bfeb789b9a101fe5e689535b16f8256e000
Functions
receive
Allow the contract to receive network native tokens (HYPE bridged from Core)
receive() external payable;
_getRolloverVaultStorage
Gets the storage location of the RolloverVault contract
function _getRolloverVaultStorage() private pure returns (RolloverVaultStorage storage $);
Returns
| Name | Type | Description |
|---|---|---|
$ | RolloverVaultStorage | The storage location of the RolloverVault contract |
__RolloverVault_init
Initializes the RolloverVault contract and calls parent initializers
function __RolloverVault_init(
string memory name,
string memory symbol,
uint8 _decimals,
uint8 _decimalsOffset,
address _generalManager
) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
name | string | The name of the rollover vault |
symbol | string | The symbol of the rollover vault |
_decimals | uint8 | The decimals of the rollover vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_generalManager | address | The address of the general manager |
__RolloverVault_init_unchained
Initializes the RolloverVault contract only
function __RolloverVault_init_unchained(address _generalManager) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
_generalManager | address | The address of the general manager |
initialize
Initializes the RolloverVault contract
function initialize(
string memory name,
string memory symbol,
uint8 _decimals,
uint8 _decimalsOffset,
address _generalManager,
address admin
) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
name | string | The name of the rollover vault |
symbol | string | The symbol of the rollover vault |
_decimals | uint8 | The decimals of the rollover vault |
_decimalsOffset | uint8 | The decimals offset for measuring internal precision of shares |
_generalManager | address | The address of the general manager |
admin | address | The address of the admin for the rollover vault |
supportsInterface
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
function supportsInterface(bytes4 interfaceId) public view override(LiquidityVault) returns (bool);
_totalAssets
Calculates the total assets of the vault
function _totalAssets() internal view override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total assets of the vault |
usdx
Gets the address of the USDX token
function usdx() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the USDX token |
consol
Gets the address of the consol token
function consol() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the consol token |
generalManager
Gets the address of the general manager
function generalManager() public view override returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the general manager |
originationPoolScheduler
Gets the address of the origination pool scheduler
function originationPoolScheduler() public view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address of the origination pool scheduler |
originationPools
Gets the addresses of the origination pools the rollover vault currently has a balance in
function originationPools() external view override returns (address[] memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | The addresses of the origination pools the rollover vault currently has a balance in |
isTracked
Checks if the given origination pool is being tracked by the rollover vault
function isTracked(address originationPool) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
originationPool | address | The address of the origination pool to check if it is being tracked |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the origination pool is being tracked, false otherwise |
depositOriginationPool
Deposits the given amount of the given origination pool into the rollover vault
function depositOriginationPool(address originationPool, uint256 amount) external onlyRole(KEEPER_ROLE) whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
originationPool | address | The address of the origination pool to deposit into |
amount | uint256 | The amount of the origination pool to deposit |
redeemOriginationPool
Redeems the entire balance of the given origination pool from the rollover vault
function redeemOriginationPool(address originationPool) external onlyRole(KEEPER_ROLE) whenPaused;
Parameters
| Name | Type | Description |
|---|---|---|
originationPool | address | The address of the origination pool to redeem from |
Structs
RolloverVaultStorage
The storage for the RolloverVault contract
Note: storage-location: erc7201:buttonwood.storage.RolloverVault
struct RolloverVaultStorage {
address _usdx;
address _consol;
address _generalManager;
address[] _originationPools;
mapping(address => uint256) _poolIndex;
}
Properties
| Name | Type | Description |
|---|---|---|
_usdx | address | The address of the USDX token |
_consol | address | The address of the consol token |
_generalManager | address | The address of the general manager |
_originationPools | address[] | The addresses of the origination pools the rollover vault currently has a balance in |
_poolIndex | mapping(address => uint256) | Mapping of origination pool addresses to their index in the _originationPools array (offset by 1) |
Router
Inherits: IRouter, Context, IMortgageNFTErrors, IERC20Errors, IGeneralManagerErrors, IOriginationPoolErrors, IOriginationPoolSchedulerErrors
Title: Router
Author: @SocksNFlops
This contract facilitates user interactions with core contracts of the Cash protocol.
State Variables
generalManager
The address of the general manager contract
address public immutable generalManager
rolloverVault
The address of the rollover vault contract
address public immutable rolloverVault
fulfillmentVault
The address of the fulfillment vault contract
address public immutable fulfillmentVault
pyth
The address of the Pyth contract
address public immutable pyth
wrappedNativeToken
The address of the wrapped native token
address public immutable wrappedNativeToken
usdx
The address of the USDX token contract
address public immutable usdx
consol
The address of the Consol token contract
address public immutable consol
originationPoolScheduler
The address of the origination pool scheduler contract
address public immutable originationPoolScheduler
Functions
constructor
constructor(
address _wrappedNativeToken,
address _generalManager,
address _rolloverVault,
address _fulfillmentVault,
address _pyth
) ;
Parameters
| Name | Type | Description |
|---|---|---|
_wrappedNativeToken | address | The address of the wrapped native token (i.e., whype: 0x555...) |
_generalManager | address | The address of the general manager contract |
_rolloverVault | address | The address of the rollover vault contract |
_fulfillmentVault | address | The address of the fulfillment vault contract |
_pyth | address | The address of the Pyth contract |
receive
receive() external payable;
approveCollaterals
Approve all the collaterals to be spent by the general manager
function approveCollaterals() external;
approveUsdTokens
Approve all the usdTokens to be spent by the USDX contract (for depositing into USDX)
function approveUsdTokens() external;
_pullUsdToken
Internal function to pull in USDX via the underlying usdToken
function _pullUsdToken(address usdToken, uint256 usdxAmount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
usdToken | address | The address of the usdToken to pull in |
usdxAmount | uint256 | The amount of USDX to pull in |
_pullInConsol
Internal function to pull in Consol via the underlying usdTokens, USDX, SubConsols, or ForfeitedAssetsPool
function _pullInConsol(address inputToken, uint256 consolAmount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token to pull in |
consolAmount | uint256 | The amount of Consol to pull in |
_pullCollateral
Internal function to pull in collateral
function _pullCollateral(address collateral, uint256 collateralCollected, bool isNative) internal;
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral token to pull in |
collateralCollected | uint256 | The amount of collateral to pull in |
isNative | bool | Whether the collateral is the native token or not (i.e., whype: 0x555...) |
_calculateCost
Internal function to calculate the cost of a borrowing the collateral amount (including the price spread)
function _calculateCost(address collateral, uint256 collateralAmount)
internal
view
returns (uint256 cost, uint8 collateralDecimals);
Parameters
| Name | Type | Description |
|---|---|---|
collateral | address | The address of the collateral token |
collateralAmount | uint256 | The amount of collateral to calculate the cost for |
Returns
| Name | Type | Description |
|---|---|---|
cost | uint256 | The cost of the collateral amount (including the price spread) |
collateralDecimals | uint8 | The decimals of the collateral token |
calculateCollectedAmounts
Calculates the amounts that will be collected from the borrower for a given creation request before sending the request to the general manager
function calculateCollectedAmounts(CreationRequest calldata creationRequest)
public
view
returns (uint256 collateralCollected, uint256 usdxCollected, uint256 paymentAmount, uint8 collateralDecimals);
Parameters
| Name | Type | Description |
|---|---|---|
creationRequest | CreationRequest | The creation request |
Returns
| Name | Type | Description |
|---|---|---|
collateralCollected | uint256 | The amount of collateral that will be collected from the borrower |
usdxCollected | uint256 | The amount of USDX that will be collected from the borrower |
paymentAmount | uint256 | The amount of USDX that will be paid to the fulfilller |
collateralDecimals | uint8 | The decimals of the collateral token |
updatePriceFeedsAndRequestMortgage
Request a mortgage
function updatePriceFeedsAndRequestMortgage(
bytes[] calldata priceUpdates,
address usdToken,
CreationRequest calldata creationRequest,
bool isNative,
uint256 maxCollected
)
public
payable
returns (uint256 collateralCollected, uint256 usdxCollected, uint256 paymentAmount, uint8 collateralDecimals);
Parameters
| Name | Type | Description |
|---|---|---|
priceUpdates | bytes[] | The price updates to send to the Pyth contract |
usdToken | address | The address of the usdToken to pull in |
creationRequest | CreationRequest | The creation request |
isNative | bool | Whether the collateral is the native token or not (i.e., whype: 0x555...) |
maxCollected | uint256 | The maximum amount that can be collected from the borrower (in USDX if non-compounding, in collateral if compounding) |
Returns
| Name | Type | Description |
|---|---|---|
collateralCollected | uint256 | The amount of collateral collected |
usdxCollected | uint256 | The amount of USDX collected |
paymentAmount | uint256 | The amount of payment to be made |
collateralDecimals | uint8 | The decimals of the collateral |
requestMortgage
Request a mortgage
function requestMortgage(
address usdToken,
CreationRequest calldata creationRequest,
bool isNative,
uint256 maxCollected
)
public
payable
returns (uint256 collateralCollected, uint256 usdxCollected, uint256 paymentAmount, uint8 collateralDecimals);
Parameters
| Name | Type | Description |
|---|---|---|
usdToken | address | The address of the usdToken to pull in |
creationRequest | CreationRequest | The creation request |
isNative | bool | Whether the collateral is the native token or not (i.e., whype: 0x555...) |
maxCollected | uint256 | The maximum amount that can be collected from the borrower (in USDX if non-compounding, in collateral if compounding) |
Returns
| Name | Type | Description |
|---|---|---|
collateralCollected | uint256 | The amount of collateral collected |
usdxCollected | uint256 | The amount of USDX collected |
paymentAmount | uint256 | The amount of payment to be made |
collateralDecimals | uint8 | The decimals of the collateral |
periodPay
Make a periodic payment on a mortgage
function periodPay(address inputToken, uint256 tokenId, uint256 inputAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token to pull in |
tokenId | uint256 | The token ID |
inputAmount | uint256 | The amount of input token to pull in |
penaltyPay
Make a penalty payment on a mortgage
function penaltyPay(address inputToken, uint256 tokenId, uint256 inputAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token to pull in |
tokenId | uint256 | The token ID |
inputAmount | uint256 | The amount of input token to pull in |
refinance
Refinance a mortgage
function refinance(address inputToken, uint256 tokenId, uint8 newTotalPeriods) external;
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token to pull in |
tokenId | uint256 | The token ID of the mortgage to refinance |
newTotalPeriods | uint8 | The new total periods of the mortgage |
_getOrCreateOriginationPool
Internal function to get or create the latest origination pool for a given OPoolConfigId
function _getOrCreateOriginationPool(OPoolConfigId oPoolConfigId)
internal
returns (IOriginationPool originationPool);
Parameters
| Name | Type | Description |
|---|---|---|
oPoolConfigId | OPoolConfigId | The OPoolConfigId of the origination pool config |
Returns
| Name | Type | Description |
|---|---|---|
originationPool | IOriginationPool | The origination pool |
originationPoolDeposit
Deposit into an origination pool
function originationPoolDeposit(OPoolConfigId oPoolConfigId, address usdToken, uint256 usdTokenAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
oPoolConfigId | OPoolConfigId | The OPoolConfigId of the origination pool to deposit into |
usdToken | address | The address of the usdToken to pull in |
usdTokenAmount | uint256 | The amount of usdToken to pull in |
convert
Quotes the amount of output token that would be received for a given amount of input token
function convert(address inputToken, address outputToken, uint256 inputAmount)
public
view
returns (uint256 outputAmount);
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token |
outputToken | address | The address of the output token |
inputAmount | uint256 | The amount of input token to convert |
Returns
| Name | Type | Description |
|---|---|---|
outputAmount | uint256 | The amount of output token received |
wrap
Wraps tokens from usdToken -> usdx -> consol
function wrap(address inputToken, address outputToken, uint256 inputAmount) public;
Parameters
| Name | Type | Description |
|---|---|---|
inputToken | address | The address of the input token |
outputToken | address | The address of the output token |
inputAmount | uint256 | The amount of input token to convert |
_vaultDeposit
Internal function to deposit into a liquidity vault
function _vaultDeposit(address vault, address usdToken, uint256 usdTokenAmount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
vault | address | The address of the liquidity vault to deposit into |
usdToken | address | The address of the usdToken to pull in |
usdTokenAmount | uint256 | The amount of usdToken to pull in |
rolloverVaultDeposit
Deposit into the rollover vault
function rolloverVaultDeposit(address usdToken, uint256 usdTokenAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
usdToken | address | The address of the usdToken to pull in |
usdTokenAmount | uint256 | The amount of usdToken to pull in |
fulfillmentVaultDeposit
Deposit into the fulfillment vault
function fulfillmentVaultDeposit(address usdToken, uint256 usdTokenAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
usdToken | address | The address of the usdToken to pull in |
usdTokenAmount | uint256 | The amount of usdToken to pull in |