概要

ReceiptQueueは、TeleporterMessageReceipt(メッセージの配送証明)を効率的に管理するためのSolidityライブラリです。 FIFO(First-In, First-Out)の原則に従うキュー(待ち行列)として機能し、ガス効率の良いデータ構造を提供します。

このライブラリは、TeleporterMessengerコントラクト内部で使用されることを想定しています。メッセージが宛先チェーンに到達すると、その送付証明であるレシートが生成されます。 ReceiptQueueは、これらのレシートを一時的に保管し、送信元チェーンへ送り返す準備が整うまで順番に保持する役割を担います。

データ構造として、TeleporterMessageReceiptQueueという構造体を使用します。 これはキューの先頭(first)と末尾(last)を指す2つのインデックスと、インデックスからレシート本体をマッピングするdataで構成されており、Solidityにおいて効率的にキューを実装するための一般的な手法です。

機能

このライブラリは、レシートキューに対する基本的な操作を提供します。

  • キューに新しいレシートを追加する (enqueue)
  • キューから最も古いレシートを取り出して削除する (dequeue)
  • 次のメッセージに含めるためのレシートを一度に複数取得する
  • キュー内のレシート数を取得する
  • キュー内の特定のレシート情報を参照する

フロー

  • レシートのキューイングと一括取得のフロー

レシートのキューイングと一括取得のフロー

sequenceDiagram
    participant Messenger as TeleporterMessenger
    participant Queue as ReceiptQueue Library

    Note over Messenger: 他チェーンからメッセージを受信
    Messenger->>+Queue: enqueue(新しいレシート)
    Note over Queue: lastインデックスをインクリメントし、<br/>mappingにレシートを保存
    Queue-->>-Messenger: 

    Note over Messenger: 複数レシートがキューに溜まった状態

    Note over Messenger: 送信元チェーンへメッセージを送付するタイミング
    Messenger->>+Queue: getOutstandingReceiptsToSend()
    activate Queue
    Note over Queue: キューのサイズと最大取得数を比較し、<br/>送付するレシート数を決定
    loop 決定した数だけ繰り返す
        Queue->>Queue: dequeue()
    end
    Queue-->>-Messenger: 送付するレシートの配列
    deactivate Queue
    
    Note over Messenger: 取得したレシートを<br/>新しいメッセージに含めて送付する

コード

solidity
// (c) 2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

// SPDX-License-Identifier: LicenseRef-Ecosystem

pragma solidity 0.8.25;

import {Math} from "@openzeppelin/contracts@5.0.2/utils/math/Math.sol";
import {TeleporterMessageReceipt} from "./ITeleporterMessenger.sol";

/**
 * @dev ReceiptQueue is a convenience library that creates a queue-like interface of
 * TeleporterMessageReceipt structs. It provides FIFO properties.
 * Note: All functions in this library are internal so that the library is not deployed as a contract.
 *
 * @custom:security-contact https://github.com/ava-labs/icm-contracts/blob/main/SECURITY.md
 */
library ReceiptQueue {
    // A receipt queue represents a FIFO list of receipts.
    struct TeleporterMessageReceiptQueue {
        // Tracks the head of the queue within the {data} mapping.
        uint256 first;
        // Tracks the tail of the queue within the {data} mapping.
        uint256 last;
        // Represents the elements in the queue. Each newly enqueue item is
        // assigned an index one greater than the previous tail.
        mapping(uint256 index => TeleporterMessageReceipt receipt) data;
    }

    // The maximum number of receipts to include in a single message.
    uint256 private constant _MAXIMUM_RECEIPT_COUNT = 5;

    // solhint-disable private-vars-leading-underscore
    /**
     * @dev Adds a receipt to the queue.
     */
    function enqueue(
        TeleporterMessageReceiptQueue storage queue,
        TeleporterMessageReceipt memory receipt
    ) internal {
        queue.data[queue.last++] = receipt;
    }

    /**
     * @dev Removes the oldest outstanding receipt from the queue.
     *
     * Requirements:
     * - The queue must be non-empty.
     */
    function dequeue(
        TeleporterMessageReceiptQueue storage queue
    ) internal returns (TeleporterMessageReceipt memory) {
        uint256 first_ = queue.first;
        require(queue.last != first_, "ReceiptQueue: empty queue");
        TeleporterMessageReceipt memory receipt = queue.data[first_];
        delete queue.data[first_];
        queue.first = first_ + 1;
        return receipt;
    }

    /**
     * @dev Returns the outstanding receipts for the given chain ID that should be included in the next message sent.
     */
    function getOutstandingReceiptsToSend(
        TeleporterMessageReceiptQueue storage queue
    ) internal returns (TeleporterMessageReceipt[] memory) {
        // Calculate the result size as the minimum of the number of receipts and maximum batch size.
        uint256 resultSize = Math.min(_MAXIMUM_RECEIPT_COUNT, size(queue));
        if (resultSize == 0) {
            return new TeleporterMessageReceipt[](0);
        }

        TeleporterMessageReceipt[] memory receipts = new TeleporterMessageReceipt[](resultSize);
        for (uint256 i; i < resultSize; ++i) {
            receipts[i] = dequeue(queue);
        }
        return receipts;
    }

    /**
     * @dev Returns the number of outstanding receipts in the queue.
     */
    function size(
        TeleporterMessageReceiptQueue storage queue
    ) internal view returns (uint256) {
        return queue.last - queue.first;
    }

    /**
     * @dev Returns the receipt at the given index in the queue.
     */
    function getReceiptAtIndex(
        TeleporterMessageReceiptQueue storage queue,
        uint256 index
    ) internal view returns (TeleporterMessageReceipt memory) {
        require(index < size(queue), "ReceiptQueue: index out of bounds");
        return queue.data[queue.first + index];
    }
    // solhint-enable private-vars-leading-underscore
}

構造体

TeleporterMessageReceiptQueue

text
struct TeleporterMessageReceiptQueue {
    // Tracks the head of the queue within the {data} mapping.
    uint256 first;
    // Tracks the tail of the queue within the {data} mapping.
    uint256 last;
    // Represents the elements in the queue. Each newly enqueue item is
    // assigned an index one greater than the previous tail.
    mapping(uint256 index => TeleporterMessageReceipt receipt) data;
}

FIFO(先入れ先出し)のレシートキューを管理する構造体。

  • first キューの先頭要素のインデックスを追跡します。 要素がデキューされるとインクリメントされます。
  • last キューの末尾(次に追加される要素のインデックス)を追跡します。 要素がエンキューされるとインクリメントされます。
  • data uint256のインデックスからTeleporterMessageReceipt構造体へのマッピング。 キューの要素の実体を格納します。

変数

_MAXIMUM_RECEIPT_COUNT

text
uint256 private constant _MAXIMUM_RECEIPT_COUNT = 5;

1つのクロスチェーンメッセージに含めることができるレシートの最大数を定義する定数。 メッセージサイズが大きくなりすぎてガスコストが高騰することを防ぐ目的で設定されています。

関数

enqueue

text
function enqueue(
    TeleporterMessageReceiptQueue storage queue,
    TeleporterMessageReceipt memory receipt
) internal {
    queue.data[queue.last++] = receipt;
}

キューの末尾に新しいレシートを追加する関数。 TeleporterMessageReceiptQueueストレージ変数と、追加したいレシートを引数に取ります。 現在のlastインデックスをキーとしてマッピングdataにレシートを格納し、その後lastインデックスを1つインクリメントします。 これにより、レシートがキューの最後尾に追加されます。

引数

  • queue 操作対象のTeleporterMessageReceiptQueueストレージ変数。
  • receipt キューに追加するTeleporterMessageReceipt。

dequeue

text
function dequeue(
    TeleporterMessageReceiptQueue storage queue
) internal returns (TeleporterMessageReceipt memory) {
    uint256 first_ = queue.first;
    require(queue.last != first_, "ReceiptQueue: empty queue");
    TeleporterMessageReceipt memory receipt = queue.data[first_];
    delete queue.data[first_];
    queue.first = first_ + 1;
    return receipt;
}

キューの先頭から最も古いレシートを1つ取り出し、キューから削除する関数。 キューが空(lastとfirstが等しい)の場合はエラーを発生させます。 空でなければ、現在のfirstインデックスにあるレシートを取得し、マッピングからその要素をdeleteで削除してガスを節約します。 その後、firstインデックスを1つインクリメントしてキューの先頭を更新し、取り出したレシートを返します。

引数

  • queue 操作対象のTeleporterMessageReceiptQueueストレージ変数。

戻り値

  • TeleporterMessageReceipt memory キューの先頭から取り出されたレシート。

getOutstandingReceiptsToSend

text
function getOutstandingReceiptsToSend(
    TeleporterMessageReceiptQueue storage queue
) internal returns (TeleporterMessageReceipt[] memory) {
    // Calculate the result size as the minimum of the number of receipts and maximum batch size.
    uint256 resultSize = Math.min(_MAXIMUM_RECEIPT_COUNT, size(queue));
    if (resultSize == 0) {
        return new TeleporterMessageReceipt[](0);
    }

    TeleporterMessageReceipt[] memory receipts = new TeleporterMessageReceipt[](resultSize);
    for (uint256 i; i < resultSize; ++i) {
        receipts[i] = dequeue(queue);
    }
    return receipts;
}

次のクロスチェーンメッセージに含めるべき、待機中のレシートを配列として取得する関数。 この関数は、キューからレシートを取り出して返却します。 取得するレシートの数は、キューの現在のサイズと定数_MAXIMUM_RECEIPT_COUNT(最大5件)のうち、小さい方の値に決定されます。 決定された数だけdequeue関数を呼び出してレシートをキューから取り出し、それらを配列にまとめて返します。 キューが空の場合は、空の配列を返します。

引数

  • queue 操作対象のTeleporterMessageReceiptQueueストレージ変数。

戻り値

  • TeleporterMessageReceipt[] memory キューから取り出されたレシートの配列。

size

text
function size(
    TeleporterMessageReceiptQueue storage queue
) internal view returns (uint256) {
    return queue.last - queue.first;
}

キュー内に存在する待機中のレシート数を返す関数。 末尾のインデックスlastから先頭のインデックスfirstを引くことで、現在のキューのサイズを計算して返します。

引数

  • queue 操作対象のTeleporterMessageReceiptQueueストレージ変数。

戻り値

  • uint256 キュー内の要素数。

getReceiptAtIndex

text
function getReceiptAtIndex(
    TeleporterMessageReceiptQueue storage queue,
    uint256 index
) internal view returns (TeleporterMessageReceipt memory) {
    require(index < size(queue), "ReceiptQueue: index out of bounds");
    return queue.data[queue.first + index];
}

キューから要素を削除せずに、指定したインデックスのレシート情報を参照する関数。 指定されたindexがキューのサイズを超えていないことを確認した後、キューの先頭firstにindexを足した値をキーとしてマッピングdataからレシート情報を取得して返します。 この操作はキューの状態を変更しません。

引数

  • queue 操作対象のTeleporterMessageReceiptQueueストレージ変数。
  • index 参照したいレシートの、キューの先頭を0とした相対インデックス。

戻り値

  • TeleporterMessageReceipt memory 指定されたインデックスに存在するレシート。