Skip to main content

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

ContractUpgradeablePausablePermissionsNotes
OriginationPoolSchedulerYes (UUPS)YesYes
OriginationPoolNoYesYesERC20 receipt tokens
GeneralManagerYes (UUPS)YesYes
LoanManagerNoNoNoFlash-swaps via Consol
MortgageNFTNoNoNoERC721
OrderPoolNoNoYes
SubConsolNoNoYesERC20 (not rebasing)
USDXNoNoYesRebasing
ConsolNoNoYesRebasing
ForfeitedAssetsPoolNoYesYesERC20 (not rebasing)
ConversionQueueNoNoYesLenderQueue + MortgageQueue
UsdxQueueNoYesYesLenderQueue
ForfeitedAssetsQueueNoYesYesLenderQueue
PythPriceOracleNoNoNoPyth pull-oracle
PythInterestRateOracleNoNoNoPyth pull-oracle

Core Contracts

Token Contracts

ContractDescription
USDXUnified USD-pegged vault wrapping multiple stablecoins with configurable scaling factors into a standard 18-decimal rebasing token
ConsolThe 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.
SubConsolCollateral-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.
RebasingERC20Abstract shares-based ERC20 where balances adjust based on underlying asset value — enables passive yield accrual
MultiTokenVaultAbstract vault accepting multiple ERC20 deposits, minting a single rebasing token. Provides relative token caps and registry.

Lending & Borrowing

ContractDescription
GeneralManagerCentral upgradeable orchestrator. Validates and routes mortgage requests through OriginationPools, coordinates oracles, manages collateral types and terms, handles balance sheet expansions.
LoanManagerManages full mortgage lifecycle — creation (depositing collateral into SubConsols), payment processing with automatic late fees, redemption, refinancing, foreclosure, and conversions
MortgageNFTERC-721 representing ownership of a mortgage position. Manages user-chosen MortgageId labels.
OriginationPoolNon-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.
OriginationPoolSchedulerCreates new OriginationPools on a weekly schedule. Manages pool configurations including limits, growth rates, and multipliers.
OrderPoolOrder 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

ContractDescription
ConversionQueueDouble-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.
UsdxQueueFIFO withdrawal queue — users deposit Consol and receive USDX. Permissionless processing with gas fee collection.
ForfeitedAssetsQueueFIFO withdrawal queue — users deposit Consol to burn ForfeitedAssetsPool tokens for underlying foreclosed collateral. Value received may exceed Consol deposited.
MortgageQueueSorted linked-list of mortgage positions ordered by trigger price (lowest to highest) for efficient conversion processing
LenderQueueAbstract base for FIFO withdrawal queues with gas fees, minimum amounts, and cancellation logic
QueueProcessorProcesses items across the various queues

Oracles

ContractDescription
PythPriceOraclePull-oracle for real-time collateral/USD prices. Validates freshness (max 60s) and confidence thresholds.
PythInterestRateOracleReads 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.
StaticInterestRateOracleFallback fixed interest rate oracle

Other

ContractDescription
ForfeitedAssetsPoolHolds 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

ContractDescription
RouterEntry point for all user transactions — handles multi-step flows (wrap, approve, deposit)
RolloverVaultAutomated vault that re-invests lender capital across pool epochs
FulfillmentVaultVault providing liquidity for order fulfillment on the chain's trading venue
LiquidityVaultAbstract 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

InterfacePurpose
IInterestRateOracleDynamic interest rates based on term length and payment structure
IPriceOracleReal-time collateral pricing in USDX terms
IConsolFlashSwapFlash swap callback for temporarily borrowing from Consol
IOriginationPoolDeployCallbackCallback for origination pool fund deployment (flash-lending)
IYieldStrategyYield-generating strategies for SubConsol collateral
INFTMetadataGeneratorDynamic 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

Git Source

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

NameTypeDescription
name_stringThe name of the token
symbol_stringThe symbol of the token
decimalsOffset_uint8The number of decimals to pad the internal shares with to avoid precision loss
admin_addressThe address of the admin
forfeitedAssetsPool_addressThe 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

NameTypeDescription
forfeitedAssetsPool_addressThe 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

NameTypeDescription
tokenaddressThe address of the token to withdraw
amountuint256The 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

NameTypeDescription
inputTokenaddressThe address of the input token
outputTokenaddressThe address of the output token
amountuint256The amount of tokens to swap
databytesThe 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

NameTypeDescription
<none>uint256The total supply of the Consol token

ConversionQueue

Git Source

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

NameTypeDescription
asset_addressThe address of the asset to convert
decimals_uint8The number of decimals of the asset
consol_addressThe address of the Consol contract
nativeWrapper_addressThe address of the native wrapper contract
generalManager_addressThe address of the GeneralManager contract
admin_addressThe 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
mortgagePositionMortgagePositionThe mortgage position to calculate the collateral to use for
amountToUseuint256The amount of principal to use for the withdrawal request

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
mortgageTokenIduint256The tokenId of the mortgage position
hintPrevIduint256The 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

NameTypeDescription
iterationsuint256The number of iterations to process. Each iteration returns collected gas fees.
receiveraddressThe 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

NameTypeDescription
mortgageTokenIduint256The tokenId of the mortgage position

ForfeitedAssetsPool

Git Source

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

NameTypeDescription
name_stringThe name of the token
symbol_stringThe symbol of the token
_adminaddressThe 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

NameTypeDescription
assetaddressThe 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

NameTypeDescription
assetaddressThe 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

NameTypeDescription
indexuint256The index of the asset to get

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
assetaddressThe address of the asset to deposit
amountuint256The amount of the asset to deposit
liabilityuint256The 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

NameTypeDescription
receiveraddressThe address to send the assets to
liabilityuint256The amount of liabilities to burn in order to purchase assets from the forfeited assets pool.

Returns

NameTypeDescription
redeemedAssetsaddress[]The list of assets purchased
redeemedAmountsuint256[]The amount of assets purchased

setPaused

Pause or unpause the contract

function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);

Parameters

NameTypeDescription
pauseboolThe new paused state

ForfeitedAssetsQueue

Git Source

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

NameTypeDescription
asset_addressThe address of the forfeited assets pool
consol_addressThe address of the Consol contract
admin_addressThe address of the admin

processWithdrawalRequests

function processWithdrawalRequests(uint256 iterations, address receiver)
external
virtual
override
nonReentrant
whenNotPaused
onlyRole(Roles.PROCESSOR_ROLE);

GeneralManager

Git Source

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

NameTypeDescription
$GeneralManagerStorageThe 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

NameTypeDescription
usdx_addressThe address of the USDX token
consol_addressThe address of the Consol token
penaltyRate_uint16The penalty rate
refinanceRate_uint16The refinancing rate
conversionPremiumRate_uint16The conversion premium rate
priceSpread_uint16The price spread
insuranceFund_addressThe address of the insurance fund
interestRateOracle_addressThe 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

NameTypeDescription
usdx_addressThe address of the USDX token
consol_addressThe address of the Consol token
penaltyRate_uint16The penalty rate
refinanceRate_uint16The refinancing rate
conversionPremiumRate_uint16The conversion premium rate
priceSpread_uint16The price spread
insuranceFund_addressThe address of the insurance fund
interestRateOracle_addressThe 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

NameTypeDescription
usdx_addressThe address of the USDX token
consol_addressThe address of the Consol token
penaltyRate_uint16The penalty rate
refinanceRate_uint16The refinancing rate
conversionPremiumRate_uint16The conversion premium rate
priceSpread_uint16The price spread
insuranceFund_addressThe address of the insurance fund
interestRateOracle_addressThe 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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
conversionQueueListaddress[]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

NameTypeDescription
usingOrderPoolboolWhether the caller is using the order pool
conversionQueueListaddress[]The list of conversion queues to calculate the required gas fee for

Returns

NameTypeDescription
requiredGasFeeuint256The required gas fee

_checkSufficientGas

Checks if the caller sent enough value to cover the required gas fee

function _checkSufficientGas(uint256 requiredGasFee) internal view;

Parameters

NameTypeDescription
requiredGasFeeuint256The required gas fee

_refundSurplusGas

Refunds the surplus gas to the caller

function _refundSurplusGas(uint256 requiredGasFee) internal;

Parameters

NameTypeDescription
requiredGasFeeuint256The required gas fee

_validateMortgageOwner

Validates that the caller is the owner of the mortgage

function _validateMortgageOwner(uint256 tokenId) internal view;

Parameters

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
collateraladdressThe collateral address
totalPeriodsuint8The total periods

onlyMortgageOwner

Modifier to check if the caller is the owner of the mortgage

modifier onlyMortgageOwner(uint256 tokenId) ;

Parameters

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
mortgageParamsMortgageParamsThe mortgage parameters

_validateOriginationPools

Validates that the origination pools are supported

function _validateOriginationPools(address[] memory originationPools) internal view;

Parameters

NameTypeDescription
originationPoolsaddress[]The origination pools

_validateConversionQueues

Validates that the conversion queues have the CONVERSION_ROLE role

function _validateConversionQueues(address[] memory conversionQueueList) internal view;

Parameters

NameTypeDescription
conversionQueueListaddress[]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

NameTypeDescription
oldRoleHolderaddressThe address to remove the NFT role from
newRoleHolderaddressThe 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

NameTypeDescription
<none>addressThe USDX token address

consol

Returns the Consol token address

function consol() external view returns (address);

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
penaltyRate_uint16The 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

NameTypeDescription
<none>MortgagePosition

Returns

NameTypeDescription
<none>uint16The penalty rate

setRefinanceRate

Sets the refinance rate for a mortgage (in basis points)

function setRefinanceRate(uint16 refinanceRate_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
refinanceRate_uint16The 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

NameTypeDescription
<none>MortgagePosition

Returns

NameTypeDescription
<none>uint16The refinance rate

setInsuranceFund

Sets the insurance fund address

function setInsuranceFund(address insuranceFund_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
insuranceFund_addressThe insurance fund address

insuranceFund

Returns the insurance fund address

function insuranceFund() external view returns (address);

Returns

NameTypeDescription
<none>addressThe insurance fund address

setInterestRateOracle

Sets the interest rate oracle address

function setInterestRateOracle(address interestRateOracle_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
interestRateOracle_addressThe interest rate oracle address

interestRateOracle

Returns the interest rate oracle address

function interestRateOracle() external view returns (address);

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
collateraladdressThe address of the collateral
totalPeriodsuint8The total number of periods for the mortgage
hasPaymentPlanboolWhether the mortgage has a payment plan

Returns

NameTypeDescription
<none>uint16The interest rate

conversionPremiumRate

Returns the conversion premium rate (in basis points)

function conversionPremiumRate(address, uint8, bool) public view returns (uint16);

Parameters

NameTypeDescription
<none>address
<none>uint8
<none>bool

Returns

NameTypeDescription
<none>uint16The conversion premium rate

setConversionPremiumRate

Sets the conversion premium rate (in basis points)

function setConversionPremiumRate(uint16 conversionPremiumRate_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
conversionPremiumRate_uint16The conversion premium rate

setOriginationPoolScheduler

Sets the origination pool scheduler address

function setOriginationPoolScheduler(address originationPoolScheduler_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
originationPoolScheduler_addressThe origination pool scheduler address

originationPoolScheduler

Returns the origination pool scheduler address

function originationPoolScheduler() public view returns (address);

Returns

NameTypeDescription
<none>addressThe origination pool scheduler address

setLoanManager

Sets the loan manager address

function setLoanManager(address loanManager_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
loanManager_addressThe loan manager address

loanManager

Returns the loan manager address

function loanManager() public view returns (address);

Returns

NameTypeDescription
<none>addressThe loan manager address

mortgageNFT

Returns the mortgage NFT address

function mortgageNFT() public view returns (address);

Returns

NameTypeDescription
<none>addressThe mortgage NFT address

setOrderPool

Sets the order pool address

function setOrderPool(address orderPool_) external onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
orderPool_addressThe order pool address

orderPool

Returns the order pool address

function orderPool() public view returns (address);

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
collateraladdressThe address of the collateral
mortgagePeriodsuint8
isSupportedboolWhether 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

NameTypeDescription
collateraladdressThe address of the collateral
mortgagePeriodsuint8The mortgage period

Returns

NameTypeDescription
<none>boolWhether 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

NameTypeDescription
collateraladdressThe address of the collateral
priceOracleaddressThe address of the price oracle

priceOracles

The address of the price oracle for the collateral

function priceOracles(address collateral) external view returns (address);

Parameters

NameTypeDescription
collateraladdressThe address of the collateral

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
collateraladdressThe address of the collateral
minimumCap_uint256The 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

NameTypeDescription
collateraladdressThe address of the collateral

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
collateraladdressThe address of the collateral
maximumCap_uint256The 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

NameTypeDescription
collateraladdressThe address of the collateral

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
priceSpread_uint16The price spread

priceSpread

The price spread to incentivize the fulfiller to fill orders

function priceSpread() external view returns (uint16);

Returns

NameTypeDescription
<none>uint16priceSpread 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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position

Returns

NameTypeDescription
<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

NameTypeDescription
collateraladdressThe address of the collateral token
collateralAmountuint256The amount of collateral to calculate the cost for

Returns

NameTypeDescription
costuint256The cost of the collateral
collateralDecimalsuint8The 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

NameTypeDescription
tokenIduint256The ID of the mortgage NFT
baseRequestBaseRequestThe base request for the mortgage
collateraladdressThe address of the collateral token
subConsoladdressThe address of the subConsol contract
hasPaymentPlanboolWhether the mortgage has a payment plan

Returns

NameTypeDescription
mortgageParamsMortgageParamsThe mortgage parameters
orderAmountsOrderAmountsThe order amounts
borrowAmountsuint256[]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

NameTypeDescription
borrowAmountsuint256[]The amounts being borrowed from each origination pool
mortgageParamsMortgageParamsThe mortgage parameters
orderAmountsOrderAmountsThe order amounts
baseRequestBaseRequestThe base request for the mortgage
conversionQueueListaddress[]The addresses of the conversion queues to use
requiredGasFeeuint256The required gas fee
expansionboolWhether 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

NameTypeDescription
baseRequestBaseRequestThe base request for the mortgage
tokenIduint256The ID of the mortgage NFT
collateraladdressThe address of the collateral token
subConsoladdressThe address of the subConsol contract
conversionQueueListaddress[]The addresses of the conversion queues to use
requiredGasFeeuint256The required gas fee
hasPaymentPlanboolWhether the mortgage has a payment plan
expansionboolWhether 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

NameTypeDescription
creationRequestCreationRequestThe parameters of the mortgage creation being requested

Returns

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
expansionRequestExpansionRequestThe parameters of the balance sheet expansion being requested

burnMortgageNFT

Burns a mortgage NFT

function burnMortgageNFT(uint256 tokenId) external onlyRole(Roles.NFT_ROLE);

Parameters

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
originationParametersOriginationParametersThe 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

NameTypeDescription
<none>uint256
returnAmountuint256The amount of consol to return to the origination pool
databytesAny 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

NameTypeDescription
tokenIduint256The ID of the mortgage NFT
conversionQueueListaddress[]The list of conversion queues
hintPrevIdsuint256[]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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
conversionQueueListaddress[]The list of conversion queues to use
hintPrevIdsuint256[]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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
amountuint256The amount of the principal being coverted
collateralAmountuint256The amount of the collateral being withdrawn during the conversion
receiveraddressThe address receiving the converted collateral

setPaused

Pause or unpause the contract

function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);

Parameters

NameTypeDescription
pauseboolThe new paused state

paused

Get the paused state of the contract

function paused() public view override returns (bool);

Returns

NameTypeDescription
<none>boolThe 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

NameTypeDescription
_usdxaddressAddress of the USDX token contract
_consoladdressAddress of the Consol token contract
_penaltyRateuint16Late payment penalty rate in basis points (BPS)
_refinanceRateuint16Refinancing fee rate in basis points (BPS)
_conversionPremiumRateuint16Conversion premium rate in basis points (BPS)
_priceSpreaduint16Price spread in basis points (BPS)
_insuranceFundaddressAddress of the insurance fund
_interestRateOracleaddressAddress of the interest rate oracle contract
_originationPoolScheduleraddressAddress of the origination pool scheduler contract
_loanManageraddressAddress of the loan manager contract
_orderPooladdressAddress of the order pool contract
_supportedMortgagePeriodTermsmapping(address => mapping(uint8 => bool))Mapping of collateral address to period term to supported status
_priceOraclesmapping(address => address)Mapping of collateral address to price oracle address
_minimumCapsmapping(address => uint256)Mapping of collateral address to minimum cap
_maximumCapsmapping(address => uint256)Mapping of collateral address to maximum cap
_conversionQueuesmapping(uint256 => address[])Mapping of collateral address to conversion queues
_mortgageEnqueuedmapping(uint256 => mapping(address => bool))Mapping of tokenId to conversion queue to enqueued status
_pausedboolWhether the contract is paused

LenderQueue

Git Source

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

NameTypeDescription
asset_addressThe address of the asset to withdraw
consol_addressThe address of the Consol contract
admin_addressThe 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

NameTypeDescription
gasFeeuint256The 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

NameTypeDescription
amountuint256The 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

NameTypeDescription
newMinimumWithdrawalAmountuint256The 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

NameTypeDescription
amountuint256The 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

NameTypeDescription
indexuint256The index of the withdrawal request

Returns

NameTypeDescription
<none>WithdrawalRequestwithdrawalRequest 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

NameTypeDescription
iterationsuint256The number of iterations to process. Each iteration returns collected gas fees.
receiveraddressThe 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

NameTypeDescription
indexuint256The index of the withdrawal request to cancel

setPaused

Pause or unpause the contract

function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);

Parameters

NameTypeDescription
pauseboolThe new paused state

LoanManager

Git Source

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

NameTypeDescription
nftNamestringThe name of the NFT
nftSymbolstringThe symbol of the NFT
_nftMetadataGeneratoraddressThe address of the NFT metadata generator
_consoladdressThe address of the Consol contract
_generalManageraddressThe 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

NameTypeDescription
mortgagePositionMortgagePositionThe mortgage position to calculate the missed payments and penalty amount for

Returns

NameTypeDescription
outputMortgagePositionMortgagePositionThe updated mortgage position
penaltyAmountuint256The penalty amount
additionalPaymentsMisseduint8The 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

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
tokenIduint256The ID of the mortgage position

onlyMortgageOwner

Modifier to check if the caller is the owner of the mortgage

modifier onlyMortgageOwner(uint256 tokenId) ;

Parameters

NameTypeDescription
tokenIduint256The ID of the mortgage position

_validateMortgageExistsAndActive

Validates that the mortgage position exists and is active

function _validateMortgageExistsAndActive(uint256 tokenId) internal view;

Parameters

NameTypeDescription
tokenIduint256The ID of the mortgage position

mortgageExistsAndActive

Modifier to check if the mortgage position exists and is active

modifier mortgageExistsAndActive(uint256 tokenId) ;

Parameters

NameTypeDescription
tokenIduint256The ID of the mortgage position

_withdrawSubConsol

Withdraws the SubConsol from the Consol contract

function _withdrawSubConsol(address subConsol, uint256 amount) internal;

Parameters

NameTypeDescription
subConsoladdressThe address of the subConsol contract
amountuint256The 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

NameTypeDescription
subConsoladdressThe address of the subConsol contract
receiveraddressThe address of the receiver
collateralAmountuint256The amount of collateral to withdraw
amountuint256The amount of SubConsol to burn
asyncboolWhether to withdraw the collateral asynchronously

_consolTransferFrom

Transfers Consol from one address to another

function _consolTransferFrom(address from, address to, uint256 amount) internal;

Parameters

NameTypeDescription
fromaddressThe address of the sender
toaddressThe address of the recipient
amountuint256The 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

NameTypeDescription
collateraladdressThe address of the collateral
subConsoladdressThe address of the subConsol
collateralAmountuint256The amount of collateral to deposit
amountuint256The 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

NameTypeDescription
amountBorroweduint256The 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

NameTypeDescription
mortgageParamsMortgageParamsThe 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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position

Returns

NameTypeDescription
outputMortgagePositionMortgagePositionThe mortgage position

imposePenalty

Imposes applicable penalties to a mortgage position

function imposePenalty(uint256 tokenId)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId);

Parameters

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
amountuint256The amount to pay

penaltyPay

Pays the penalty for a mortgage position

function penaltyPay(uint256 tokenId, uint256 amount)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId);

Parameters

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
amountuint256The amount to pay

redeemMortgage

Redeems a mortgage position

function redeemMortgage(uint256 tokenId, bool async)
external
override
mortgageExistsAndActive(tokenId)
imposePenaltyBefore(tokenId)
onlyMortgageOwner(tokenId);

Parameters

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
asyncboolWhether 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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
totalPeriodsuint8The 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

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
inputTokenaddressThe address of the input token
outputTokenaddressThe address of the output token
amountuint256The amount of tokens to swap
databytesThe 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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
currentPriceuint256The current price of the collateral
amountuint256The amount of the principal being coverted
collateralAmountuint256The amount of the collateral being withdrawn during the conversion
receiveraddressThe 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

NameTypeDescription
tokenIduint256The tokenId of the mortgage position
amountInuint256The amount of the principal being added to the mortgage position
collateralAmountInuint256The amount of collateral being added to the mortgage position
newInterestRateuint16The new interest rate of the mortgage position

MortgageNFT

Git Source

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

NameTypeDescription
namestringThe name of the NFT
symbolstringThe symbol of the NFT
generalManager_addressThe address of the general manager
nftMetadataGenerator_addressThe address of the NFT metadata generator

mortgageIdNotTaken

Modifier to check if the mortgage ID is already taken

modifier mortgageIdNotTaken(string memory mortgageId) ;

Parameters

NameTypeDescription
mortgageIdstringThe 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

NameTypeDescription
toaddressThe address to mint the NFT to
mortgageIdstringThe ID of the mortgage

Returns

NameTypeDescription
tokenIduint256The ID of the minted NFT

burn

Burns a mortgage NFT. Only the general manager can burn NFTs.

function burn(uint256 tokenId) external onlyGeneralManager;

Parameters

NameTypeDescription
tokenIduint256The 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

NameTypeDescription
mortgageIdstringThe ID of the mortgage

Returns

NameTypeDescription
owneraddressThe owner of the mortgage position

tokenURI

function tokenURI(uint256 tokenId) public view override returns (string memory);

MortgageQueue

Git Source

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

NameTypeDescription
tokenIduint256The tokenId of the MortgagePosition to get the node for.

Returns

NameTypeDescription
mortgageNodeMortgageNodeThe 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

NameTypeDescription
mortgageGasFee_uint256The 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

NameTypeDescription
tokenIduint256The tokenId of the MortgagePosition to insert.
triggerPriceuint256The trigger price of the MortgagePosition to insert.
hintPrevIduint256The 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

NameTypeDescription
tokenIduint256The tokenId of the MortgagePosition to remove.

Returns

NameTypeDescription
gasFeeuint256The 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

NameTypeDescription
tokenIduint256The tokenId of the node to pop.

Returns

NameTypeDescription
nextIduint256The tokenId of the next node in the queue.
gasFeeuint256The 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

NameTypeDescription
triggerPriceuint256The trigger price to find the first MortgagePosition for.

Returns

NameTypeDescription
tokenIduint256The tokenId of the first MortgagePosition in the Conversion Queue that has a trigger price less than or equal to the input trigger price.

MultiTokenVault

Git Source

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

NameTypeDescription
name_stringThe name of the MultiTokenVault
symbol_stringThe symbol of the MultiTokenVault
decimalsOffset_uint8The decimals offset
admin_addressThe admin address

enforceCaps

Enforces the maximum cap for a token

modifier enforceCaps(address token) ;

Parameters

NameTypeDescription
tokenaddressThe 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

NameTypeDescription
tokenaddressThe 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

NameTypeDescription
tokenaddressThe address of the token to remove

getSupportedTokens

Get the list of supported tokens

function getSupportedTokens() external view override returns (address[] memory);

Returns

NameTypeDescription
<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

NameTypeDescription
tokenaddressThe address of the token to check

Returns

NameTypeDescription
isSupportedboolTrue 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

NameTypeDescription
tokenaddressThe address of the token to set the cap for
_maximumCapuint256The 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

NameTypeDescription
<none>address
amountuint256The amount of tokens to deposit/withdraw

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>address
amountuint256The amount of tokens minted/burned as a result of the deposit/withdraw operation

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
tokenaddressThe address of the token to deposit
amountuint256The 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

NameTypeDescription
tokenaddressThe address of the token to withdraw
amountuint256The 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

NameTypeDescription
amountuint256The 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

NameTypeDescription
sharesuint256The amount of shares to burn
amountuint256The 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

NameTypeDescription
totalSupplyuint256The total supply of the MultiTokenVault

OrderPool

Git Source

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

NameTypeDescription
nativeWrapper_addressThe address of the native wrapper contract
generalManager_addressThe address of the GeneralManager
admin_addressThe 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

NameTypeDescription
gasFee_uint256The 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

NameTypeDescription
maximumOrderDuration_uint256The 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

NameTypeDescription
indexuint256The index of the purchase order

Returns

NameTypeDescription
<none>PurchaseOrderThe 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

NameTypeDescription
conversionQueuesaddress[]The list of conversion queues to calculate the mortgage gas fee for

Returns

NameTypeDescription
mortgageGasFeeuint256The 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

NameTypeDescription
originationPoolsaddress[]The addresses of the origination pools to deploy funds from
borrowAmountsuint256[]The amounts being borrowed from each origination pool
conversionQueuesaddress[]The addresses of the conversion queues to use
orderAmountsOrderAmountsThe amounts being collected from the borrower
mortgageParamsMortgageParamsThe parameters for the mortgage being created
expirationuint256The expiration timestamp of the order
expansionboolWhether the mortgage is a balance sheet expansion of an existing position

Returns

NameTypeDescription
indexuint256The 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

NameTypeDescription
receiveraddressThe address to send the assets to
orderPurchaseOrderThe order being processed

_processOrder

Processes an order at a given internal index

function _processOrder(uint256 index, uint256[] memory hintPrevIds) internal returns (uint256 collectedGasFee);

Parameters

NameTypeDescription
indexuint256The index of the order
hintPrevIdsuint256[]List of hints for identifying the previous mortgage position in the respective conversion queue.

Returns

NameTypeDescription
collectedGasFeeuint256The 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

NameTypeDescription
indicesuint256[]The indices of the purchase orders to process
hintPrevIdsListuint256[][]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

Git Source

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

NameTypeDescription
namePrefixstringThe prefix for the name of the pool
symbolPrefixstringThe prefix for the symbol of the pool
epochuint256The epoch of the pool
consol_addressThe address of the consol contract
usdx_addressThe address of the USDX token
deployPhaseTimestamp_uint256The timestamp of the deploy phase
redemptionPhaseTimestamp_uint256The timestamp of the redemption phase
poolLimit_uint256The pool limit
poolMultiplierBps_uint16The 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

NameTypeDescription
phaseOriginationPoolPhaseThe 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

NameTypeDescription
pauseboolThe new paused state

currentPhase

Fetches the current phase of the Origination Pool

function currentPhase() public view override returns (OriginationPoolPhase);

Returns

NameTypeDescription
<none>OriginationPoolPhaseThe 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

NameTypeDescription
amountuint256The amount of USDX to calculate the return amount for

Returns

NameTypeDescription
returnAmountuint256The return amount of Consol

deposit

Deposit USDX into the pool

function deposit(uint256 amount)
external
override
whenNotPaused
onlyPhase(OriginationPoolPhase.DEPOSIT)
returns (uint256);

Parameters

NameTypeDescription
amountuint256The amount of USDX to deposit

Returns

NameTypeDescription
<none>uint256mintAmount 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

NameTypeDescription
amountuint256The amount of USDX to deploy
databytesThe 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

NameTypeDescription
amountuint256The amount of receipt tokens to burn in exchange for USDX + Consol

OriginationPoolScheduler

Git Source

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

NameTypeDescription
$OriginationPoolSchedulerStorageThe 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

NameTypeDescription
generalManager_addressThe address of the general manager
oPoolAdmin_addressThe address of the oPool admin

__OriginationPoolScheduler_init_unchained

Initializes the OriginationPoolScheduler contract only

function __OriginationPoolScheduler_init_unchained(address generalManager_, address oPoolAdmin_)
internal
onlyInitializing;

Parameters

NameTypeDescription
generalManager_addressThe address of the general manager
oPoolAdmin_addressThe address of the oPool admin

initialize

Initializes the OriginationPoolScheduler contract

function initialize(address generalManager_, address oPoolAdmin_) external initializer;

Parameters

NameTypeDescription
generalManager_addressThe address of the general manager
oPoolAdmin_addressThe 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

NameTypeDescription
newImplementationaddressThe address of the new implementation

_getRawEpoch

Gets the raw internal epoch needed for calculating timestamps

function _getRawEpoch() internal view returns (uint256);

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
newGeneralManageraddressThe address of the new general manager

generalManager

Get the general manager address

function generalManager() public view override returns (address);

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
newOpoolAdminaddressThe 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

NameTypeDescription
<none>addressThe address of the origination pool admin

configLength

Get the number of origination pool configs

function configLength() public view override returns (uint256);

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
indexuint256The index of the origination pool config to get the ID for

Returns

NameTypeDescription
oPoolConfigIdOPoolConfigIdThe 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

NameTypeDescription
indexuint256The index of the origination pool config to get

Returns

NameTypeDescription
<none>OriginationPoolConfigconfig 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

NameTypeDescription
indexuint256The index of the origination pool config to get the last deployment address from

Returns

NameTypeDescription
lastDeploymentRecordLastDeploymentRecordThe 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

NameTypeDescription
oPoolConfigIdOPoolConfigIdThe ID of the origination pool config to get the last deployment address from

Returns

NameTypeDescription
lastDeploymentRecordLastDeploymentRecordThe last deployment record

addConfig

Add a new origination pool config

function addConfig(OriginationPoolConfig memory config) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
configOriginationPoolConfigThe origination pool config to add

removeConfig

Remove an origination pool config

function removeConfig(OriginationPoolConfig memory config) external override onlyRole(Roles.DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
configOriginationPoolConfigThe origination pool config to remove

currentEpoch

Get the current epoch. Indexed from 1

function currentEpoch() public view override returns (uint256);

Returns

NameTypeDescription
<none>uint256currentEpoch The current epoch

_updateRegistration

Updates the registration of an origination pool

function _updateRegistration(address originationPool, bool registered) internal;

Parameters

NameTypeDescription
originationPooladdressThe address of the origination pool
registeredboolWhether 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

NameTypeDescription
configOriginationPoolConfigThe config for the origination pool
lastDeploymentRecordLastDeploymentRecordThe last deployment record for the origination pool
currEpochuint256The current epoch

Returns

NameTypeDescription
bytecodebytesThe 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

NameTypeDescription
configOriginationPoolConfigThe config for the origination pool
lastDeploymentRecordLastDeploymentRecordThe last deployment record for the origination pool
_generalManageraddressThe address of the general manager
_oPoolAdminaddressThe address of the oPool admin
currEpochuint256The current epoch

Returns

NameTypeDescription
originationPooladdressThe 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

NameTypeDescription
lastDeploymentRecordLastDeploymentRecordThe last deployment record for the origination pool
defaultPoolLimituint256The default pool limit
poolLimitGrowthRateBpsuint16The pool limit growth rate in basis points
currEpochuint256The current epoch

Returns

NameTypeDescription
poolLimituint256The pool limit

deployOriginationPool

Deploy a new origination pool

function deployOriginationPool(OPoolConfigId oPoolConfigId)
external
whenNotPaused
returns (address deploymentAddress);

Parameters

NameTypeDescription
oPoolConfigIdOPoolConfigIdThe ID of the origination pool config to deploy

Returns

NameTypeDescription
deploymentAddressaddressThe 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

NameTypeDescription
oPoolConfigIdOPoolConfigIdThe ID of the origination pool config to predict the address for

Returns

NameTypeDescription
deploymentAddressaddressThe 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

NameTypeDescription
originationPooladdressThe address of the origination pool to check

Returns

NameTypeDescription
registeredboolWhether 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

NameTypeDescription
originationPooladdressThe address of the origination pool to update the registration for
registeredboolWhether the origination pool is registered

setPaused

Pause or unpause the contract

function setPaused(bool pause) external override onlyRole(Roles.PAUSE_ROLE);

Parameters

NameTypeDescription
pauseboolThe new paused state

paused

Get the paused state of the contract

function paused() public view override returns (bool);

Returns

NameTypeDescription
<none>boolThe 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

NameTypeDescription
_generalManageraddressThe address of the general manager
_oPoolAdminaddressThe address of the oPool admin
_epochCountStartuint256The epoch count start (helps start that count from 0 for the current epoch)
_oPoolConfigIdsOPoolConfigId[]Array of supported oPool config ids
_oPoolConfigIndexesmapping(OPoolConfigId => uint256)Mapping of ids to their index in the _oPoolConfigIds array
_oPoolConfigsmapping(OPoolConfigId => OriginationPoolConfig)Mapping of ids to the oPool configs
_oPoolLastDeploymentRecordsmapping(OPoolConfigId => LastDeploymentRecord)Mapping of ids to the last deployed origination pool with that config
_oPoolRegistrymapping(address => bool)Mapping of origination pool addresses to a boolean indicating if they are registered
_pausedboolWhether the contract is paused

PythInterestRateOracle

Git Source

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

NameTypeDescription
pyth_addressThe 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

NameTypeDescription
totalPeriodsuint8The total number of periods for the mortgage
hasPaymentPlanboolWhether the mortgage has a payment plan

Returns

NameTypeDescription
rateuint16The 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

NameTypeDescription
ageuint256The age of the price
maxAgeuint256The 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

NameTypeDescription
confidenceuint256The confidence of the price
maxConfidenceuint256The maximum confidence

InvalidTotalPeriods

The error thrown when the total periods are invalid and not supported by the InterestRateOracle

error InvalidTotalPeriods(uint8 totalPeriods);

Parameters

NameTypeDescription
totalPeriodsuint8The total periods

PythPriceOracle

Git Source

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

NameTypeDescription
pyth_addressThe address of the Pyth contract
priceId_bytes32The Pyth price ID
maxConfidence_uint256The maximum confidence
collateralDecimals_uint8The number of decimals for the collateral

price

Returns the price of the collateral in USDX

function price() public view override returns (uint256 assetPrice);

Returns

NameTypeDescription
assetPriceuint256The 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

NameTypeDescription
collateralAmountuint256The amount of collateral to calculate the cost of

Returns

NameTypeDescription
totalCostuint256The cost of the collateral in USDX (18 decimals)
_collateralDecimalsuint8The 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

NameTypeDescription
ageuint256The age of the price
maxAgeuint256The 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

NameTypeDescription
confidenceuint256The confidence of the price
maxConfidenceuint256The maximum confidence

QueueProcessor

Git Source

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

NameTypeDescription
queueaddress
iterationsuint256The 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

NameTypeDescription
<none>address

Returns

NameTypeDescription
blockeraddressAnother source that is blocking the source
blockedboolWhether the source is blocked by another source

RebasingERC20

Git Source

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

NameTypeDescription
name_stringThe name of the token
symbol_stringThe symbol of the token
decimalsOffset_uint8The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
sharesuint256The amount of shares

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
assetsuint256The amount of underlying token

Returns

NameTypeDescription
<none>uint256The 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

Git Source

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

NameTypeDescription
baseRate_uint16The 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

NameTypeDescription
totalPeriodsuint8The total number of periods for the mortgage
hasPaymentPlanboolWhether the mortgage has a payment plan

Returns

NameTypeDescription
rateuint16The interest rate

Errors

InvalidTotalPeriods

The error thrown when the total periods are invalid and not supported by the InterestRateOracle

error InvalidTotalPeriods(uint8 totalPeriods);

Parameters

NameTypeDescription
totalPeriodsuint8The total periods

SubConsol

Git Source

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

NameTypeDescription
name_stringThe name of the token
symbol_stringThe symbol of the token
admin_addressThe address of the admin
collateral_addressThe 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

NameTypeDescription
yieldStrategy_addressThe 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

NameTypeDescription
collateralAmountuint256The amount of collateral to deposit
mintAmountuint256The 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

NameTypeDescription
toaddressThe address to send the collateral to
collateralAmountuint256The amount of collateral to withdraw
burnAmountuint256The 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

NameTypeDescription
toaddressThe address to send the collateral to
collateralAmountuint256The amount of collateral to withdraw
burnAmountuint256The 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

NameTypeDescription
toaddressThe address to send the collateral to
collateralAmountuint256The amount of collateral to withdraw
burnAmountuint256The amount of SubConsol to burn

depositToYieldStrategy

Deposit collateral into the yield strategy

function depositToYieldStrategy(uint256 collateralAmount) external override onlyRole(Roles.PORTFOLIO_ROLE);

Parameters

NameTypeDescription
collateralAmountuint256The amount of collateral to deposit

withdrawFromYieldStrategy

Withdraw collateral from the yield strategy

function withdrawFromYieldStrategy(uint256 collateralAmount) external override onlyRole(Roles.PORTFOLIO_ROLE);

Parameters

NameTypeDescription
collateralAmountuint256The amount of collateral to withdraw

USDX

Git Source

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

NameTypeDescription
name_stringThe name of the token
symbol_stringThe symbol of the token
decimalsOffset_uint8The number of decimals to pad the internal shares with to avoid precision loss
admin_addressThe 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

NameTypeDescription
tokenaddressThe 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

NameTypeDescription
tokenaddressThe address of the token to add
scalarNumeratoruint256The scalar numerator for the token
scalarDenominatoruint256The 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

NameTypeDescription
tokenaddressThe 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

NameTypeDescription
tokenaddressThe address of the token to deposit/withdraw
amountuint256The amount of tokens to deposit/withdraw

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
tokenaddressThe address of the token to deposit/withdraw
amountuint256The amount of tokens minted/burned as a result of the deposit/withdraw operation

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
totalSupplyuint256The 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

NameTypeDescription
amountuint256The amount of USDX to burn

UsdxQueue

Git Source

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

NameTypeDescription
asset_addressThe address of the asset
consol_addressThe address of the Consol contract
admin_addressThe 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

Git Source

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

NameTypeDescription
$FulfillmentVaultStorageThe 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

NameTypeDescription
namestringThe name of the fulfillment vault
symbolstringThe symbol of the fulfillment vault
_decimalsuint8The decimals of the fulfillment vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_wrappedNativeTokenaddressThe address of the wrapped native token
_generalManageraddressThe address of the general manager

__FulfillmentVault_init_unchained

Initializes the FulfillmentVault contract only

function __FulfillmentVault_init_unchained(address _wrappedNativeToken, address _generalManager)
internal
onlyInitializing;

Parameters

NameTypeDescription
_wrappedNativeTokenaddressThe address of the wrapped native token
_generalManageraddressThe 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

NameTypeDescription
namestringThe name of the fulfillment vault
symbolstringThe symbol of the fulfillment vault
_decimalsuint8The decimals of the fulfillment vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_wrappedNativeTokenaddressThe address of the wrapped native token
_generalManageraddressThe address of the general manager
adminaddressThe 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

NameTypeDescription
<none>uint256The total assets of the vault

wrappedNativeToken

Gets the address of the wrapped native token

function wrappedNativeToken() public view override returns (address);

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<none>addressThe address of the general manager

orderPool

Gets the address of the order pool

function orderPool() public view override returns (address);

Returns

NameTypeDescription
<none>addressThe address of the order pool

usdx

Gets the address of the USDX token

function usdx() public view override returns (address);

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<none>uint128The 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

NameTypeDescription
assetaddressThe 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

NameTypeDescription
assetIndexuint64The index of the asset to bridge
amountuint256The 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

NameTypeDescription
amountuint256The amount of USDX to burn

withdrawUsdTokenFromUsdx

Withdraws usdToken from usdx

function withdrawUsdTokenFromUsdx(address usdToken, uint256 amount)
external
override
onlyRole(KEEPER_ROLE)
whenPaused;

Parameters

NameTypeDescription
usdTokenaddressThe address of the usdToken to withdraw
amountuint256The amount of usdToken to withdraw

depositUsdTokenToUsdx

Deposits usdToken into usdx

function depositUsdTokenToUsdx(address usdToken, uint256 amount) external override onlyRole(KEEPER_ROLE) whenPaused;

Parameters

NameTypeDescription
usdTokenaddressThe address of the usdToken to deposit
amountuint256The 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

NameTypeDescription
assetaddressThe address of the asset to bridge
amountuint256The 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

NameTypeDescription
spotIduint32The spotId of the asset to trade (identifies the trading pair)
isBuyboolWhether to buy or sell
limitPxuint64The limit price. Note, This is is (weiUnits - szUnits). For USDT0 and USDC, weiUnits is 1e6.
szuint64The 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

NameTypeDescription
indexuint256The index of the order to fill
hintPrevIdsuint256[]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

NameTypeDescription
_wrappedNativeTokenaddressThe address of the wrapped native token
_generalManageraddressThe address of the general manager
_usdxaddressThe address of the USDX token
_nonceuint128The ongoing nonce that generates distinct cloid values for exchanges on core

LiquidityVault

Git Source

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

NameTypeDescription
$LiquidityVaultStorageThe 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

NameTypeDescription
namestringThe name of the liquidity vault
symbolstringThe symbol of the liquidity vault
_decimalsuint8The decimals of the liquidity vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_depositableAssetsaddress[]The addresses of the depositable assets
_redeemableAssetsaddress[]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

NameTypeDescription
_decimalsuint8The decimals of the liquidity vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_depositableAssetsaddress[]The addresses of the depositable assets
_redeemableAssetsaddress[]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

NameTypeDescription
namestringThe name of the liquidity vault
symbolstringThe symbol of the liquidity vault
_decimalsuint8The decimals of the liquidity vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_depositableAssetsaddress[]The addresses of the depositable assets
_redeemableAssetsaddress[]The addresses of the redeemable assets
adminaddressThe 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

NameTypeDescription
<none>boolWhether the whitelist is enforced.

setWhitelistEnforced

Enforces the whitelist.

function setWhitelistEnforced(bool enforced) external virtual override onlyRole(DEFAULT_ADMIN_ROLE);

Parameters

NameTypeDescription
enforcedboolWhether 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

NameTypeDescription
<none>uint8The decimals offset

depositableAssets

The address of the depositable asset.

function depositableAssets() public view virtual override returns (address[] memory);

Returns

NameTypeDescription
<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

NameTypeDescription
<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

NameTypeDescription
assetaddressThe address of the asset to update
isRedeemableboolWhether the asset is redeemable
addboolWhether to add the asset or remove the asset

_totalAssets

Calculates the total assets of the vault

function _totalAssets() internal view virtual returns (uint256);

Returns

NameTypeDescription
<none>uint256The total assets of the vault

totalAssets

The total assets of the vault

function totalAssets() public view virtual override returns (uint256);

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
assetsuint256The amount of assets to convert to shares
roundingMath.RoundingThe rounding direction

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
sharesuint256The amount of shares to convert to assets
roundingMath.RoundingThe rounding direction

Returns

NameTypeDescription
<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

NameTypeDescription
pausedboolThe 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

NameTypeDescription
depositableAssetaddressThe address of the depositable asset to deposit.
assetsuint256The 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

NameTypeDescription
sharesuint256The 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

NameTypeDescription
_decimalsuint8The decimals of the vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_depositableAssetsaddress[]The addresses of the depositable assets
_depositableAssetIndexmapping(address => uint256)The index of the depositable assets (one-indexed)
_redeemableAssetsaddress[]The addresses of the redeemable assets
_redeemableAssetIndexmapping(address => uint256)The index of the redeemable assets (one-indexed)
_whitelistEnforcedboolWhether the whitelist is enforced

RolloverVault

Git Source

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

NameTypeDescription
$RolloverVaultStorageThe 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

NameTypeDescription
namestringThe name of the rollover vault
symbolstringThe symbol of the rollover vault
_decimalsuint8The decimals of the rollover vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_generalManageraddressThe address of the general manager

__RolloverVault_init_unchained

Initializes the RolloverVault contract only

function __RolloverVault_init_unchained(address _generalManager) internal onlyInitializing;

Parameters

NameTypeDescription
_generalManageraddressThe 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

NameTypeDescription
namestringThe name of the rollover vault
symbolstringThe symbol of the rollover vault
_decimalsuint8The decimals of the rollover vault
_decimalsOffsetuint8The decimals offset for measuring internal precision of shares
_generalManageraddressThe address of the general manager
adminaddressThe 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

NameTypeDescription
<none>uint256The total assets of the vault

usdx

Gets the address of the USDX token

function usdx() public view override returns (address);

Returns

NameTypeDescription
<none>addressThe address of the USDX token

consol

Gets the address of the consol token

function consol() public view override returns (address);

Returns

NameTypeDescription
<none>addressThe address of the consol token

generalManager

Gets the address of the general manager

function generalManager() public view override returns (address);

Returns

NameTypeDescription
<none>addressThe address of the general manager

originationPoolScheduler

Gets the address of the origination pool scheduler

function originationPoolScheduler() public view returns (address);

Returns

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<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

NameTypeDescription
originationPooladdressThe address of the origination pool to check if it is being tracked

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
originationPooladdressThe address of the origination pool to deposit into
amountuint256The 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

NameTypeDescription
originationPooladdressThe 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

NameTypeDescription
_usdxaddressThe address of the USDX token
_consoladdressThe address of the consol token
_generalManageraddressThe address of the general manager
_originationPoolsaddress[]The addresses of the origination pools the rollover vault currently has a balance in
_poolIndexmapping(address => uint256)Mapping of origination pool addresses to their index in the _originationPools array (offset by 1)

Router

Git Source

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

NameTypeDescription
_wrappedNativeTokenaddressThe address of the wrapped native token (i.e., whype: 0x555...)
_generalManageraddressThe address of the general manager contract
_rolloverVaultaddressThe address of the rollover vault contract
_fulfillmentVaultaddressThe address of the fulfillment vault contract
_pythaddressThe 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

NameTypeDescription
usdTokenaddressThe address of the usdToken to pull in
usdxAmountuint256The 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

NameTypeDescription
inputTokenaddressThe address of the input token to pull in
consolAmountuint256The amount of Consol to pull in

_pullCollateral

Internal function to pull in collateral

function _pullCollateral(address collateral, uint256 collateralCollected, bool isNative) internal;

Parameters

NameTypeDescription
collateraladdressThe address of the collateral token to pull in
collateralCollecteduint256The amount of collateral to pull in
isNativeboolWhether 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

NameTypeDescription
collateraladdressThe address of the collateral token
collateralAmountuint256The amount of collateral to calculate the cost for

Returns

NameTypeDescription
costuint256The cost of the collateral amount (including the price spread)
collateralDecimalsuint8The 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

NameTypeDescription
creationRequestCreationRequestThe creation request

Returns

NameTypeDescription
collateralCollecteduint256The amount of collateral that will be collected from the borrower
usdxCollecteduint256The amount of USDX that will be collected from the borrower
paymentAmountuint256The amount of USDX that will be paid to the fulfilller
collateralDecimalsuint8The 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

NameTypeDescription
priceUpdatesbytes[]The price updates to send to the Pyth contract
usdTokenaddressThe address of the usdToken to pull in
creationRequestCreationRequestThe creation request
isNativeboolWhether the collateral is the native token or not (i.e., whype: 0x555...)
maxCollecteduint256The maximum amount that can be collected from the borrower (in USDX if non-compounding, in collateral if compounding)

Returns

NameTypeDescription
collateralCollecteduint256The amount of collateral collected
usdxCollecteduint256The amount of USDX collected
paymentAmountuint256The amount of payment to be made
collateralDecimalsuint8The 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

NameTypeDescription
usdTokenaddressThe address of the usdToken to pull in
creationRequestCreationRequestThe creation request
isNativeboolWhether the collateral is the native token or not (i.e., whype: 0x555...)
maxCollecteduint256The maximum amount that can be collected from the borrower (in USDX if non-compounding, in collateral if compounding)

Returns

NameTypeDescription
collateralCollecteduint256The amount of collateral collected
usdxCollecteduint256The amount of USDX collected
paymentAmountuint256The amount of payment to be made
collateralDecimalsuint8The decimals of the collateral

periodPay

Make a periodic payment on a mortgage

function periodPay(address inputToken, uint256 tokenId, uint256 inputAmount) external;

Parameters

NameTypeDescription
inputTokenaddressThe address of the input token to pull in
tokenIduint256The token ID
inputAmountuint256The 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

NameTypeDescription
inputTokenaddressThe address of the input token to pull in
tokenIduint256The token ID
inputAmountuint256The amount of input token to pull in

refinance

Refinance a mortgage

function refinance(address inputToken, uint256 tokenId, uint8 newTotalPeriods) external;

Parameters

NameTypeDescription
inputTokenaddressThe address of the input token to pull in
tokenIduint256The token ID of the mortgage to refinance
newTotalPeriodsuint8The 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

NameTypeDescription
oPoolConfigIdOPoolConfigIdThe OPoolConfigId of the origination pool config

Returns

NameTypeDescription
originationPoolIOriginationPoolThe origination pool

originationPoolDeposit

Deposit into an origination pool

function originationPoolDeposit(OPoolConfigId oPoolConfigId, address usdToken, uint256 usdTokenAmount) external;

Parameters

NameTypeDescription
oPoolConfigIdOPoolConfigIdThe OPoolConfigId of the origination pool to deposit into
usdTokenaddressThe address of the usdToken to pull in
usdTokenAmountuint256The 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

NameTypeDescription
inputTokenaddressThe address of the input token
outputTokenaddressThe address of the output token
inputAmountuint256The amount of input token to convert

Returns

NameTypeDescription
outputAmountuint256The amount of output token received

wrap

Wraps tokens from usdToken -> usdx -> consol

function wrap(address inputToken, address outputToken, uint256 inputAmount) public;

Parameters

NameTypeDescription
inputTokenaddressThe address of the input token
outputTokenaddressThe address of the output token
inputAmountuint256The 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

NameTypeDescription
vaultaddressThe address of the liquidity vault to deposit into
usdTokenaddressThe address of the usdToken to pull in
usdTokenAmountuint256The amount of usdToken to pull in

rolloverVaultDeposit

Deposit into the rollover vault

function rolloverVaultDeposit(address usdToken, uint256 usdTokenAmount) external;

Parameters

NameTypeDescription
usdTokenaddressThe address of the usdToken to pull in
usdTokenAmountuint256The amount of usdToken to pull in

fulfillmentVaultDeposit

Deposit into the fulfillment vault

function fulfillmentVaultDeposit(address usdToken, uint256 usdTokenAmount) external;

Parameters

NameTypeDescription
usdTokenaddressThe address of the usdToken to pull in
usdTokenAmountuint256The amount of usdToken to pull in