# TermAuction.sol

## TermAuction

This contract calculates a clearing price in a blind double auction and manages auction clearing and settlement

*This contract belongs to the Term Auction group of contracts and is specific to a Term Repo deployment*

### ClearingPriceState

```solidity
struct ClearingPriceState {
  uint256 offerPrice;
  uint256 offerIndex;
  uint256 bidIndex;
  uint256 cumSumOffers;
  uint256 cumSumBids;
  uint256 maxClearingVolume;
  uint256 nextOfferIndex;
  uint256 nextBidIndex;
  uint256 nextCumSumOffers;
  uint256 nextCumSumBids;
  uint256 nextOfferPrice;
  uint256 nextMaxClearingVolume;
  bool minCumSumCorrection;
  uint256 nextBidPrice;
  uint256 clearingPrice;
}
```

### THREESIXTY\_DAYCOUNT\_SECONDS

```solidity
uint256 THREESIXTY_DAYCOUNT_SECONDS
```

### ADMIN\_ROLE

```solidity
bytes32 ADMIN_ROLE
```

### DEVOPS\_ROLE

```solidity
bytes32 DEVOPS_ROLE
```

### INITIALIZER\_ROLE

```solidity
bytes32 INITIALIZER_ROLE
```

### termRepoId

```solidity
bytes32 termRepoId
```

### termAuctionId

```solidity
bytes32 termAuctionId
```

### auctionEndTime

```solidity
uint256 auctionEndTime
```

### dayCountFractionMantissa

```solidity
uint256 dayCountFractionMantissa
```

### termRepoServicer

```solidity
contract ITermRepoServicer termRepoServicer
```

### termAuctionBidLocker

```solidity
contract ITermAuctionBidLocker termAuctionBidLocker
```

### termAuctionOfferLocker

```solidity
contract ITermAuctionOfferLocker termAuctionOfferLocker
```

### purchaseToken

```solidity
contract IERC20MetadataUpgradeable purchaseToken
```

### emitter

```solidity
contract ITermEventEmitter emitter
```

### clearingPrice

```solidity
uint256 clearingPrice
```

### clearingPricePostProcessingOffset

```solidity
uint256 clearingPricePostProcessingOffset
```

### auctionCompleted

```solidity
bool auctionCompleted
```

### auctionCancelledForWithdrawal

```solidity
bool auctionCancelledForWithdrawal
```

### completeAuctionPaused

```solidity
bool completeAuctionPaused
```

### termContractPaired

```solidity
bool termContractPaired
```

### onlyWhileAuctionClosed

```solidity
modifier onlyWhileAuctionClosed()
```

This only runs if the auction is closed (after auction end time)

*This uses the block timestamp to determine if the auction is closed*

### whenCompleteAuctionNotPaused

```solidity
modifier whenCompleteAuctionNotPaused()
```

### notTermContractPaired

```solidity
modifier notTermContractPaired()
```

### constructor

```solidity
constructor() public
```

### initialize

```solidity
function initialize(string termRepoId_, string auctionId_, uint256 auctionEndTime_, uint256 termStart_, uint256 redemptionTimestamp_, contract IERC20MetadataUpgradeable purchaseToken_, address termAuctionInitializer_, uint256 clearingPricePostProcessingOffset_) external
```

Initializes the contract

*See: <https://docs.openzeppelin.com/contracts/4.x/upgradeable>*

### pairTermContracts

```solidity
function pairTermContracts(contract ITermEventEmitter emitter_, contract ITermRepoServicer termRepoServicer_, contract ITermAuctionBidLocker termAuctionBidLocker_, contract ITermAuctionOfferLocker termAuctionOfferLocker_, address devopsMultisigAddress_, address adminWallet_, string version_) external
```

### completeAuction

```solidity
function completeAuction(struct CompleteAuctionInput completeAuctionInput) external
```

Calculates an auction's clearing price, assigns bids/offers, and returns unassigned funds

#### Parameters

| Name                 | Type                        | Description                                                                               |
| -------------------- | --------------------------- | ----------------------------------------------------------------------------------------- |
| completeAuctionInput | struct CompleteAuctionInput | A struct containing all revealed and unrevealed bids and offers and expired rollover bids |

### cancelAuction

```solidity
function cancelAuction(struct CompleteAuctionInput completeAuctionInput) public
```

Cancels an auction and returns all funds to bidders and fulfillBiders

#### Parameters

| Name                 | Type                        | Description                                                                               |
| -------------------- | --------------------------- | ----------------------------------------------------------------------------------------- |
| completeAuctionInput | struct CompleteAuctionInput | A struct containing all revealed and unrevealed bids and offers and expired rollover bids |

### cancelAuctionForWithdrawal

```solidity
function cancelAuctionForWithdrawal(address[] rolloverBorrowers, address[] rolloverPairOffTermRepoServicer) public
```

Cancels an auction and sets auctionCancelledForWithdrawal to true to open unlocking tenders

### \_increaseCumSumBids

```solidity
function _increaseCumSumBids(struct TermAuctionRevealedBid[] sortedBids, uint256 startIndex, uint256 previousCumSumBids, uint256 currentPrice) internal pure returns (uint256, uint256)
```

### \_decreaseCumSumBids

```solidity
function _decreaseCumSumBids(struct TermAuctionRevealedBid[] sortedBids, uint256 startIndex, uint256 previousCumSumBids, uint256 currentPrice) internal pure returns (uint256, uint256)
```

### \_minUint256

```solidity
function _minUint256(uint256 a, uint256 b) internal pure returns (uint256)
```

Returns the min of two `uint256` values

#### Parameters

| Name | Type    | Description                 |
| ---- | ------- | --------------------------- |
| a    | uint256 | The first value to compare  |
| b    | uint256 | The second value to compare |

#### Return Values

| Name | Type    | Description               |
| ---- | ------- | ------------------------- |
| \[0] | uint256 | The min of the two values |

### \_calculateClearingPrice

```solidity
function _calculateClearingPrice(struct TermAuctionRevealedBid[] sortedBids, struct TermAuctionRevealedOffer[] sortedOffers, uint256 clearingOffset) internal pure returns (uint256, uint256)
```

Calculates the intersection between bid/offer schedules to arrive at a clearing price

*Imagine a graph with price along the X-axis and cumsum(bid/offerAmount\*price) along the Y-axis. This function finds the point where the supply line crosses the demand line using binary search*

#### Parameters

| Name           | Type                               | Description                                                                                         |
| -------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------- |
| sortedBids     | struct TermAuctionRevealedBid\[]   | A sorted array of bids used to arrive at a demand schedule                                          |
| sortedOffers   | struct TermAuctionRevealedOffer\[] | A sorted array of offers used to arrive at a supply schedule                                        |
| clearingOffset | uint256                            | The offset to apply to the marginal bid and offer indexes when calculating the final clearing price |

#### Return Values

| Name | Type    | Description                                                   |
| ---- | ------- | ------------------------------------------------------------- |
| \[0] | uint256 | clearingPrice The price at which Term Auction will be cleared |
| \[1] | uint256 |                                                               |

### \_findFirstIndexForPrice

```solidity
function _findFirstIndexForPrice(uint256 price, struct TermAuctionRevealedBid[] sortedBids, uint256 startIndex) internal pure returns (uint256 i, uint256 totalAmount)
```

Finds the index of the first bid with a bidPrice of `price` and calculate the cumsum of the bid amounts up to that index

#### Parameters

| Name       | Type                             | Description                       |
| ---------- | -------------------------------- | --------------------------------- |
| price      | uint256                          | The price to search for           |
| sortedBids | struct TermAuctionRevealedBid\[] | An array of sorted bids to search |
| startIndex | uint256                          | The index to start searching from |

#### Return Values

| Name        | Type    | Description                                           |
| ----------- | ------- | ----------------------------------------------------- |
| i           | uint256 | The index of the first bid with a bidPrice of `price` |
| totalAmount | uint256 | The cumsum of the bid amounts up to return index i    |

### \_findLastIndexForPrice

```solidity
function _findLastIndexForPrice(uint256 price, struct TermAuctionRevealedOffer[] sortedOffers, uint256 startIndex) internal pure returns (uint256 i, uint256 totalAmount)
```

Finds the index of the last offer with a offerPrice of `price` and calculate the cumsum of the offer amounts up to that index

#### Parameters

| Name         | Type                               | Description                       |
| ------------ | ---------------------------------- | --------------------------------- |
| price        | uint256                            | The price to search for           |
| sortedOffers | struct TermAuctionRevealedOffer\[] | An array of offers to search      |
| startIndex   | uint256                            | The index to start searching from |

#### Return Values

| Name        | Type    | Description                                              |
| ----------- | ------- | -------------------------------------------------------- |
| i           | uint256 | The index of the last offer with a offerPrice of `price` |
| totalAmount | uint256 | The cumsum of the offer amounts up to return index i     |

### \_fullyAssignBid

```solidity
function _fullyAssignBid(struct TermAuctionRevealedBid bid) internal returns (uint256)
```

Fully assigns a bid

#### Parameters

| Name | Type                          | Description       |
| ---- | ----------------------------- | ----------------- |
| bid  | struct TermAuctionRevealedBid | The bid to assign |

#### Return Values

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| \[0] | uint256 | The amount that was assigned |

### \_fullyAssignOffer

```solidity
function _fullyAssignOffer(struct TermAuctionRevealedOffer offer) internal returns (uint256)
```

Fully assigns an offer

#### Parameters

| Name  | Type                            | Description         |
| ----- | ------------------------------- | ------------------- |
| offer | struct TermAuctionRevealedOffer | The offer to assign |

#### Return Values

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| \[0] | uint256 | The amount that was assigned |

### \_partiallyAssignBid

```solidity
function _partiallyAssignBid(struct TermAuctionRevealedBid bid, uint256 assignedAmount) internal returns (uint256)
```

Partially assigns a bid

#### Parameters

| Name           | Type                          | Description          |
| -------------- | ----------------------------- | -------------------- |
| bid            | struct TermAuctionRevealedBid | The bid to assign    |
| assignedAmount | uint256                       | The amount to assign |

#### Return Values

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| \[0] | uint256 | The amount that was assigned |

### \_partiallyAssignOffer

```solidity
function _partiallyAssignOffer(struct TermAuctionRevealedOffer offer, uint256 assignedAmount) internal returns (uint256)
```

Partially assigns an offer

#### Parameters

| Name           | Type                            | Description          |
| -------------- | ------------------------------- | -------------------- |
| offer          | struct TermAuctionRevealedOffer | The offer to assign  |
| assignedAmount | uint256                         | The amount to assign |

#### Return Values

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| \[0] | uint256 | The amount that was assigned |

### \_assignRolloverBid

```solidity
function _assignRolloverBid(address borrower, uint256 purchasePrice, uint256 repurchasePrice, address rolloverPairOffTermRepoServicer) internal
```

### \_markRolloverAsProcessed

```solidity
function _markRolloverAsProcessed(address rolloverPairOffTermRepoServicer, address borrower) internal
```

### \_assignBids

```solidity
function _assignBids(struct TermAuctionRevealedBid[] sortedBids, uint256 maxAssignable, uint256 purchaseTokenDecimals) internal returns (uint256)
```

Assigns bids up to `maxAssignable`

*This method allocates pro-rata across an the marginal price group (pro-rata on the margin) and attempts to prevent residuals from accumulating to a single bid*

#### Parameters

| Name                  | Type                             | Description                                                    |
| --------------------- | -------------------------------- | -------------------------------------------------------------- |
| sortedBids            | struct TermAuctionRevealedBid\[] | An array of sorted bids to process                             |
| maxAssignable         | uint256                          | The maximum bid amount that can be assigned across all bidders |
| purchaseTokenDecimals | uint256                          | The number of decimals of the purchase token                   |

#### Return Values

| Name | Type    | Description               |
| ---- | ------- | ------------------------- |
| \[0] | uint256 | The total amount assigned |

### \_assignOffers

```solidity
function _assignOffers(struct TermAuctionRevealedOffer[] sortedOffers, uint256 maxAssignable, uint256 purchaseTokenDecimals) internal returns (uint256)
```

Assigns offers up to `maxAssignable`

*This method allocates pro-rata across an the marginal price group (pro-rata on the margin) and attempts to prevent residuals from accumulating to a single offer*

#### Parameters

| Name                  | Type                               | Description                                                     |
| --------------------- | ---------------------------------- | --------------------------------------------------------------- |
| sortedOffers          | struct TermAuctionRevealedOffer\[] | An array of sorted offers to process                            |
| maxAssignable         | uint256                            | The maximum offer amount that can be assigned across all offers |
| purchaseTokenDecimals | uint256                            | The number of decimals of the purchase token                    |

#### Return Values

| Name | Type    | Description               |
| ---- | ------- | ------------------------- |
| \[0] | uint256 | The total amount assigned |

### \_calculateRepurchasePrice

```solidity
function _calculateRepurchasePrice(uint256 purchasePrice) internal view returns (uint256)
```

Calculates repurchase price given a purchase price (equivalent to principal plus interest)

#### Parameters

| Name          | Type    | Description        |
| ------------- | ------- | ------------------ |
| purchasePrice | uint256 | The purchase price |

#### Return Values

| Name | Type    | Description                                                                                       |
| ---- | ------- | ------------------------------------------------------------------------------------------------- |
| \[0] | uint256 | The repurchase price obtained by applying the clearing rate on an Actual/360 day-count convention |

### \_calculateAndStoreClearingPrice

```solidity
function _calculateAndStoreClearingPrice(struct TermAuctionRevealedBid[] sortedBids, struct TermAuctionRevealedOffer[] sortedOffers) internal returns (uint256, uint256)
```

### pauseCompleteAuction

```solidity
function pauseCompleteAuction() external
```

\_This function pauses the TermAuction contract preventing public state changes See {Pausable-*pause}.*

### unpauseCompleteAuction

```solidity
function unpauseCompleteAuction() external
```

Unpuses the TermAuction contract allowing public state changes

\_See {Pausable-*unpause}.*

### \_authorizeUpgrade

```solidity
function _authorizeUpgrade(address impl) internal
```

*required override by the OpenZeppelin UUPS module*

#### Parameters

| Name | Type    | Description                        |
| ---- | ------- | ---------------------------------- |
| impl | address | new impl address for proxy upgrade |
