# FlashLoan Reciever Specification

This document defines the specification for contracts that receive flash loans in a decentralized environment, ensuring that the receiving contract can interact with flash loan protocols efficiently and securely.

```lua
Handlers.add('onloanrecieved', Handlers.utils.hasMatchingTag('Action', 'OnLoanReceived'), function(msg)
    local quantity = tonumber(msg.Tags.Quantity)
    local tokenProcessId = msg.Tags.TokenProcessId -- Get TokenProcessId from message tags
    local feeAmount = tonumber(msg.Tags.Fee) -- Get Fee percentage from message tags
    assert(type(quantity) == 'number', 'Quantity must be a number')
    assert(type(tokenProcessId) == 'string', 'TokenProcessId must be a string')
    assert(type(feePercentage) == 'number', 'Fee must be a number')
    
    local totalAmount = quantity + feeAmount

    -- Transfer tokens from msg.From to this contract using TransferFrom
    ao.send({
        Target = tokenProcessId, -- Use TokenProcessId from parameter
        Tags = {
            Action = 'TransferFrom',
            from = msg.From,
            to = ao.id,
            Quantity = tostring(quantity)
        }
    })


--[[
Perform whatever you want to do with the received tokens here
For example, you can use the received tokens to provide liquidity to a pool, or to trade on a DEX

--]]

    -- Approve msg.From to spend the quantity received plus fees
    ao.send({
        Target = tokenProcessId, -- Use TokenProcessId from parameter
        Tags = {
            Action = 'Transfer',
            Recipient = msg.From,
            Quantity = tostring(totalAmount)
        }
    })
end)
```

The `onloanrecieved` handler expects the following parameters within the `msg` object:

1. **`msg.From`**
   * **Type:** `string`
   * **Description:** The identifier of the entity sending the loan. This represents the account from which tokens will be transferred.
2. **`msg.Tags.Quantity`**
   * **Type:** `string` (converted to `number` within the handler)
   * **Description:** The amount of tokens to be transferred from `msg.From` to the contract. This value determines both the transfer quantity and the subsequent approval amount after fees.
3. **`msg.Tags.TokenProcessId`**
   * **Type:** `string`
   * **Description:** The process ID of the token contract (`AOToken-Specification`). This ID is used to specify which token contract to interact with for the `TransferFrom` and `Approve` actions.
4. **`msg.Tags.Fee`**
   * **Type:** `string` (converted to `number` within the handler)
   * **Description:** The fee percentage to be applied to the transferred tokens. This percentage is used to calculate the fee amount, which is added to the approved quantity.

#### 🚀 Explanation :&#x20;

1. **Parameter Extraction and Validation**

```lua
local quantity = tonumber(msg.Tags.Quantity)
local tokenProcessId = msg.Tags.TokenProcessId
local feePercentage = tonumber(msg.Tags.Fee)

assert(type(quantity) == 'number', 'Quantity must be a number')
assert(type(tokenProcessId) == 'string', 'TokenProcessId must be a string')
assert(type(feePercentage) == 'number', 'Fee must be a number')
```

* Converts `Quantity` and `Fee` from strings to numbers.
* Validates the types of `quantity`, `tokenProcessId`, and `feePercentage`

2. **Fee Calculation**

```lua
local feeAmount = quantity * feePercentage / 100
local totalApprove = quantity + feeAmount
```

* Calculates the fee based on the provided percentage.
* Determines the total amount to approve, which is the sum of the transferred quantity and the fee.

3. **Token Transfer (`TransferFrom`)**

```lua
ao.send({
    Target = tokenProcessId,
    Tags = {
        Action = 'TransferFrom',
        Owner = msg.From,
        Recipient = ao.id,
        Quantity = tostring(quantity)
    }
})
```

Initiates a `TransferFrom` action to move the specified `quantity` of tokens from `msg.From` to the contract (`ao.id`).

4. Arbitage/Self-Liquidation/ Loan Refiance

   Add specific calls to ensure what you want to perfrom gets performed.
5. **Transfer back  Tokens (Transfer`)`**

{% code fullWidth="false" %}

```lua
ao.send({
    Target = tokenProcessId, -- Use TokenProcessId from parameter
    Tags = {
        Action = "Transfer",
        Spender = msg.From,
        Quantity = tostring(totalAmount)
    }
})
```

{% endcode %}

We must return the borrowed token back to the `ArFlash` protocol otherwise the whole transaction might revert.

Grants `msg.From` the permission to spend the `totalApprove` amount of tokens on behalf of the contract. This includes both the transferred quantity and the calculated fee.

Granting this protocol will transferback the same number of tokens back to itself.<br>


---

# 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://calc1f4r.gitbook.io/arflash/specification/flashloan-reciever-specification.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.
