openapi: 3.0.3
info:
  title: Referral Smart Contract
  description: >
    The Referral Smart Contract enables dApp integrators to earn referral fees
    on swaps routed through their application. It executes a normal router swap
    and then splits the final output between the referral address and the user.


    ## Overview


    The Referral contract provides:


    - **On-chain Referral Fees**: Your dApp earns fees directly on-chain for
    swaps it routes

    - **Automatic Output Splitting**: After swap, output is split between
    referral and user

    - **Configurable Percentage**: Referral percentage from 0.1% to 5% (base
    100,000)


    ## How Output Splitting Works


    After the swap output is determined:


    1. `referral_amount = amount_out_total * referral_percentage / 100000`

    2. `destination_amount = amount_out_total - referral_amount`


    - **Referral amount** → sent to your `referral_address`

    - **User amount** → sent to `amount_out_destination` (or caller if not
    provided)


    ## Referral Percentage Format


    `referral_percentage` uses a base of `100_000`:


    | Value | Percentage |

    |-------|-----------|

    | `100` | `0.1%` |

    | `1_000` | `1.0%` |

    | `5_000` | `5.0%` (max) |


    ## Quotation Flow (Best Practice)


    Before sending the swap transaction, request a quotation using token asset
    IDs:


    **Endpoint:** `POST https://api.bitcoin.me/quotation`


    ```bash

    curl -X POST https://api.bitcoin.me/quotation \
      -H "Content-Type: application/json" \
      -d '{
        "amountIn": "1000",
        "tokenIn": "KLV",
        "tokenOut": "KFI"
      }'
    ```


    **Notes:**

    - `amountIn` must be a string

    - `tokenIn` and `tokenOut` must be token asset IDs/tickers expected by the
    quotation API

    - Use the quotation response to set `amount_out_min` with common DEX
    slippage best practices (for example, apply a configurable slippage
    tolerance and never use zero protection in production)


    ## Suggested Integration Sequence


    1. User selects input/output tokens and amount

    2. Frontend calls quotation API

    3. Frontend computes `amount_out_min` based on quote and slippage

    4. Frontend submits `swap` transaction with your referral address, referral
    percentage, and user payment in `token_in`

    5. Contract executes swap and splits output


    ## ABI


    ABI reference for the Referral smart contract (`Referral`). Framework:
    **klever-sc v0.45.0**.


    ### swap (Swap with Referral)


    Executes a swap via Router with a referral fee. The fee is extracted from
    the output and sent to the referral address.


    - `referral_percentage`: in units of 1/100,000 (100 = 0.1%, 1000 = 1%, 5000
    = 5%)

    - Min: 100 (0.1%), Max: 5000 (5%)

    - Supports direct swaps (1 hop) and via KLV (2 hops)


    ```json

    {
      "name": "swap",
      "mutability": "mutable",
      "payableInTokens": ["*"],
      "inputs": [
        { "name": "referral_address", "type": "Address" },
        { "name": "referral_percentage", "type": "u32" },
        { "name": "token_in", "type": "TokenIdentifier" },
        { "name": "token_out", "type": "TokenIdentifier" },
        { "name": "amount_out_min", "type": "BigUint" },
        { "name": "amount_out_destination", "type": "optional<Address>" }
      ],
      "outputs": []
    }

    ```


    ### getRouterAddress (view)


    ```json

    {
      "name": "getRouterAddress",
      "mutability": "readonly",
      "inputs": [],
      "outputs": [
        { "type": "Address" }
      ]
    }

    ```
  version: 1.0.0
  contact:
    name: Bitcoin.me DeFi
    url: https://bitcoin.me
servers:
  - url: https://node.testnet.klever.org
    description: Testnet
  - url: https://node.mainnet.klever.org
    description: Mainnet
tags:
  - name: Endpoints
    description: Write operations that modify contract state
paths:
  /vm/query#swap:
    post:
      tags:
        - Endpoints
      summary: Swap with Referral
      description: >
        Executes a router swap and splits the final output between the referral
        address and the destination address.


        **How it works:**

        1. Receives the swap parameters along with referral configuration

        2. Executes the swap through the router

        3. Calculates the referral fee from the total output

        4. Sends the referral amount to `referral_address`

        5. Sends the remaining amount to `amount_out_destination` (or the caller
        if not provided)


        **Referral Fee Calculation:**

        - `referral_amount = amount_out_total * referral_percentage / 100000`

        - `destination_amount = amount_out_total - referral_amount`


        **Referral Percentage:**

        Uses a base of `100_000` — valid range is `100` (0.1%) to `5_000` (5.0%)


        **Payment:** The input token amount to be swapped (sent as transaction
        value)
      operationId: swap
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - scAddress
                - funcName
                - args
                - value
              properties:
                scAddress:
                  type: string
                  description: Referral contract address
                  example: >-
                    klv1qqqqqqqqqqqqqpgqjd9k34hzy53lsreq4drqkwfedqvtqen3x04sevtrjj
                funcName:
                  type: string
                  enum:
                    - swap
                  example: swap
                args:
                  type: array
                  items:
                    type: string
                  description: >
                    Arguments:

                    - `referral_address` (ManagedAddress): Address that receives
                    the referral fee

                    - `referral_percentage` (u64): Referral fee percentage (base
                    100,000 — e.g., 1000 = 1.0%)

                    - `token_in` (TokenIdentifier): Input token identifier

                    - `token_out` (TokenIdentifier): Output token identifier

                    - `amount_out_min` (BigUint): Minimum acceptable output
                    amount (slippage protection)

                    - `amount_out_destination` (ManagedAddress, optional):
                    Address to receive user output (defaults to caller)
                  example:
                    - address:klv1referral_address_example
                    - u64:1000
                    - string:KLV
                    - string:KFI
                    - BigUint:950
                    - address:klv1destination_address_example
            examples:
              swap_with_referral:
                summary: Swap KLV for KFI with 1% referral fee
                value:
                  scAddress: >-
                    klv1qqqqqqqqqqqqqpgqjd9k34hzy53lsreq4drqkwfedqvtqen3x04sevtrjj
                  funcName: swap
                  args:
                    - address:klv1referral_address_example
                    - u64:1000
                    - string:KLV
                    - string:KFI
                    - BigUint:950
                    - address:klv1destination_address_example
                  value: KLV=1000
              swap_without_destination:
                summary: Swap KLV for KFI (output to caller)
                value:
                  scAddress: >-
                    klv1qqqqqqqqqqqqqpgqjd9k34hzy53lsreq4drqkwfedqvtqen3x04sevtrjj
                  funcName: swap
                  args:
                    - address:klv1referral_address_example
                    - u64:500
                    - string:KLV
                    - string:KFI
                    - BigUint:950
                  value: KLV=1000
      responses:
        '200':
          description: Returns the swap output amounts (referral amount and user amount)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VMQueryResponse'
              example:
                data:
                  returnData:
                    - referral amount sent to referral_address
                    - user amount sent to destination
                  returnCode: ok
components:
  schemas:
    VMQueryResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            returnData:
              type: array
              items:
                type: string
            returnCode:
              type: string
            returnMessage:
              type: string
        error:
          type: string
        code:
          type: string
    KdaTokenPayment:
      type: object
      description: Token payment structure
      properties:
        assetId:
          type: string
          description: Asset identifier (e.g., "KFI", "KLV")
        assetType:
          type: string
          enum:
            - Fungible
            - SemiFungible
        from:
          type: string
          description: Sender address
        to:
          type: string
          description: Recipient address
        value:
          type: string
          description: Amount transferred
