> ## Documentation Index
> Fetch the complete documentation index at: https://wallet-docs.iexexchanger.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Refund deposit to sender (1.4.0)

> Создаёт выплату-возврат (`source=refund`) на адрес отправителя входящей транзакции (или на `toAddress`). Депозит переходит в `refund_process`; по исходу выплаты — `refund_paid` (webhook `deposit.refunded`) или `refund_fail` (`deposit.refund_failed`). Разрешено из статусов paid / paid_over / wrong_amount / refund_fail. По настройке платформы выплата-возврат ждёт одобрения оператора (`pending_approval`). Повторный вызов при живой выплате-возврате → 409 REFUND_IN_PROGRESS. Требует scope deposit_and_payout.



## OpenAPI

````yaml /openapi-public.json post /v1/public/deposits/{uuid}/refund
openapi: 3.0.0
info:
  title: Wallet Platform — Public API
  description: >-
    API для интеграции CMS обменника: создание депозитов и выплат, отслеживание
    статусов, справочники активов и сетей.


    ## Аутентификация

    Каждый запрос подписывается HMAC-SHA256. Обязательные заголовки:

    - `X-Api-Id` — публичный идентификатор ключа (выдаётся в админке).

    - `X-Api-Key` — публичный ключ.

    - `X-Timestamp` — Unix-секунды; сервер принимает ±300 сек от своего времени.

    - `X-Signature` — `HMAC_SHA256_Hex( X-Timestamp + "." + raw_body, api_secret
    )`. Для GET тело пустое.

    - `X-Idempotency-Key` — опционально (UUID). Гарантирует, что повторный POST
    не создаст дубликат.


    Дополнительно: IP-вызывающего должен быть в whitelist сайта (настраивается в
    админке). Секрет (`api_secret`) показывается один раз при создании ключа и
    хранится только у вас.


    ## Формат ответа

    Все ответы — единый envelope: `{ "ok": true, "data": ... }` при успехе либо
    `{ "ok": false, "error": { "code": "...", "message": "..." } }` при ошибке.


    ## Идемпотентность

    Создание депозита/выплаты идемпотентно по вашему `order_id` (уникален в
    рамках сайта и актива) и/или по `X-Idempotency-Key`. Повторный вызов с тем
    же ключом вернёт исходный объект, а не создаст новый.


    ## Webhooks (исходящие)

    При смене статуса платформа шлёт POST на ваш `callback_url`. Заголовки:
    `X-Event-Type`, `X-Event-Id` (uuid, идемпотентность на вашей стороне),
    `X-Timestamp`, `X-Signature` = `HMAC_SHA256_Hex(raw_body, callback_secret)`.
    Проверяйте подпись перед обработкой.

    События: `deposit.tx_detected`, `deposit.finalized`, `deposit.failed`,
    `deposit.refunded`, `payout.broadcasted`, `payout.confirmed`,
    `payout.failed`.

    Доставка считается успешной при HTTP 2xx за 10 секунд. Ретраи: 30s, 2m, 10m,
    1h, 6h, 24h (до 8 попыток).
  version: '1'
  contact: {}
servers: []
security:
  - X-Api-Id: []
    X-Api-Key: []
    hmac: []
    X-Timestamp: []
tags: []
paths:
  /v1/public/deposits/{uuid}/refund:
    post:
      tags:
        - public · deposits
      summary: Refund deposit to sender (1.4.0)
      description: >-
        Создаёт выплату-возврат (`source=refund`) на адрес отправителя входящей
        транзакции (или на `toAddress`). Депозит переходит в `refund_process`;
        по исходу выплаты — `refund_paid` (webhook `deposit.refunded`) или
        `refund_fail` (`deposit.refund_failed`). Разрешено из статусов paid /
        paid_over / wrong_amount / refund_fail. По настройке платформы
        выплата-возврат ждёт одобрения оператора (`pending_approval`). Повторный
        вызов при живой выплате-возврате → 409 REFUND_IN_PROGRESS. Требует scope
        deposit_and_payout.
      operationId: DepositRefundPublicController_create
      parameters:
        - name: uuid
          required: true
          in: path
          schema:
            type: string
            format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateDepositRefundDto'
      responses:
        '201':
          description: ''
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DepositRefundResponseDto'
      security:
        - hmac: []
components:
  schemas:
    CreateDepositRefundDto:
      type: object
      properties:
        toAddress:
          type: string
          example: TXYZ…
          description: >-
            Адрес получателя возврата. По умолчанию — адрес отправителя входящей
            транзакции (transaction.fromAddress).
          maxLength: 255
        toMemo:
          type: string
          description: 'Memo/tag получателя (memo-based сети: TON, XRP, XLM…).'
          maxLength: 255
        amount:
          type: string
          example: '95.5'
          description: >-
            Сумма возврата (string decimal). По умолчанию — вся полученная
            сумма. Не больше полученной; сетевая комиссия удерживается с
            hot-кошелька по правилам выплат.
        reason:
          type: string
          example: client cancelled the order
          maxLength: 500
          description: Причина возврата (в аудит).
    DepositRefundResponseDto:
      type: object
      properties:
        payout:
          description: Созданная выплата-возврат (source=refund).
          allOf:
            - $ref: '#/components/schemas/PublicPayoutResponseDto'
        deposit:
          $ref: '#/components/schemas/DepositRefundDepositRefDto'
      required:
        - payout
        - deposit
    PublicPayoutResponseDto:
      type: object
      properties:
        uuid:
          type: string
          format: uuid
          description: Публичный идентификатор выплаты.
        orderId:
          type: string
          example: payout_77
          description: Ваш order_id (label).
        status:
          type: string
          enum:
            - new
            - pending_approval
            - approved
            - rejected
            - queued
            - signing
            - broadcasted
            - confirmed
            - failed
            - cancelled
          example: queued
          description: >-
            Бизнес-статус выплаты (полный набор). Поток: new → pending_approval
            → approved → queued → signing → broadcasted → confirmed.
            Терминальные: rejected (отклонена оператором), failed (ошибка
            broadcast/revert), cancelled (отменена до подписи).
        assetCode:
          type: string
          example: USDT_TRC20
        destinationAddress:
          type: string
          example: TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
          description: Адрес получателя.
        destinationMemo:
          type: string
          nullable: true
          example: null
          description: Memo получателя (для memo-based сетей), иначе null.
        amount:
          type: string
          example: '50.000000'
          description: Сумма выплаты (string).
        requiresApproval:
          type: boolean
          example: false
          description: Требуется ли ручное одобрение оператором.
        txHash:
          type: string
          nullable: true
          example: a1b2c3...e9f0
          description: >-
            Хеш исходящей blockchain-tx (после broadcast). null пока не
            отправлена.
        confirmations:
          type: number
          nullable: true
          example: 12
          description: >-
            Текущее число подтверждений сети для исходящей tx. null пока не
            отправлена.
        requiredConfirmations:
          type: number
          nullable: true
          example: 19
          description: >-
            Сколько подтверждений нужно для финализации
            (asset.minConfirmations). null пока не отправлена.
        networkStatus:
          type: string
          enum:
            - pending
            - mempool
            - confirmed
            - fail
          nullable: true
          example: confirmed
          description: >-
            On-chain статус исходящей tx: pending → mempool → confirmed | fail.
            null пока не отправлена.
        explorerTxUrl:
          type: string
          nullable: true
          example: https://tronscan.org/#/transaction/a1b2c3
          description: Ссылка на исходящую tx в explorer.
        failReason:
          type: string
          nullable: true
          description: Причина ошибки (для status=failed/rejected/cancelled), иначе null.
        approvedAt:
          type: string
          format: date-time
          nullable: true
          description: >-
            Когда выплата одобрена оператором. null если ещё не одобрена /
            auto-approve.
        broadcastedAt:
          type: string
          format: date-time
          nullable: true
          description: Когда tx отправлена в сеть (broadcast). null пока не отправлена.
        confirmedAt:
          type: string
          format: date-time
          nullable: true
          description: Когда выплата подтверждена сетью. null пока не подтверждена.
        createdAt:
          type: string
          format: date-time
          description: Время создания выплаты.
        updatedAt:
          type: string
          format: date-time
          description: Время последнего обновления.
        network:
          type: string
          example: TRON
          description: '1.4.0: сеть актива.'
        isFinal:
          type: boolean
          example: false
          description: '1.4.0: терминальный ли статус — можно прекращать поллинг.'
        priority:
          type: string
          enum:
            - economy
            - recommended
            - high
          example: recommended
          description: '1.4.0: приоритет сетевой комиссии.'
        amountUsd:
          type: string
          nullable: true
          example: '50.00'
          description: '1.4.0: оценка суммы в USD.'
        rateUsd:
          type: string
          nullable: true
          example: '1.00'
          description: '1.4.0: курс актива к USD.'
        commission:
          type: string
          nullable: true
          description: '1.4.0: комиссия обменника (ledger), если учёт включён.'
        networkFee:
          type: string
          nullable: true
          description: >-
            1.4.0: фактическая сетевая комиссия исходящей tx (нативная монета
            сети).
      required:
        - uuid
        - orderId
        - status
        - assetCode
        - destinationAddress
        - destinationMemo
        - amount
        - requiresApproval
        - txHash
        - confirmations
        - requiredConfirmations
        - networkStatus
        - explorerTxUrl
        - failReason
        - approvedAt
        - broadcastedAt
        - confirmedAt
        - createdAt
        - updatedAt
        - network
        - isFinal
        - priority
        - amountUsd
        - rateUsd
        - commission
        - networkFee
    DepositRefundDepositRefDto:
      type: object
      properties:
        uuid:
          type: string
          format: uuid
        orderId:
          type: string
          example: ORD-1001
        status:
          type: string
          example: refund_process
      required:
        - uuid
        - orderId
        - status
  securitySchemes:
    X-Api-Id:
      type: apiKey
      in: header
      name: X-Api-Id
      description: Публичный идентификатор API-ключа
    X-Api-Key:
      type: apiKey
      in: header
      name: X-Api-Key
      description: Публичный API-ключ
    hmac:
      type: apiKey
      in: header
      name: X-Signature
      description: HMAC-SHA256-Hex(timestamp + "." + raw_body, api_secret)
    X-Timestamp:
      type: apiKey
      in: header
      name: X-Timestamp
      description: Unix-секунды, ±300с

````