# TokenPartitionsLibrary.sol

> TokenPartitionsLibraryは、パーティション化されたトークン（例：発行日や属性が異なるトークン）の残高管理と操作ロジックを提供するライブラリです。

- URL: https://cardene.dev/books/blackrock-buidl/a63204
- 本: BlackRock BUIDL (https://cardene.dev/books/blackrock-buidl.md)
- 章: 9 / 24
- 前の章: https://cardene.dev/books/blackrock-buidl/d239e5.md
- 次の章: https://cardene.dev/books/blackrock-buidl/bb94ee.md
- 公開日: 2025-07-12
- 更新日: 2025-07-12
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## 概要

**TokenPartitionsLibrary**は、パーティション化されたトークン（例：発行日や属性が異なるトークン）の残高管理と操作ロジックを提供するライブラリです。
トークンを異なる区分（パーティション）ごとに管理し、それぞれの残高を追跡、発行や送付（Transfer）といった操作をパーティション単位で実行する機能を提供します。

このライブラリは、**ERC20**のような単純な残高管理とは異なり、より複雑な証券トークンの要件に対応するために設計されています。
証券トークンは、ロックアップ期間、議決権の有無、税制上の扱いなど、発行された時期や条件によって異なる属性を持つことがあります。
このライブラリは、これらの異なる属性を持つトークン群を「**パーティション**」という単位で明確に区別して管理します。

例えば、2023年に発行されたトークン（パーティションA）と2024年に発行されたトークン（パーティションB）は、同じトークンシンボルであっても、このライブラリによって別々の残高として扱われます。

このライブラリは、**DSTokenPartitioned**のようなコントラクトから利用されることを想定しており、どのウォレットがどのパーティションのトークンをどれだけ保有しているか、という複雑なデータ構造の操作をカプセル化して安全かつ効率的に実行する役割を担います。
発行、送付、残高照会といったすべての操作が、パーティションを意識して行われます。

## 機能

* **パーティションごとのトークン発行**
    * 発行時の情報（発行日や投資家の国籍など）に基づいて適切なパーティションを決定し、そのパーティションに対してトークンを発行します。
* **パーティション単位での残高管理**
    * ウォレットアドレスごと、投資家IDごとに、どのパーティションのトークンをどれだけ保有しているかを正確に追跡・管理します。
* **パーティション横断的なトークン送付**
    * 送付したいトークンの総量を指定すると、送金元が保有する複数のパーティションから自動的にトークンを引き出して送付します。
* **パーティション指定でのトークン送付**
    * 送付するパーティションと量を明示的に指定してトークンを送付します。
* **コンプライアンスサービスとの連携**
    * トークンを送付する時、関連するコンプライアンスサービスと連携して各パーティションで送付が許可されているトークン量を確認します。

## フロー

### パーティションごとのトークン発行 (issueTokensCustom)

```mermaid
sequenceDiagram
    participant Caller as 呼び出し元 (DSTokenPartitioned)
    participant TPL as TokenPartitionsLibrary
    participant RS as IDSRegistryService
    participant PM as IDSPartitionsManager
    participant LM as IDSLockManagerPartitioned

    Caller->>+TPL: issueTokensCustom(to, value, issuanceTime, ...)
    Note right of TPL: トークン発行処理を開始します。

    TPL->>+RS: getInvestor(to) / getCountry(investor)
    Note right of RS: 受け取り手('to')のウォレットアドレスから<br>投資家IDと国籍情報を取得します。
    RS-->>-TPL: 投資家IDと国籍を返します。
    
    TPL->>+PM: ensurePartition(issuanceTime, countryCompliance)
    Note right of PM: 発行日時と国籍情報に基づいて、<br>今回の発行に最適なパーティションIDを決定します。<br>必要であれば新しいパーティションを作成します。
    PM-->>-TPL: パーティションID (bytes32形式) を返します。
    
    Note right of TPL: `IssueByPartition`イベントを発行し、<br>どのパーティションに発行されたかを記録します。
    
    TPL->>TPL: transferPartition(from: 0x0, to, value, partition)
    Note right of TPL: 内部の残高更新関数を呼び出し、<br>発行元をゼロアドレスとして、受け取り手の<br>パーティション残高を増加させます。
    
    loop ロックアップ設定のループ
        Note right of TPL: 指定されたロックアップ情報を処理します。
        TPL->>+LM: createLockForInvestor(investor, valueLocked, ...)
        Note right of LM: 指定された量のトークンに対して、<br>特定のパーティションにロックを設定します。
        LM-->>-TPL: ロック設定成功を返します。
    end
    
    TPL-->>-Caller: 全ての処理が完了し、成功を返します。
```

### パーティション横断的なトークン送付 (transferPartitions)

```mermaid
sequenceDiagram
    participant Caller as 呼び出し元 (DSTokenPartitioned)
    participant TPL as TokenPartitionsLibrary
    participant SkipCheck as shouldSkipComplianceCheck
    participant CS as IDSComplianceServicePartitioned
    
    Caller->>+TPL: transferPartitions(from, to, value)
    Note right of TPL: 指定された総量のトークン送付処理を開始します。
    
    TPL->>+SkipCheck: shouldSkipComplianceCheck(from, to)
    Note right of SkipCheck: 送付元と送付先が同一投資家であるなど、<br>特定の条件下でコンプライアンスチェックを<br>省略できるか判断します。
    SkipCheck-->>-TPL: チェックを省略するかどうかの結果 (bool) を返します。

    loop 送付元('from')が保有する全パーティションに対するループ
        Note right of TPL: 送付すべき残量がある限り、<br>保有パーティションを一つずつ処理します。
        
        alt コンプライアンスチェックが必要な場合
            TPL->>+CS: getComplianceTransferableTokens(from, to, partition)
            Note right of CS: このパーティションで、コンプライアンス的に<br>送付が許可されているトークン量を計算します。
            CS-->>-TPL: 送付可能量を返します。
        end
        
        Note right of TPL: このパーティションから実際に送付する量を<br>(送付可能量と送付要求量の小さい方で)計算します。
        
        TPL->>TPL: transferPartition(from, to, transferable, partition)
        Note right of TPL: 実際の残高更新関数を呼び出し、<br>送付元と送付先のパーティション残高を更新し、<br>`TransferByPartition`イベントを発行します。
    end
    
    Note right of TPL: ループ終了後、要求された総量('value')が<br>すべて送付されたか(残量が0か)を検証します。
    TPL-->>-Caller: 全ての処理が完了し、成功を返します。
```

## コード

```sol
pragma solidity ^0.8.13;

import "../utils/CommonUtils.sol";
import "../compliance/IDSComplianceServicePartitioned.sol";
import "../compliance/IDSLockManagerPartitioned.sol";
import "../registry/IDSRegistryService.sol";
import "../compliance/IDSComplianceConfigurationService.sol";
import "../compliance/IDSPartitionsManager.sol";
import "../omnibus/IDSOmnibusTBEController.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";

//SPDX-License-Identifier: UNLICENSED
library TokenPartitionsLibrary {
    using SafeMath for uint256;

    uint256 internal constant COMPLIANCE_SERVICE = 0;
    uint256 internal constant REGISTRY_SERVICE = 1;
    uint256 internal constant OMNIBUS_TBE_CONTROLLER = 2;

    event IssueByPartition(address indexed to, uint256 value, bytes32 indexed partition);
    event TransferByPartition(address indexed from, address indexed to, uint256 value, bytes32 indexed partition);
    struct AddressPartitions {
        uint256 count;
        mapping(bytes32 => uint256) toIndex;
        mapping(uint256 => bytes32) partitions;
        mapping(bytes32 => uint256) balances;
    }

    struct TokenPartitions {
        mapping(address => AddressPartitions) walletPartitions;
        mapping(string => mapping(bytes32 => uint256)) investorPartitionsBalances;
    }

    function issueTokensCustom(
        TokenPartitions storage self,
        IDSRegistryService _registry,
        IDSComplianceConfigurationService _compConf,
        IDSPartitionsManager _partitionsManager,
        IDSLockManagerPartitioned _lockManager,
        address _to,
        uint256 _value,
        uint256 _issuanceTime,
        uint256[] memory _valuesLocked,
        string memory _reason,
        uint64[] memory _releaseTimes
    ) public returns (bool) {
        string memory investor = _registry.getInvestor(_to);
        string memory country = _registry.getCountry(investor);
        bytes32 partition = _partitionsManager.ensurePartition(_issuanceTime, _compConf.getCountryCompliance(country));
        emit IssueByPartition(_to, _value, partition);
        transferPartition(self, _registry, address(0), _to, _value, partition);
        uint256 totalLocked = 0;
        for (uint256 i = 0; i < _valuesLocked.length; i++) {
            totalLocked += _valuesLocked[i];
            _lockManager.createLockForInvestor(investor, _valuesLocked[i], 0, _reason, _releaseTimes[i], partition);
        }
        require(totalLocked <= _value, "valueLocked must be smaller than value");

        return true;
    }

    function issueTokensWithNoCompliance(
        TokenPartitions storage self,
        IDSRegistryService _registry,
        IDSComplianceConfigurationService _compConf,
        IDSPartitionsManager _partitionsManager,
        address _to,
        uint256 _value,
        uint256 _issuanceTime
    ) public returns (bool) {
        string memory investor = _registry.getInvestor(_to);
        string memory country = _registry.getCountry(investor);
        bytes32 partition = _partitionsManager.ensurePartition(_issuanceTime, _compConf.getCountryCompliance(country));
        emit IssueByPartition(_to, _value, partition);
        transferPartition(self, _registry, address(0), _to, _value, partition);
        return true;
    }

    function setPartitionToAddressImpl(TokenPartitions storage self, address _who, uint256 _index, bytes32 _partition) internal returns (bool) {
        self.walletPartitions[_who].partitions[_index] = _partition;
        self.walletPartitions[_who].toIndex[_partition] = _index;
        return true;
    }

    function addPartitionToAddress(TokenPartitions storage self, address _who, bytes32 _partition) internal {
        uint256 partitionCount = self.walletPartitions[_who].count;
        setPartitionToAddressImpl(self, _who, self.walletPartitions[_who].count, _partition);
        self.walletPartitions[_who].count = SafeMath.add(partitionCount, 1);
    }

    function removePartitionFromAddress(TokenPartitions storage self, address _from, bytes32 _partition) internal {
        uint256 oldIndex = self.walletPartitions[_from].toIndex[_partition];
        uint256 lastPartitionIndex = SafeMath.sub(self.walletPartitions[_from].count, 1);
        bytes32 lastPartition = self.walletPartitions[_from].partitions[lastPartitionIndex];

        setPartitionToAddressImpl(self, _from, oldIndex, lastPartition);

        delete self.walletPartitions[_from].partitions[lastPartitionIndex];
        delete self.walletPartitions[_from].toIndex[_partition];
        delete self.walletPartitions[_from].balances[_partition];
        self.walletPartitions[_from].count = SafeMath.sub(self.walletPartitions[_from].count, 1);
    }

    function transferPartition(TokenPartitions storage self, IDSRegistryService _registry, address _from, address _to, uint256 _value, bytes32 _partition) public {
        if (_from != address(0)) {
            self.walletPartitions[_from].balances[_partition] = SafeMath.sub(self.walletPartitions[_from].balances[_partition], _value);
            updateInvestorPartitionBalance(self, _registry, _from, _value, CommonUtils.IncDec.Decrease, _partition);
            if (self.walletPartitions[_from].balances[_partition] == 0) {
                removePartitionFromAddress(self, _from, _partition);
            }
        }

        if (_to != address(0)) {
            if (self.walletPartitions[_to].balances[_partition] == 0 && _value > 0) {
                addPartitionToAddress(self, _to, _partition);
            }
            self.walletPartitions[_to].balances[_partition] += _value;
            updateInvestorPartitionBalance(self, _registry, _to, _value, CommonUtils.IncDec.Increase, _partition);
        }
        emit TransferByPartition(_from, _to, _value, _partition);
    }

    function transferPartitions(TokenPartitions storage self, address[] memory _services, address _from, address _to, uint256 _value) public returns (bool) {
        uint256 partitionCount = partitionCountOf(self, _from);
        uint256 index = 0;
        bool skipComplianceCheck = shouldSkipComplianceCheck(IDSRegistryService(_services[REGISTRY_SERVICE]),
            IDSOmnibusTBEController(_services[OMNIBUS_TBE_CONTROLLER]), _from, _to);
        while (_value > 0 && index < partitionCount) {
            bytes32 partition = partitionOf(self, _from, index);
            uint256 transferableInPartition = skipComplianceCheck
                ? self.walletPartitions[_from].balances[partition]
                : IDSComplianceServicePartitioned(_services[COMPLIANCE_SERVICE]).getComplianceTransferableTokens(_from, block.timestamp, _to, partition);
            uint256 transferable = Math.min(_value, transferableInPartition);
            if (transferable > 0) {
                if (self.walletPartitions[_from].balances[partition] == transferable) {
                    unchecked {
                        --index;
                        --partitionCount;
                    }
                }
                transferPartition(self, IDSRegistryService(_services[REGISTRY_SERVICE]), _from, _to, transferable, partition);
                _value -= transferable;
            }
            unchecked {
                ++index;
            }
        }

        require(_value == 0);

        return true;
    }

    function transferPartitions(
        TokenPartitions storage self,
        address[] memory _services,
        address _from,
        address _to,
        uint256 _value,
        bytes32[] memory _partitions,
        uint256[] memory _values
    ) public returns (bool) {
        require(_partitions.length == _values.length);
        bool skipComplianceCheck = shouldSkipComplianceCheck(IDSRegistryService(_services[REGISTRY_SERVICE]),
            IDSOmnibusTBEController(_services[OMNIBUS_TBE_CONTROLLER]), _from, _to);
        for (uint256 index = 0; index < _partitions.length; ++index) {
            if (!skipComplianceCheck) {
                require(_values[index] <= IDSComplianceServicePartitioned(_services[COMPLIANCE_SERVICE]).getComplianceTransferableTokens(_from, block.timestamp, _to, _partitions[index]));
            }
            transferPartition(self, IDSRegistryService(_services[REGISTRY_SERVICE]), _from, _to, _values[index], _partitions[index]);
            _value -= _values[index];
        }

        require(_value == 0);
        return true;
    }

    function balanceOfByPartition(TokenPartitions storage self, address _who, bytes32 _partition) internal view returns (uint256) {
        return self.walletPartitions[_who].balances[_partition];
    }

    function balanceOfInvestorByPartition(TokenPartitions storage self, string memory _id, bytes32 _partition) internal view returns (uint256) {
        return self.investorPartitionsBalances[_id][_partition];
    }

    function partitionCountOf(TokenPartitions storage self, address _who) internal view returns (uint256) {
        return self.walletPartitions[_who].count;
    }

    function partitionOf(TokenPartitions storage self, address _who, uint256 _index) internal view returns (bytes32) {
        return self.walletPartitions[_who].partitions[_index];
    }

    function updateInvestorPartitionBalance(TokenPartitions storage self, IDSRegistryService _registry, address _wallet, uint256 _value, CommonUtils.IncDec _increase, bytes32 _partition)
        internal
        returns (bool)
    {
        string memory investor = _registry.getInvestor(_wallet);
        if (!CommonUtils.isEmptyString(investor)) {
            uint256 balance = self.investorPartitionsBalances[investor][_partition];
            if (_increase == CommonUtils.IncDec.Increase) {
                balance = SafeMath.add(balance, _value);
            } else {
                balance = SafeMath.sub(balance, _value);
            }
            self.investorPartitionsBalances[investor][_partition] = balance;
        }
        return true;
    }

    function shouldSkipComplianceCheck(IDSRegistryService _registry, IDSOmnibusTBEController _omnibusTBEController, address _from, address _to) internal view returns (bool) {
        return CommonUtils.isEqualString(_registry.getInvestor(_from), _registry.getInvestor(_to)) ||
            (address(_omnibusTBEController) != address(0) && (_omnibusTBEController.getOmnibusWallet() == _from ||
                _omnibusTBEController.getOmnibusWallet() == _to));
    }
}
```

## 変数

### `COMPLIANCE_SERVICE`

```sol
uint256 internal constant COMPLIANCE_SERVICE = 0;
```

`transferPartitions`関数などに渡される`address[] memory _services`というアドレス配列において、コンプライアンスサービス（Compliance Service）コントラクトのアドレスが格納されているインデックスが `0` であることを示す定数。

トークンを送付する時に、その取引が規制やルールに準拠しているかを確認する必要があります。
その確認ロジックを持つのがコンプライアンスサービスコントラクトです。
コード内で`_services[0]`と直接記述する代わりに`_services[COMPLIANCE_SERVICE]`と書くことで、`0`という数字がコンプライアンスサービスを指していることが一目瞭然となり、コードの可読性と保守性が大幅に向上します。

### `REGISTRY_SERVICE`

```sol
uint256 internal constant REGISTRY_SERVICE = 1;
```

`_services`アドレス配列において、レジストリサービス（Registry Service）コントラクトのアドレスが格納されているインデックスが`1`であることを示す定数。

レジストリサービスは、投資家のKYC（本人確認）情報やウォレットアドレスと投資家IDの紐付けなどを管理するコントラクトです。
このライブラリでは、例えばトークンを送付する時に、送付元と送付先が同一投資家であるかを確認したり、投資家単位での残高を更新したりするためにこのサービスコントラクトにアクセスする必要があります。

### `OMNIBUS_TBE_CONTROLLER`

```sol
uint256 internal constant OMNIBUS_TBE_CONTROLLER = 2;
```

`_services`アドレス配列において、オムニバスTBEコントローラー（Omnibus TBE Controller）コントラクトのアドレスが格納されているインデックスが`2`であることを示す定数。

オムニバスTBEコントローラーは、多数の投資家の資産をまとめて管理するオムニバスウォレットの運用を制御します。
このライブラリでは、`shouldSkipComplianceCheck`関数内で、取引の当事者がオムニバスウォレットであるかどうかを判断するためにこのコントローラーの情報を使用します。
オムニバスウォレットが関与する取引は、通常の投資家間の取引とは異なるコンプライアンスルールが適用されることがあるため、このチェックが必要になります。

### `AddressPartitions`

```sol
struct AddressPartitions {
    uint256 count;
    mapping(bytes32 => uint256) toIndex;
    mapping(uint256 => bytes32) partitions;
    mapping(bytes32 => uint256) balances;
}
```

特定のウォレットアドレスが保有するパーティション情報を管理する構造体。

- `count`
    - そのアドレスが保有しているパーティションの総数。
- `toIndex`
    - パーティションID (`bytes32`) から、そのパーティションが`partitions`配列のどのインデックスに格納されているかをマッピングします。
    - これにより、特定のパーティション情報へ高速にアクセスできます。
- `partitions`
    - インデックス番号からパーティションID (`bytes32`) へマッピングします。
    - これにより、アドレスが保有する全パーティションをループで列挙することが可能になります。
- `balances`
    - パーティションID (`bytes32`) から、そのパーティションのトークン残高へマッピングします。

### `TokenPartitions`

```sol
struct TokenPartitions {
    mapping(address => AddressPartitions) walletPartitions;
    mapping(string => mapping(bytes32 => uint256)) investorPartitionsBalances;
}
```

ライブラリ全体のデータストレージを定義する最上位の構造体。

この構造体型の`storage`変数が、ライブラリを利用するコントラクトのストレージに配置されます。
- `walletPartitions`
    - ウォレットアドレスをキーとして、そのアドレスのパーティション情報（`AddressPartitions`構造体）をマッピングします。
- `investorPartitionsBalances`
    - 投資家ID（`string`）をキーとして、さらにパーティションIDをキーとする、二重のマッピング構造。
    - これにより、ウォレット単位だけでなく、投資家単位でのパーティションごとの残高も管理できます。

## イベント

### `IssueByPartition`

```sol
event IssueByPartition(address indexed to, uint256 value, bytes32 indexed partition);
```

パーティション化されたトークンが発行されたときに発行されるイベント。

- `to`
    - トークンを受け取るウォレットアドレス。
- `value`
    - 発行されたトークンの量。
- `partition`
    - トークンが発行されたパーティションのID。

`to`と`partition`はインデックス化されており、これらの値をフィルタリングしてイベントを高速に検索できます。

### `TransferByPartition`

```sol
event TransferByPartition(address indexed from, address indexed to, uint256 value, bytes32 indexed partition);
```

パーティション化されたトークンが送付（Transfer）されたときに発行されるイベント。

- `from`
    - トークンを送付したウォレットアドレス。
    - 発行時は`address(0)`になります。
- `to`
    - トークンを受け取ったウォレットアドレス。
- `value`
    - 送付されたトークンの量。
- `partition`
    - トークンが送付されたパーティションのID。

`from`, `to`, `partition`はインデックス化されており、これらの値をフィルタリングしてイベントを高速に検索できます。

## 関数

### `issueTokensCustom`

```sol
function issueTokensCustom(
    TokenPartitions storage self,
    IDSRegistryService _registry,
    IDSComplianceConfigurationService _compConf,
    IDSPartitionsManager _partitionsManager,
    IDSLockManagerPartitioned _lockManager,
    address _to,
    uint256 _value,
    uint256 _issuanceTime,
    uint256[] memory _valuesLocked,
    string memory _reason,
    uint64[] memory _releaseTimes
) public returns (bool) {
    string memory investor = _registry.getInvestor(_to);
    string memory country = _registry.getCountry(investor);
    bytes32 partition = _partitionsManager.ensurePartition(_issuanceTime, _compConf.getCountryCompliance(country));
    emit IssueByPartition(_to, _value, partition);
    transferPartition(self, _registry, address(0), _to, _value, partition);
    uint256 totalLocked = 0;
    for (uint256 i = 0; i < _valuesLocked.length; i++) {
        totalLocked += _valuesLocked[i];
        _lockManager.createLockForInvestor(investor, _valuesLocked[i], 0, _reason, _releaseTimes[i], partition);
    }
    require(totalLocked <= _value, "valueLocked must be smaller than value");

    return true;
}
```

パーティション化されたトークンを発行して同時にロックアップ設定も行う関数。

この関数は、トークンを発行する際の中心的なロジックを提供します。
まず、**IDSRegistryService**に準拠したコントラクトから受け取り手(`_to`)の投資家IDと国籍を取得します。
次に、その情報と発行日時(`_issuanceTime`)を**IDSPartitionsManager**に準拠したコントラクトに渡し、今回の発行に適したパーティションIDを決定・取得します。
`IssueByPartition`イベントを発行した後、内部関数`transferPartition`を呼び出して、発行元を`address(0)`として指定し、受け取り手のウォレットと投資家IDの残高を更新します。
最後に、引数で指定されたロックアップ情報に基づき、**IDSLockManagerPartitioned**に準拠したコントラクトを呼び出して、発行されたトークンの一部または全部にロックを設定します。

**引数**

-  `self`
    - ライブラリが操作するストレージデータ（`TokenPartitions`構造体）への参照。
- `_registry`
    - 投資家情報を管理する**IDSRegistryService**に準拠したコントラクトのインスタンス。
- `_compConf`
    - コンプライアンス設定を管理する**IDSComplianceConfigurationService**に準拠したコントラクトのインスタンス。
- _partitionsManager`
    - パーティションの作成・管理を行う**IDSPartitionsManager**に準拠したコントラクトのインスタンス。
- `_lockManager`
    - トークンのロックを管理する**IDSLockManagerPartitioned**に準拠したコントラクトのインスタンス。
- `_to`
    - 発行されたトークンを受け取るウォレットアドレス。
- `_value`
    - 発行するトークンの総量。
- `_issuanceTime`
    - トークンの発行日時（Unixタイムスタンプ）。パーティション決定に使用されます。
- `_valuesLocked`
    - ロックアップするトークン量の配列。
- `_reason`
    - ロックアップの理由を示す文字列。
- `_releaseTimes`
    - 各ロックアップが解除される日時の配列。

**戻り値**

- `bool`
    - 処理が正常に完了した場合に`true`を返します。

### `issueTokensWithNoCompliance`

```sol
function issueTokensWithNoCompliance(
    TokenPartitions storage self,
    IDSRegistryService _registry,
    IDSComplianceConfigurationService _compConf,
    IDSPartitionsManager _partitionsManager,
    address _to,
    uint256 _value,
    uint256 _issuanceTime
) public returns (bool) {
    string memory investor = _registry.getInvestor(_to);
    string memory country = _registry.getCountry(investor);
    bytes32 partition = _partitionsManager.ensurePartition(_issuanceTime, _compConf.getCountryCompliance(country));
    emit IssueByPartition(_to, _value, partition);
    transferPartition(self, _registry, address(0), _to, _value, partition);
    return true;
}
```

コンプライアンスチェックを伴わずにパーティション化トークンを発行する関数。

`issueTokensCustom`と似ていますが、トークンのロックアップ設定を行いません。
この関数は、呼び出し元のトークンコントラクト側で、通常のコンプライアンス検証プロセスをスキップする特定のシナリオ（例：内部的な残高調整など）で使用されることを想定しています。
処理の流れは`issueTokensCustom`と同様に、適切なパーティションを決定し、イベントを発行、そして`transferPartition`を呼び出して残高を更新します。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_registry`
    - **IDSRegistryService**に準拠したコントラクトのインスタンス。
- `_compConf`
    - **IDSComplianceConfigurationService**に準拠したコントラクトのインスタンス。
- `_partitionsManager`
    - **IDSPartitionsManager**に準拠したコントラクトのインスタンス。
- `_to`
    - 発行されたトークンを受け取るウォレットアドレス。
- `_value`
    - 発行するトークンの総量。
- `_issuanceTime`
    - トークンの発行日時（Unixタイムスタンプ）。

**戻り値**

- `bool`
    - 処理が正常に完了した場合に`true`を返します。

### `setPartitionToAddressImpl`

```sol
function setPartitionToAddressImpl(TokenPartitions storage self, address _who, uint256 _index, bytes32 _partition) internal returns (bool) {
    self.walletPartitions[_who].partitions[_index] = _partition;
    self.walletPartitions[_who].toIndex[_partition] = _index;
    return true;
}
```

特定アドレスのパーティション情報を直接設定する低レベルな内部関数。

このヘルパー関数は、`AddressPartitions`構造体内の2つのマッピングを同時に更新します。`partitions`マッピング（インデックスからパーティションIDへ）と`toIndex`マッピング（パーティションIDからインデックスへ）の整合性を保ちます。
`addPartitionToAddress`や`removePartitionFromAddress`といった、より高レベルな関数から呼び出されます。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_who`
    - 対象のウォレットアドレス。
- `_index`
    - 設定するパーティションのインデックス番号。
- `_partition`
    - 設定するパーティションのID (`bytes32`)。

**戻り値**

- `bool`
    - 処理が正常に完了した場合に`true`を返します。

### `addPartitionToAddress`

```sol
function addPartitionToAddress(TokenPartitions storage self, address _who, bytes32 _partition) internal {
    uint256 partitionCount = self.walletPartitions[_who].count;
    setPartitionToAddressImpl(self, _who, self.walletPartitions[_who].count, _partition);
    self.walletPartitions[_who].count = SafeMath.add(partitionCount, 1);
}
```

アドレスに新しいパーティション情報を追加する内部関数。

あるウォレットアドレスが、それまで保有していなかった新しいパーティションのトークンを初めて受け取った時に呼び出されます。
内部で`setPartitionToAddressImpl`を呼び出してパーティション情報を追加し、そのアドレスが保有するパーティションの総数を示す`count`を1つ増やします。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_who`
    - パーティション情報を追加するウォレットアドレス。
- `_partition`
    - 追加する新しいパーティションのID。

### `removePartitionFromAddress`

```sol
function removePartitionFromAddress(TokenPartitions storage self, address _from, bytes32 _partition) internal {
    uint256 oldIndex = self.walletPartitions[_from].toIndex[_partition];
    uint256 lastPartitionIndex = SafeMath.sub(self.walletPartitions[_from].count, 1);
    bytes32 lastPartition = self.walletPartitions[_from].partitions[lastPartitionIndex];

    setPartitionToAddressImpl(self, _from, oldIndex, lastPartition);

    delete self.walletPartitions[_from].partitions[lastPartitionIndex];
    delete self.walletPartitions[_from].toIndex[_partition];
    delete self.walletPartitions[_from].balances[_partition];
    self.walletPartitions[_from].count = SafeMath.sub(self.walletPartitions[_from].count, 1);
}
```

アドレスからパーティション情報を削除する内部関数。

あるウォレットアドレスの特定のパーティション残高が0になったときに呼び出されます。
この関数は、配列に穴を開けずに効率的に要素を削除する「**Swap and Pop**」という手法を用いています。
具体的には、削除対象のパーティションを配列の最後にあるパーティションで上書きし、その後、配列の最後尾と関連データを削除します。
これにより、データ構造の整合性を保ちつつ、パーティション情報をクリーンアップします。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_from`
    - パーティション情報を削除するウォレットアドレス。
- `_partition`
    - 削除するパーティションのID。

### `transferPartition`

```sol
function transferPartition(TokenPartitions storage self, IDSRegistryService _registry, address _from, address _to, uint256 _value, bytes32 _partition) public {
    if (_from != address(0)) {
        self.walletPartitions[_from].balances[_partition] = SafeMath.sub(self.walletPartitions[_from].balances[_partition], _value);
        updateInvestorPartitionBalance(self, _registry, _from, _value, CommonUtils.IncDec.Decrease, _partition);
        if (self.walletPartitions[_from].balances[_partition] == 0) {
            removePartitionFromAddress(self, _from, _partition);
        }
    }

    if (_to != address(0)) {
        if (self.walletPartitions[_to].balances[_partition] == 0 && _value > 0) {
            addPartitionToAddress(self, _to, _partition);
        }
        self.walletPartitions[_to].balances[_partition] += _value;
        updateInvestorPartitionBalance(self, _registry, _to, _value, CommonUtils.IncDec.Increase, _partition);
    }
    emit TransferByPartition(_from, _to, _value, _partition);
}
```

単一のパーティション内でトークン残高を更新する中心的な関数。

この関数は、発行や送付（Transfer）の際の実際の残高操作を担います。
送付元(`_from`)が指定されている場合（`address(0)`でない場合）、そのウォレットと投資家IDのパーティション残高を減らします。
残高が0になった場合は`removePartitionFromAddress`を呼び出してパーティション情報をクリーンアップします。
送付先(`_to`)が指定されている場合、そのウォレットと投資家IDのパーティション残高を増やします。
送付先がそのパーティションを初めて受け取る場合は`addPartitionToAddress`を呼び出します。
最後に`TransferByPartition`イベントを発行して、この操作をブロックチェーン上に記録します。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_registry`
    - **IDSRegistryService**に準拠するコントラクトのインスタンス。
    - 投資家IDの取得に使用します。
- `_from`
    - トークンを送付するウォレットアドレス。
    - 発行時は`address(0)`。
- `_to`
    - トークンを受け取るウォレットアドレス。
- `_value`
    - 送付するトークンの量。
- `_partition`
    - 操作対象のパーティションID。

### `transferPartitions`

```sol
function transferPartitions(TokenPartitions storage self, address[] memory _services, address _from, address _to, uint256 _value) public returns (bool) {
    uint256 partitionCount = partitionCountOf(self, _from);
    uint256 index = 0;
    bool skipComplianceCheck = shouldSkipComplianceCheck(IDSRegistryService(_services[REGISTRY_SERVICE]),
        IDSOmnibusTBEController(_services[OMNIBUS_TBE_CONTROLLER]), _from, _to);
    while (_value > 0 && index < partitionCount) {
        bytes32 partition = partitionOf(self, _from, index);
        uint256 transferableInPartition = skipComplianceCheck
            ? self.walletPartitions[_from].balances[partition]
            : IDSComplianceServicePartitioned(_services[COMPLIANCE_SERVICE]).getComplianceTransferableTokens(_from, block.timestamp, _to, partition);
        uint256 transferable = Math.min(_value, transferableInPartition);
        if (transferable > 0) {
            if (self.walletPartitions[_from].balances[partition] == transferable) {
                unchecked {
                    --index;
                    --partitionCount;
                }
            }
            transferPartition(self, IDSRegistryService(_services[REGISTRY_SERVICE]), _from, _to, transferable, partition);
            _value -= transferable;
        }
        unchecked {
            ++index;
        }
    }

    require(_value == 0);

    return true;
}
```

トークン総量を指定して送付元が持つ複数のパーティションから自動的に引き出して送付（Transfer）する関数。

この関数は、送付元のウォレットが保有する全パーティションをループ処理します。
各パーティションについて、コンプライアンス的に送付可能なトークン量を**IDSComplianceServicePartitioned**に準拠したコントラクトに問い合わせて取得します（`shouldSkipComplianceCheck`が`false`の場合）。
そして、送付すべき総量に達するまで、各パーティションからトークンを引き出して`transferPartition`を呼び出して残高を更新します。
送付が完了したら、要求された総量がすべて送付されたことを`require`で検証します。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_services`
    - 関連サービスコントラクトのアドレス配列。
- `_from`
    - トークンを送付するウォレットアドレス。
- `_to`
    - トークンを受け取るウォレットアドレス。
- `_value`
    - 送付するトークンの総量。

**戻り値**

- `bool`
    - 処理が正常に完了した場合に`true`を返します。

### `transferPartitions`

```sol
function transferPartitions(
    TokenPartitions storage self,
    address[] memory _services,
    address _from,
    address _to,
    uint256 _value,
    bytes32[] memory _partitions,
    uint256[] memory _values
) public returns (bool) {
    require(_partitions.length == _values.length);
    bool skipComplianceCheck = shouldSkipComplianceCheck(IDSRegistryService(_services[REGISTRY_SERVICE]),
        IDSOmnibusTBEController(_services[OMNIBUS_TBE_CONTROLLER]), _from, _to);
    for (uint256 index = 0; index < _partitions.length; ++index) {
        if (!skipComplianceCheck) {
            require(_values[index] <= IDSComplianceServicePartitioned(_services[COMPLIANCE_SERVICE]).getComplianceTransferableTokens(_from, block.timestamp, _to, _partitions[index]));
        }
        transferPartition(self, IDSRegistryService(_services[REGISTRY_SERVICE]), _from, _to, _values[index], _partitions[index]);
        _value -= _values[index];
    }

    require(_value == 0);
    return true;
}
```

送付するパーティションと量を明示的に指定して送付（Transfer）する関数。

この関数は、呼び出し元がどのパーティションからどれだけの量を送付するかを正確に制御したい場合に使用されます。
引数で渡されたパーティションの配列と量の配列をループ処理し、各要素についてコンプライアンスチェック（必要な場合）を行った後、`transferPartition`を呼び出して残高を更新します。
最終的に、指定された総量がすべて送付されたことを検証します。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_services`
    - 関連サービスコントラクトのアドレス配列。
- `_from`
    - トークンを送付するウォレットアドレス。
- `_to`
    - トークンを受け取るウォレットアドレス。
- `_value`
    - 送付するトークンの総量（検証用）。
- `_partitions`
    - 送付元のパーティションIDの配列。
- `_values`
    - 上記各パーティションから送付するトークン量の配列。

**戻り値**

- `bool`
    - 処理が正常に完了した場合に`true`を返します。

### `balanceOfByPartition`

```sol
function balanceOfByPartition(TokenPartitions storage self, address _who, bytes32 _partition) internal view returns (uint256) {
    return self.walletPartitions[_who].balances[_partition];
}
```

特定アドレスの指定されたパーティションにおける残高を返す関数。

`AddressPartitions`構造体内の`balances`マッピングから、指定されたウォレットアドレス(`_who`)とパーティションID(`_partition`)に対応する残高を直接返します。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_who`
    - 残高を照会するウォレットアドレス。
- `_partition`
    - 残高を照会するパーティションのID。

**戻り値**

- `uint256`
    - 指定されたパーティションのトークン残高。

### `balanceOfInvestorByPartition`

```sol
function balanceOfInvestorByPartition(TokenPartitions storage self, string memory _id, bytes32 _partition) internal view returns (uint256) {
    return self.investorPartitionsBalances[_id][_partition];
}
```

特定投資家IDの指定されたパーティションにおける残高を返す関数。

`TokenPartitions`構造体内の`investorPartitionsBalances`マッピングから、指定された投資家ID(`_id`)とパーティションID(`_partition`)に対応する残高を直接返します。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_id`
    - 残高を照会する投資家のID（文字列）。
- `_partition`
    - 残高を照会するパーティションのID。

**戻り値**

- `uint256`
    - 指定されたパーティションのトークン残高。

### `partitionCountOf`

```sol
function partitionCountOf(TokenPartitions storage self, address _who) internal view returns (uint256) {
    return self.walletPartitions[_who].count;
}
```

特定アドレスが保有しているパーティションの総数を返す関数。

`AddressPartitions`構造体内の`count`変数の値を返します。これにより、外部からあるウォレットがいくつの異なるパーティションを保有しているかを確認できます。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_who`
    - パーティション数を照会するウォレットアドレス。

**戻り値**

- `uint256`
    - 保有しているパーティションの総数。

### `partitionOf`

```sol
function partitionOf(TokenPartitions storage self, address _who, uint256 _index) internal view returns (bytes32) {
    return self.walletPartitions[_who].partitions[_index];
}
```

特定アドレスが保有するパーティションをインデックス指定で取得する関数。

`partitionCountOf`と組み合わせて使用することで、あるアドレスが保有する全てのパーティションIDをループで列挙することができます。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_who`
    - パーティションIDを照会するウォレットアドレス。
- `_index`
    - 取得したいパーティションのインデックス番号（0から`count-1`まで）。

**戻り値**

- `bytes32`
    - 指定されたインデックスに対応するパーティションID。

### `updateInvestorPartitionBalance`

```sol
function updateInvestorPartitionBalance(TokenPartitions storage self, IDSRegistryService _registry, address _wallet, uint256 _value, CommonUtils.IncDec _increase, bytes32 _partition)
    internal
    returns (bool)
{
    string memory investor = _registry.getInvestor(_wallet);
    if (!CommonUtils.isEmptyString(investor)) {
        uint256 balance = self.investorPartitionsBalances[investor][_partition];
        if (_increase == CommonUtils.IncDec.Increase) {
            balance = SafeMath.add(balance, _value);
        } else {
            balance = SafeMath.sub(balance, _value);
        }
        self.investorPartitionsBalances[investor][_partition] = balance;
    }
    return true;
}
```

投資家ID単位でのパーティション残高を更新する内部関数。

この関数は、`transferPartition`から呼び出され、ウォレット単位の残高更新と同時に投資家単位の残高も更新します。
**IDSRegistryService**に準拠したコントラクトからウォレットアドレスに紐づく投資家IDを取得し、その投資家の指定されたパーティションの残高を増減させます。

**引数**

- `self`
    - ライブラリが操作するストレージデータへの参照。
- `_registry`
    - **IDSRegistryService**に準拠したコントラクトのインスタンス。
- `_wallet`
    - 残高が変動したウォレットアドレス。
- `_value`
    - 変動したトークンの量。
- `_increase`
    - 残高を増加させるか減少させるかを示すフラグ (`Increase`または`Decrease`)。
- `_partition`
    - 操作対象のパーティションID。

**戻り値**

- `bool`
    - 処理が正常に完了した場合に`true`を返します。

### `shouldSkipComplianceCheck`

```sol
function shouldSkipComplianceCheck(IDSRegistryService _registry, IDSOmnibusTBEController _omnibusTBEController, address _from, address _to) internal view returns (bool) {
    return CommonUtils.isEqualString(_registry.getInvestor(_from), _registry.getInvestor(_to)) ||
        (address(_omnibusTBEController) != address(0) && (_omnibusTBEController.getOmnibusWallet() == _from ||
            _omnibusTBEController.getOmnibusWallet() == _to));
}
```

トークン送付（Transfer）時にコンプライアンスチェックをスキップできるか判断する内部関数。

`transferPartitions`関数内で呼び出され、特定の条件下で高コストなコンプライアンスチェックを省略するために使用されます。
以下のいずれかの条件を満たす場合に`true`を返します。

- 送付元と送付先のウォレットが、同じ投資家IDに紐づいている場合（同一投資家内での資産移動）。
- 送付元または送付先のいずれかが、登録されたオムニバスウォレットである場合。

**引数**

- `_registry`
    - **IDSRegistryService**に準拠したコントラクトのインスタンス。
- `_omnibusTBEController`
    - **IDSOmnibusTBEController**に準拠したコントラクトのインスタンス。
- `_from`
    - トークンを送付するウォレットアドレス。
- `_to`
    - トークンを受け取るウォレットアドレス。

**戻り値**

- `bool`
    - コンプライアンスチェックをスキップできる場合は`true`、それ以外は`false`を返します。
