# AtomicQueue

[Git Source](https://github.com/Ion-Protocol/nucleus-boring-vault/blob/cc0b494b83e17b9b169a73b96050d2810b690477/src/atomic-queue/AtomicQueue.sol)

**Inherits:** ReentrancyGuard

**Author:** crispymangoes

Allows users to create `AtomicRequests` that specify an ERC20 asset to `offer` and an ERC20 asset to `want` in return.

Making atomic requests where the exchange rate between offer and want is not relatively stable is effectively the same as placing a limit order between those assets, so requests can be filled at a rate worse than the current market rate.

It is possible for a user to make multiple requests that use the same offer asset. If this is done it is important that the user has approved the queue to spend the total amount of assets aggregated from all their requests, and to also have enough `offer` asset to cover the aggregate total request of `offerAmount`.

## State Variables

### userAtomicRequest

Maps user address to offer asset to want asset to a AtomicRequest struct.

```solidity
mapping(address => mapping(ERC20 => mapping(ERC20 => AtomicRequest))) public userAtomicRequest;
```

## Functions

### getUserAtomicRequest

Get a users Atomic Request.

```solidity
function getUserAtomicRequest(address user, ERC20 offer, ERC20 want) external view returns (AtomicRequest memory);
```

**Parameters**

| Name    | Type      | Description                                         |
| ------- | --------- | --------------------------------------------------- |
| `user`  | `address` | the address of the user to get the request for      |
| `offer` | `ERC20`   | the ERC0 token they want to exchange for the want   |
| `want`  | `ERC20`   | the ERC20 token they want in exchange for the offer |

### isAtomicRequestValid

Helper function that returns either true: Withdraw request is valid. false: Withdraw request is not valid.

*It is possible for a withdraw request to return false from this function, but using the request in `updateAtomicRequest` will succeed, but solvers will not be able to include the user in `solve` unless some other state is changed.*

```solidity
function isAtomicRequestValid(
    ERC20 offer,
    address user,
    AtomicRequest calldata userRequest
)
    external
    view
    returns (bool);
```

**Parameters**

| Name          | Type            | Description                                       |
| ------------- | --------------- | ------------------------------------------------- |
| `offer`       | `ERC20`         | the ERC0 token they want to exchange for the want |
| `user`        | `address`       | the address of the user making the request        |
| `userRequest` | `AtomicRequest` | the request struct to validate                    |

### updateAtomicRequest

Allows user to add/update their withdraw request.

It is possible for a withdraw request with a zero atomicPrice to be made, and solved. If this happens, users will be selling their shares for no assets in return. To determine a safe atomicPrice, share.previewRedeem should be used to get a good share price, then the user can lower it from there to make their request fill faster.

```solidity
function updateAtomicRequest(ERC20 offer, ERC20 want, AtomicRequest calldata userRequest) external nonReentrant;
```

**Parameters**

| Name          | Type            | Description                                                   |
| ------------- | --------------- | ------------------------------------------------------------- |
| `offer`       | `ERC20`         | the ERC20 token the user is offering in exchange for the want |
| `want`        | `ERC20`         | the ERC20 token the user wants in exchange for offer          |
| `userRequest` | `AtomicRequest` | the users request                                             |

### solve

Called by solvers in order to exchange offer asset for want asset.

Solvers are optimistically transferred the offer asset, then are required to approve this contract to spend enough of want assets to cover all requests.

*It is very likely `solve` TXs will be front run if broadcasted to public mem pools, so solvers should use private mem pools.*

```solidity
function solve(
    ERC20 offer,
    ERC20 want,
    address[] calldata users,
    bytes calldata runData,
    address solver
)
    external
    nonReentrant;
```

**Parameters**

| Name      | Type        | Description                                                           |
| --------- | ----------- | --------------------------------------------------------------------- |
| `offer`   | `ERC20`     | the ERC20 offer token to solve for                                    |
| `want`    | `ERC20`     | the ERC20 want token to solve for                                     |
| `users`   | `address[]` | an array of user addresses to solve for                               |
| `runData` | `bytes`     | extra data that is passed back to solver when `finishSolve` is called |
| `solver`  | `address`   | the address to make `finishSolve` callback to                         |

### viewSolveMetaData

Helper function solvers can use to determine if users are solvable, and the required amounts to do so.

Repeated users are not accounted for in this setup, so if solvers have repeat users in their `users` array the results can be wrong.

*Since a user can have multiple requests with the same offer asset but different want asset, it is possible for `viewSolveMetaData` to report no errors, but for a solve to fail, if any solves were done between the time `viewSolveMetaData` and before `solve` is called.*

```solidity
function viewSolveMetaData(
    ERC20 offer,
    ERC20 want,
    address[] calldata users
)
    external
    view
    returns (SolveMetaData[] memory metaData, uint256 totalAssetsForWant, uint256 totalAssetsToOffer);
```

**Parameters**

| Name    | Type        | Description                                         |
| ------- | ----------- | --------------------------------------------------- |
| `offer` | `ERC20`     | the ERC20 offer token to check for solvability      |
| `want`  | `ERC20`     | the ERC20 want token to check for solvability       |
| `users` | `address[]` | an array of user addresses to check for solvability |

### \_calculateAssetAmount

Helper function to calculate the amount of want assets a users wants in exchange for `offerAmount` of offer asset.

```solidity
function _calculateAssetAmount(
    uint256 offerAmount,
    uint256 atomicPrice,
    uint8 offerDecimals
)
    internal
    pure
    returns (uint256);
```

## Events

### AtomicRequestUpdated

Emitted when `updateAtomicRequest` is called.

```solidity
event AtomicRequestUpdated(
    address user,
    address offerToken,
    address wantToken,
    uint256 amount,
    uint256 deadline,
    uint256 minPrice,
    uint256 timestamp
);
```

### AtomicRequestFulfilled

Emitted when `solve` exchanges a users offer asset for their want asset.

```solidity
event AtomicRequestFulfilled(
    address user,
    address offerToken,
    address wantToken,
    uint256 offerAmountSpent,
    uint256 wantAmountReceived,
    uint256 timestamp
);
```

## Errors

### AtomicQueue\_\_UserRepeated

```solidity
error AtomicQueue__UserRepeated(address user);
```

### AtomicQueue\_\_RequestDeadlineExceeded

```solidity
error AtomicQueue__RequestDeadlineExceeded(address user);
```

### AtomicQueue\_\_UserNotInSolve

```solidity
error AtomicQueue__UserNotInSolve(address user);
```

### AtomicQueue\_\_ZeroOfferAmount

```solidity
error AtomicQueue__ZeroOfferAmount(address user);
```

## Structs

### AtomicRequest

Stores request information needed to fulfill a users atomic request.

*atomicPrice MUST be in terms of `want` asset decimals.*

```solidity
struct AtomicRequest {
    uint64 deadline;
    uint88 atomicPrice;
    uint96 offerAmount;
    bool inSolve;
}
```

**Properties**

| Name          | Type     | Description                                                                                |
| ------------- | -------- | ------------------------------------------------------------------------------------------ |
| `deadline`    | `uint64` | unix timestamp for when request is no longer valid                                         |
| `atomicPrice` | `uint88` | the price in terms of `want` asset the user wants their `offer` assets "sold" at           |
| `offerAmount` | `uint96` | the amount of `offer` asset the user wants converted to `want` asset                       |
| `inSolve`     | `bool`   | bool used during solves to prevent duplicate users, and to prevent redoing multiple checks |

### SolveMetaData

Used in `viewSolveMetaData` helper function to return data in a clean struct.

```solidity
struct SolveMetaData {
    address user;
    uint8 flags;
    uint256 assetsToOffer;
    uint256 assetsForWant;
}
```

**Properties**

| Name            | Type      | Description                                                                                                                                                                                                                                                                                                                                                                                               |
| --------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user`          | `address` | the address of the user                                                                                                                                                                                                                                                                                                                                                                                   |
| `flags`         | `uint8`   | 8 bits indicating the state of the user only the first 4 bits are used XXXX0000 Either all flags are false(user is solvable) or only 1 is true(an error occurred). From right to left - 0: indicates user deadline has passed. - 1: indicates user request has zero offer amount. - 2: indicates user does not have enough offer asset in wallet. - 3: indicates user has not given AtomicQueue approval. |
| `assetsToOffer` | `uint256` | the amount of offer asset to solve                                                                                                                                                                                                                                                                                                                                                                        |
| `assetsForWant` | `uint256` | the amount of assets users want for their offer assets                                                                                                                                                                                                                                                                                                                                                    |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nucleusearn.io/nucleus-architecture/smart-contracts/contracts/atomic-queue/atomicqueue.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
