Vishnuram Rajkumar
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # LIBRE Audit Findings - Vishnuram ## 01. [High] Admin cancellation of first order in queue will lead to failing of settling orders **File(s)**: [`SubscriptionBook.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/SubscriptionBook.sol) **Description**: Admin has privilege of cancelling order even after the tokens are locked for a particular order. In that case the orderId is removed from the queue. But in a special case after an order is cancelled, settle order functionality fails. ```solidity function settleOrders(uint256 _lastOrderId, uint256 _percentageToSettle, bytes32 _role) external override { ... if (_lastOrderId < nextOrderToSettle) { revert IOrderPipelineOrderAlreadySettledInCurrentRound(); } uint256[] memory allOrders = getIdsOrderFrom(nextOrderToSettle == 0 ? start : nextOrderToSettle, _lastOrderId); ... nextOrderToSettle = idsQueue[_lastOrderId].next; } ``` Let's take a scenario were there are five orders(1,2,3,4,5) 1. Admin first settles orders till 2. Queue is updated and `nextOrderToSettle` is updated to 3. 2. Later admin cancels the order 3 which updates the `start` variable in `idSorter` contract to 4 and orders queue look like (1,2,4,5). 3. Then admin wants to settle orders till 5, which should basically settle order 4 and 5. But since `nextOrderToSettle` is not updated, `settleOrders` function will fetch for orders from 3 to 5 which reverts because of `IdSorterToParamNotFound()` error. ```solidity function testSettleOrders() public { uint256 _amount = 1000; instrumentRegistry.updateAuditedNavPerShare( keccak256("LIBRE_FUND_ADMIN_ROLE"), subscriptionBook.instrumentId(), 1000 ); dealerRegistry.allowDealer(0x0, LIBRE_DEALER, LIBRE_INSTRUMENT, true); investorRegistry.allowInvestor(LIBRE_DEALER_ROLE, LIBRE_INVESTOR); paymentToken.mint(LIBRE_INVESTOR_WALLET, _amount); // 1000 dealerRegistry.allowDealer(0x0, LIBRE_DEALER, LIBRE_INSTRUMENT, true); investorRegistry.allowInvestor(LIBRE_DEALER_ROLE, LIBRE_INVESTOR_2); paymentToken.mint(LIBRE_INVESTOR_WALLET_2, _amount + 1000); // 2000 dealerRegistry.allowDealer(0x0, LIBRE_DEALER, LIBRE_INSTRUMENT, true); investorRegistry.allowInvestor(LIBRE_DEALER_ROLE, LIBRE_INVESTOR_3); paymentToken.mint(LIBRE_INVESTOR_WALLET_3, _amount + 100); // 1100 dealerRegistry.allowDealer(0x0, LIBRE_DEALER, LIBRE_INSTRUMENT, true); investorRegistry.allowInvestor(LIBRE_DEALER_ROLE, LIBRE_INVESTOR_4); paymentToken.mint(LIBRE_INVESTOR_WALLET_4, _amount + 200); // 1200 dealerRegistry.allowDealer(0x0, LIBRE_DEALER, LIBRE_INSTRUMENT, true); investorRegistry.allowInvestor(LIBRE_DEALER_ROLE, LIBRE_INVESTOR_5); paymentToken.mint(LIBRE_INVESTOR_WALLET_5, _amount - 100); // 900 // five investors create order, confirm and lock tokens vm.startPrank(LIBRE_INVESTOR_WALLET); uint256 orderId1 = subscriptionBook.investorCreateOrder(_amount); subscriptionBook.investorConfirmOrder(orderId1); paymentToken.approve(address(subscriptionBook), type(uint256).max); subscriptionBook.investorLockTokens(orderId1); vm.stopPrank(); vm.startPrank(LIBRE_INVESTOR_WALLET_2); uint256 orderId2 = subscriptionBook.investorCreateOrder(_amount + 1000); subscriptionBook.investorConfirmOrder(orderId2); paymentToken.approve(address(subscriptionBook), type(uint256).max); subscriptionBook.investorLockTokens(orderId2); vm.stopPrank(); vm.startPrank(LIBRE_INVESTOR_WALLET_3); uint256 orderId3 = subscriptionBook.investorCreateOrder(_amount + 100); subscriptionBook.investorConfirmOrder(orderId3); paymentToken.approve(address(subscriptionBook), type(uint256).max); subscriptionBook.investorLockTokens(orderId3); vm.stopPrank(); vm.startPrank(LIBRE_INVESTOR_WALLET_4); uint256 orderId4 = subscriptionBook.investorCreateOrder(_amount + 200); subscriptionBook.investorConfirmOrder(orderId4); paymentToken.approve(address(subscriptionBook), type(uint256).max); subscriptionBook.investorLockTokens(orderId4); vm.stopPrank(); vm.startPrank(LIBRE_INVESTOR_WALLET_5); uint256 orderId5 = subscriptionBook.investorCreateOrder(_amount - 100); subscriptionBook.investorConfirmOrder(orderId5); paymentToken.approve(address(subscriptionBook), type(uint256).max); subscriptionBook.investorLockTokens(orderId5); vm.stopPrank(); subscriptionBook.settleOrders(orderId2, 10000, keccak256("LIBRE_FUND_ADMIN_ROLE")); // admin settling orders till 2 subscriptionBook.adminCancelOrder(orderId3, keccak256("LIBRE_FUND_ADMIN_ROLE")); // admin cancelling order 3 subscriptionBook.settleOrders(orderId5, 10000, keccak256("LIBRE_FUND_ADMIN_ROLE")); // admin trying to settle orders till 5 but reverts } ``` While cancelling the order nextOrderToSettle is not updated. ```solidity function _afterCancelOrderCheck(uint256 _orderId, Order memory _order, uint256 _submitter) internal { ... if (_order.confirmed) { confirmedAmount -= _order.amount; confirmedAmountPerInvestor[_order.investorId] -= _order.amount; // If locked update the locked amount if (!_order.available) { amountLocked -= _order.amount; paymentToken.transfer(_order.beneficiary, _order.amount); removeId(_orderId); } } ... // @audit update the nextOrderToSettle // delete the order delete orders[_orderId]; emit OrderCanceled(_orderId, _submitter); } ``` **Recommendation(s)**: Consider updating the `nextOrderToSettle` variable while admin cancelling the order to resolve this issue. By setting the variable to next order id in queue if it is equal to order id which is getting cancelled. **Status**: Unresolved **Update from the client**: --- ## 02. [Low] Settled order is not marked done **File(s)**: [`SubscriptionBook.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/SubscriptionBook.sol) **Description**: There are four phases in Subscription Book contract which are order creation, order confirmation, locking tokens and settle orders. Two important parameters which track of each phases are `available` and `confirmed`. When order is `confirmed` it is set to `true` and when tokens are locked `available` is set to `false`. When an order is settled through `_instantSettlement` function, confirmed parameter is set to true correctly which means the order is marked true. But in case of `settleOrders` function this is not happening. ```solidity function settleOrders(uint256 _lastOrderId, uint256 _percentageToSettle, bytes32 _role) external override { ... if (orders[orderId].amount == 0) { lastEmptyOrder = orderId; amountOfEmptyOrders++; _decreaseInvestorOrders(order.investorId); // @audit order is not marked as done } ... } ``` **Recommendation(s)**: Consider to mark an settled order as done by setting `false` to `confirmed` parameter, so the Subscription process works as intended. As well as both `_instantSettlement` and `settleOrders` will follow same methodology. **Status**: Unresolved **Update from the client**: --- ## 03. [Low] Incorrect definition of `INITIAL_RESTRICTED_PERIOD_ALLOWANCE` constant variable **File(s)**: [`RedemptionBook.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/RedemptionBook.sol) **Description**: Incorrect definition of constant variables can lead to critical issues like reading wrong values from storage. In RedemptionBook contract `INITIAL_RESTRICTED_PERIOD_ALLOWANCE` is incorrectly defined with the same value of `INITIAL_SUBSCRIPTION_RESTRICTED_PERIOD_ALLOWANCE`. Through this wrong uint value is read to `allowedPercent` variable in `_calculateFeeDeduction` function. ```solidity contract RedemptionBook is Initializable, PermissionedContract, IdSorter, IRedemptionBook { ... bytes32 constant INITIAL_SUBSCRIPTION_RESTRICTED_PERIOD_ALLOWANCE = keccak256("INITIAL_SUBSCRIPTION_RESTRICTED_PERIOD_ALLOWANCE"); bytes32 constant INITIAL_SUBSCRIPTION_RESTRICTED_PERIOD_FEE = keccak256("INITIAL_SUBSCRIPTION_RESTRICTED_PERIOD_FEE"); bytes32 constant INITIAL_RESTRICTED_PERIOD_ALLOWANCE = keccak256("INITIAL_SUBSCRIPTION_RESTRICTED_PERIOD_ALLOWANCE"); // @audit value is clashing with INITIAL_SUBSCRIPTION_RESTRICTED_PERIOD_ALLOWANCE ... } ``` **Recommendation(s)**: Consider changing the value of `INITIAL_RESTRICTED_PERIOD_ALLOWANCE` to `keccak256("INITIAL_RESTRICTED_PERIOD_ALLOWANCE")` **Status**: Unresolved **Update from the client**: --- ## 04. [Best Practice] Missing Event Emission **File(s)**: [`EternalRegistryStorage.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/EternalRegistryStorage.sol) **Description**: `_setReservedKey` function in this contract helps to set a reserved key by restricting the key. Several registry contracts use this to set the default reserved keys. It is important to emit an event while this is happening. ```solidity function _setReservedKey(bytes32 _id, bytes32 _key) internal { internalKeys[_id][_key] = true; // @audit missing event emission } ``` **Recommendation(s)**: Consider creating a separate event for adding new reserved key, for example `AddedNewReservedKey(bytes32 indexed id, bytes32 indexed key)` and update the `_setReservedKey` function to emit that event. **Status**: Unresolved **Update from the client**: --- ## 05. [Best Practice] Presence of unused Variables **Files**: [`SecurityToken.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/SecurityToken.sol) [`InstrumentRegistry.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/registries/InstrumentRegistry.sol) **Description**: The presence of unused variables is generally considered a practice to be avoided, as they may lead to potential issues such as: - Increased computational costs (i.e., unnecessary gas consumption); - Reduced code readability; and - The possibility of bugs (e.g., when an explicit return statement is forgotten and return values are never assigned). The state variable `lifecycleContract` in the SecurityToken contract is not used throughout the contract. ```solidity contract SecurityToken is ISecurityToken, ERC20Upgradeable { ... // @audit unused address lifecycleContract; ... } ``` The state variables `subscriptionBookImp` and `redemptionBookImp` in the InstruemtnRegistry contract are not used throughput the contract. ```solidity contract InstrumentRegistry is BaseRegistry, IInstrumentRegistry { ... // @audit unused address public subscriptionBookImp; address public redemptionBookImp; ... } ``` **Recommendation(s)**: We recommend removing all unused variables from the codebase to enhance code quality and minimize the risk of errors or inefficiencies. **Status**: Unresolved **Update from the client**: ## 06. [Best Practice] Emitting address instead of index of the wallet **File(s)**: [`BaseUserRegistry.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/registries/BaseUserRegistry.sol) **Description**: `removeWallet` function emits the index of the wallet from the user's wallet address array. But emitting wallet address (`walletToDelete`) will be useful and clear. ```solidity function removeWallet(uint256 _index) external override { ... address walletToDelete = ownedWallets[_userId][_index]; ... emit WalletRemoved(_index); // @audit emit the address of the removed wallet ... } ``` **Recommendation**: Consider emitting address of wallet removed (`walletToDelete`) in `removeWallet` function. This provides better information for anyone monitoring or interacting with the smart contract. **Status**: Unresolved **Update from the client**: --- ## 07. [Best Practice] Verify whether the transfer was successful and the token balance after transfer using order amount **File(s)**: [`SubscriptionBook.sol`](https://github.com/NethermindEth/libre-platform-contracts/blob/e88db8da563a0acbe3bffa7af911714215759d4c/src/SubscriptionBook.sol) **Description**: At the locking tokens phase the ERC20 token is transfered from the `sender` to the `SubscriptionBook` contract. In some ERC20 tokens, if the transfer fails it won't revert instead returns false or it won't return anything like in USDT. In that case an order is locked without receiving the tokens. ```solidity function _afterLockOrderCheck(uint256 _orderId, Order memory _order, address _investorWallet, uint256 _submitter) internal { ... paymentToken.transferFrom(sender, address(this), _order.amount); // @audit-issue check the return value // @audit-issue verify the token balance before and after the transfer using order amount ... } ``` This applies in case of admin cancels an order. Payment tokens are sent to order `beneficiary` ```solidity function _afterCancelOrderCheck(uint256 _orderId, Order memory _order, uint256 _submitter) internal { ... if (_order.confirmed) { confirmedAmount -= _order.amount; confirmedAmountPerInvestor[_order.investorId] -= _order.amount; // If locked update the locked amount if (!_order.available) { amountLocked -= _order.amount; paymentToken.transfer(_order.beneficiary, _order.amount); // @audit-issue check the return value // @audit-issue verify the token balance before and after the transfer using order amount removeId(_orderId); } } ... } ``` **Recommendation(s)**: Consider using SafeERC20 functionalities for transfer and transferFrom. Also, consider comparing the contract's token balances before and after it.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully