xanoutas/solidity-security-findings huggingface dataset:
Upgraded Q -> 2 from #114 [1730392942076]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #114 as 2 risk. The relevant finding follows:

 ## [L-08] provided wrong data to `ReceivedCrossChainTx.to_handler` when `receive_cross_chain_msg` on `ChakraSettlement`.

`address(this)` provided as `to_handler` instead of `to_handler`.

https://github.com/code-423n4/2024-08-chakra/blob/main/solidity/settlement/contracts/ChakraSettlement.sol#L211

```solidity
// ...
        // struct ReceivedCrossChainTx {
        //     uint256 txid;
        //     string from_chain;
        //     string to_chain;
        //     uint256 from_address;
        //     uint256 from_handler;
        //     address to_handler;
        //     bytes payload;
        //     CrossChainMsgStatus status;
        // }
        receive_cross_txs[txid] = ReceivedCrossChainTx(
            txid,
            from_chain,
            contract_chain_name,
            from_address,
            from_handler,
>>>         address(this), 
            payload,
            CrossChainMsgStatus.Pending
        );
// ..
```

### Mitigation

provide `to_handler` to ReceivedCrossChainTx.to_handler`.

## [L-09] hardcoded `version` is provided when `coded.cairo` 's `encode_message` is called.

`version` is hardcoded instead of just accessing `message.version` from the params.

https://github.com/code-423n4/2024-08-chakra/blob/main/cairo/handler/src/codec.cairo#L95

```cairo
pub fn encode_message(message: Message) -> Array<u8>{
    
    // let message = Message{
    //     version: 1, 
    //     message_id: message_id.into(),
    //     payload_type: PayloadType::ERC20,
    //     payload: encode_transfer(transfer),
    // };
    let mut array_u8 = ArrayTrait::new();

>>> let version: u8 = 1;
    // ..
}
```

### Mitigation

use `message.version` from the params instead.
Upgraded Q -> 2 from #106 [1730392784616]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #106 as 2 risk. The relevant finding follows:

 ## 10. `cross_chain_erc20_settlement()` doesn't check that valid handler is given
The solidity instance of  `cross_chain_erc20_settlement()` doesn't check that valid handler is given like in cairo.
```solidity
    function cross_chain_erc20_settlement(
        string memory to_chain,
        uint256 to_handler,
        uint256 to_token,
        uint256 to,
        uint256 amount
    ) external {
        ///@audit-issue L valid handler check missing
        .....
    }
```
### Recommended Mitigation Steps
Implement that check like its implemented in cairo:
```cairo
           assert(self.support_handler.read((to_chain, to_handler)), 'not support handler');
```
Upgraded Q -> 2 from #96 [1730392672128]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #96 as 2 risk. The relevant finding follows:

 ## [QA-3]: Incorrect `from_address` can be emitted by the `CrossChainResult` event

In the `CrossChainResult` event, an incorrect `from_address` can be emitted. This is because `get_tx_info().unbox().account_contract_address` is equivalent to `tx.origin`


What this means is that it is possible for another user to provide the required signatures for the `receive_cross_chain_callback`, such that the `get_tx_info().unbox().account_contract_address` is no longer the true `from_address` of the initial `created_tx`.

The solution is to use the initial saved `from_address` in the `created_tx` mapping

```rust
       fn receive_cross_chain_callback(
            ref self: ContractState,
            cross_chain_msg_id: felt252,
            from_chain: felt252,
            to_chain: felt252,
            from_handler: u256,
            to_handler: ContractAddress,
            cross_chain_msg_status: u8,
            sign_type: u8,
            signatures: Array<(felt252, felt252, bool)>,
        ) -> bool {
            assert(self.created_tx.read(cross_chain_msg_id).tx_id == cross_chain_msg_id, 'message id error');
            assert(self.created_tx.read(cross_chain_msg_id).from_chain == to_chain, 'from_chain error');
            assert(self.created_tx.read(cross_chain_msg_id).to_chain == from_chain, 'to_chain error');
            assert(self.created_tx.read(cross_chain_msg_id).from_handler == to_handler, 'from_handler error');
            assert(self.created_tx.read(cross_chain_msg_id).to_handler == from_handler, 'to_handler error');
            assert(self.created_tx.read(cross_chain_msg_id).tx_status == CrossChainMsgStatus::PENDING, 'tx status error');

            let mut message_hash_temp: felt252 = LegacyHash::hash(from_chain, (cross_chain_msg_id, to_chain, from_handler, to_handler));
            let message_hash_final:felt252 = LegacyHash::hash(message_hash_temp, cross_chain_msg_status);
            self.check_chakra_signatures(message_hash_final, signatures);
            let handler = IHandlerDispatcher{contract_address: to_handler};
            let success = handler.receive_cross_chain_callback(cross_chain_msg_id, from_chain, to_chain, from_handler, to_handler , cross_chain_msg_status);
            let mut state = CrossChainMsgStatus::PENDING;
            if success{
                state = CrossChainMsgStatus::SUCCESS;
            }else{
                state = CrossChainMsgStatus::FAILED;
            }
            
            self.created_tx.write(cross_chain_msg_id, CreatedTx{
                tx_id:cross_chain_msg_id,
                tx_status:state,
                from_chain: to_chain,
                to_chain: from_chain,
                from_handler: to_handler,
                to_handler: from_handler
            });

            self.emit(CrossChainResult {
                cross_chain_settlement_id: cross_chai
Upgraded Q -> 2 from #92 [1730392536302]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #92 as 2 risk. The relevant finding follows:

 ## [03] When sending cross-chain messages, check whether the to_handler is on the whitelist.
### Link
github:[https://github.com/code-423n4/2024-08-chakra/blob/d0d45ae1d26ca1b87034e67180fac07ce9642fd9/solidity/handler/contracts/ChakraSettlementHandler.sol#L111](https://github.com/code-423n4/2024-08-chakra/blob/d0d45ae1d26ca1b87034e67180fac07ce9642fd9/solidity/handler/contracts/ChakraSettlementHandler.sol#L111)
### Description
When sending cross-chain requests to the target chain, the validity of `to_handler` is not checked. By verifying `to_handler`, it can reduce the occurrence of erroneous message calls and the triggering of incorrect events.  
Additionally, the system currently lacks a robust mechanism for handling refunds in the event of cross-chain message execution failures. Therefore, it is even more crucial to perform parameter validity checks.  
```solidity
    function cross_chain_erc20_settlement(
        string memory to_chain,
        uint256 to_handler,
        uint256 to_token,
        uint256 to,
        uint256 amount
    ) external {
        require(amount > 0, "Amount must be greater than 0");
        require(to != 0, "Invalid to address");
        require(to_handler != 0, "Invalid to handler address");
        require(to_token != 0, "Invalid to token address");
        
        ...
    }
```
### Recommendation
Check whether `to_handler` is in the whitelist, as messages will definitely fail if the `to_handler` is not whitelisted.  
```diff
    function cross_chain_erc20_settlement(
        string memory to_chain,
        uint256 to_handler,
        uint256 to_token,
        uint256 to,
        uint256 amount
    ) external {
        require(amount > 0, "Amount must be greater than 0");
        require(to != 0, "Invalid to address");
        require(to_handler != 0, "Invalid to handler address");
        require(to_token != 0, "Invalid to token address");
+       require(is_valid_handler(to_chain, to_handler), "Invalid target address");
        ...
    }
```
Upgraded Q -> 2 from #55 [1730392206979]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #55 as 2 risk. The relevant finding follows:

 ## Issue7: Wrong field `from` in the struct `CreatedCrossChainTx`
The field `from` should be the address of the caller. So, it should be replaced by `get_caller_address()`.
```rust
    pub struct CreatedCrossChainTx {
       tx_id : felt252,
       from_chain: felt252,
       to_chain: felt252,
       from: ContractAddress,
       to: u256,
       from_token: ContractAddress,
       to_token: u256,
       amount: u256,
       tx_status: u8
    }
```
https://github.com/code-423n4/2024-08-chakra/blob/main/cairo/handler/src/handler_erc20.cairo#L98
```rust
            let tx: CreatedCrossChainTx = CreatedCrossChainTx{
                    tx_id: tx_id,
                    from_chain: from_chain,
                    to_chain: to_chain,
                    from: get_contract_address(),
                    to: to,
                    from_token: self.token_address.read(),
                    to_token: to_token,
                    amount: amount,
                    tx_status: CrossChainTxStatus::PENDING
                };
```
https://github.com/code-423n4/2024-08-chakra/blob/main/cairo/handler/src/handler_erc20.cairo#L188
Upgraded Q -> 2 from #55 [1730392179617]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #55 as 2 risk. The relevant finding follows:

 ## Issue5: `to_handler` is not verified when sending message from EVM-based blockchains
When the function `ChakraSettlementHandler::cross_chain_erc20_settlement` is called, the parameter `to_handler` is not enforced to be a supported handler on the destination chain.
```solidity
    function cross_chain_erc20_settlement(
        string memory to_chain,
        uint256 to_handler,
        uint256 to_token,
        uint256 to,
        uint256 amount
    ) external {
        //....
    }
```
https://github.com/code-423n4/2024-08-chakra/blob/main/solidity/handler/contracts/ChakraSettlementHandler.sol#L113

While, when sending a message from Starknet, `to_handler` is enforced to be supported.
```rust
        fn cross_chain_erc20_settlement(ref self: ContractState, to_chain: felt252, to_handler: u256, to_token: u256, to: u256, amount: u256) -> felt252{
            assert(self.support_handler.read((to_chain, to_handler)), 'not support handler');
            //....
        }
```
https://github.com/code-423n4/2024-08-chakra/blob/main/cairo/handler/src/handler_erc20.cairo#L168

Note that the functions `receive_cross_chain_msg` and `receive_cross_chain_callback` enforce that `from_chain` and `from_handler` are valid set.
https://github.com/code-423n4/2024-08-chakra/blob/main/solidity/handler/contracts/ChakraSettlementHandler.sol#L311

This means that it is possible to send a message from EVM-based `chainA` to any arbitrary address (here is `to_handler`) on the destination chain.
Upgraded Q -> 2 from #539 [1730391912598]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #539 as 2 risk. The relevant finding follows:

 ### [L-04] Setting `set_required_validators_num` in Settlement doesn't update it in `SettlementSignatureVerifier`

#### Bug Description

* `ChakraSettlement` contract is basically manager of `SettlementSignatureVerifier` as calling function `add_validator` in `ChakraSettlement` will directly call `add_validator` in `SettlementSignatureVerifier` which has Only Manager Access.

* For Adding any validator, `add_validator` function is used while for removing any validator, `remove_validator` is used. Important to note here that it adds and removes from both Settlement and Signature contracts.

* But Setting Required number of validators in `ChakraSettlement` via `set_required_validators_num` doesn't call `set_required_validators_num` in the Signature Verifier contract.

#### Recommendation

```diff
File: BaseSettlement.sol

    function set_required_validators_num(
        uint256 _required_validators
    ) external onlyRole(MANAGER_ROLE) {
+       signature_verifier.set_required_validators_num(_required_validators);
        uint256 old = required_validators;
        required_validators = _required_validators;
        emit RequiredValidatorsChanged(msg.sender, old, required_validators);
    }

```
Upgraded Q -> 2 from #539 [1730391885926]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #539 as 2 risk. The relevant finding follows:

 ### [L-01] `cross_chain_erc20_settlement` doesn't validated bridging to `to_chain` via `to_handler` is possible or not leading to loss of funds

#### Bug Description

* There is no validation about `to_chain` and `to_handler` when any user call `cross_chain_erc20_settlement`.

* This can lead to User Unintensionally Locking or Burning their token for non supported handlers or chain or Previously allowed and now not allowed routes.

#### Recommendation

Validate the `to_chain` and `to_handler` to make sure that bridging is possible in that route.
Upgraded Q -> 2 from #540 [1730391806393]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #540 as 2 risk. The relevant finding follows:

 ### [L-06] cross_chain_erc20_settlement in handler_erc20.cairo does not have sufficient checks unlike its solidity counterpart

In `ChakraSettlementHandler.cross_chain_erc20_settlement()`, the parameters are checked:

```
    function cross_chain_erc20_settlement(
        string memory to_chain,
        uint256 to_handler,
        uint256 to_token,
        uint256 to,
        uint256 amount
    ) external {
        require(amount > 0, "Amount must be greater than 0");
        require(to != 0, "Invalid to address");
        require(to_handler != 0, "Invalid to handler address");
        require(to_token != 0, "Invalid to token address");
```

The same check is not applied in `handler_erc20.cairo.cross_chain_erc20_settlement()`

```
      fn cross_chain_erc20_settlement(ref self: ContractState, to_chain: felt252, to_handler: u256, to_token: u256, to: u256, amount: u256) -> felt252{
            assert(self.support_handler.read((to_chain, to_handler)), 'not support handler');
            let settlement = IChakraSettlementDispatcher {contract_address: self.settlement_address.read()};
            let from_chain = settlement.chain_name();
            let token = IERC20Dispatcher{contract_address: self.token_address.read()};
            let token_burnable = IERC20MintDispatcher{contract_address: self.token_address.read()};
```

Ensure sufficient checks on the parameter of the cairo function.

https://github.com/code-423n4/2024-08-chakra/blob/d0d45ae1d26ca1b87034e67180fac07ce9642fd9/cairo/handler/src/handler_erc20.cairo#L167
Upgraded Q -> 2 from #543 [1730391612437]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #543 as 2 risk. The relevant finding follows:

 ## L-08: Insufficient Handler Validation in ChakraSettlementHandler

### Summary
The ChakraSettlementHandler contract is designed to facilitate cross-chain ERC20 token transfers. It uses a system of whitelisted handlers to validate cross-chain messages. However, there's a critical flaw in how these handlers are validated.

The contract fails to properly validate the `to_handler` when initiating a cross-chain transaction in the `cross_chain_erc20_settlement` function. While the contract checks the validity of incoming handlers, it does not verify if the destination handler is whitelisted before sending tokens.

### Details
In the `cross_chain_erc20_settlement` function:

https://github.com/code-423n4/2024-08-chakra/blob/d0d45ae1d26ca1b87034e67180fac07ce9642fd9/solidity/handler/contracts/ChakraSettlementHandler.sol#L111

```solidity
function cross_chain_erc20_settlement(
    string memory to_chain,
    uint256 to_handler,
    uint256 to_token,
    uint256 to,
    uint256 amount
) external {
    // ... other checks ...
    require(to_handler != 0, "Invalid to handler address");
    // ... rest of the function ...
}
```

The function only checks if `to_handler` is not zero, but doesn't verify if it's a whitelisted handler for the destination chain.

### Impact
This vulnerability could allow an attacker to:
1. Initiate transfers to unauthorized handlers on other chains.
2. Potentially lock or lose tokens by sending them to invalid destinations.
3. Bypass intended security measures of the cross-chain system.

### Scenario
An attacker could exploit this by:
1. Calling `cross_chain_erc20_settlement` with a valid `to_chain` but an unauthorized `to_handler`.
2. The contract would process the transaction, locking or burning tokens on the source chain.
3. The cross-chain message would be sent to an invalid handler on the destination chain, potentially resulting in lost tokens.

### Fix
Implement a check in the `cross_chain_erc20_settlement` function to validate the destination handler:

```solidity
function cross_chain_erc20_settlement(
    string memory to_chain,
    uint256 to_handler,
    uint256 to_token,
    uint256 to,
    uint256 amount
) external {
    require(amount > 0, "Amount must be greater than 0");
    require(to != 0, "Invalid to address");
    require(to_handler != 0, "Invalid to handler address");
    require(to_token != 0, "Invalid to token address");
    require(is_valid_handler(to_chain, to_handler), "Invalid destination handler");

    // ... rest of the function ...
}
```
Upgraded Q -> 2 from #550 [1730391313418]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #550 as 2 risk. The relevant finding follows:

 ## [QA-01] Incorrect `to_handler` Value Set in `receive_cross_txs` During Cross-Chain Message Reception
### Impact
In the `ChakraSettlement` Solidity contract, when a cross-chain message is received, the `ReceivedCrossChainTx` structure is populated. However, there is an issue where the 6th argument, which corresponds to the handler address (`to_handler`) responsible for processing the cross-chain message, is incorrectly set to the address of the settlement contract (`address(this)`) instead of the intended handler address.
```solidity
function receive_cross_chain_msg(
    uint256 txid,
    string memory from_chain,
    uint256 from_address,
    uint256 from_handler,
    address to_handler,
    PayloadType payload_type,
    bytes calldata payload,
    uint8 sign_type, // validators signature type /  multisig or bls sr25519
    bytes calldata signatures // signature array
) external {
    // --SNIP
    receive_cross_txs[txid] = ReceivedCrossChainTx(
        txid,
        from_chain,
        contract_chain_name,
        from_address,
        from_handler,
>>>        address(this),
        payload,
        CrossChainMsgStatus.Pending
    );
    // --SNIP
}
```

### Recommended Mitigation Steps

Update the 6th argument of the `ReceivedCrossChainTx` structure to correctly reference the `to_handler` parameter instead of `address(this)`:
```diff
function receive_cross_chain_msg(
    uint256 txid,
    string memory from_chain,
    uint256 from_address,
    uint256 from_handler,
    address to_handler,
    PayloadType payload_type,
    bytes calldata payload,
    uint8 sign_type, // validators signature type /  multisig or bls sr25519
    bytes calldata signatures // signature array
) external {
    // --SNIP
    receive_cross_txs[txid] = ReceivedCrossChainTx(
        txid,
        from_chain,
        contract_chain_name,
        from_address,
        from_handler,
-       address(this),
+       to_handler,
        payload,
        CrossChainMsgStatus.Pending
    );
    // --SNIP
}
```
Upgraded Q -> 2 from #553 [1730390957831]
Audit: 2024-08-chakra-findings
Severity: MEDIUM

Judge has assessed an item in Issue #553 as 2 risk. The relevant finding follows:

 ## [QA-11] `cross_chain_erc20_settlement` is missing address 0 check in Cairo

**Issue Description:**

`cross_chain_erc20_settlement` in `Cairo` is missing check for the `to`,`to_token` addresses provided and users can lose their funds by passing 0 as an argument:

[handler_erc20.cairo](https://github.com/code-423n4/2024-08-chakra/blob/main/cairo/handler/src/handler_erc20.cairo#L167-L181)

```rust
  fn cross_chain_erc20_settlement(ref self: ContractState, to_chain: felt252, to_handler: u256, to_token: u256, to: u256, amount: u256) -> felt252{
      assert(self.support_handler.read((to_chain, to_handler)), 'not support handler');
      let settlement = IChakraSettlementDispatcher {contract_address: self.settlement_address.read()};
      let from_chain = settlement.chain_name();
      let token = IERC20Dispatcher{contract_address: self.token_address.read()};
      let token_burnable = IERC20MintDispatcher{contract_address: self.token_address.read()};
      ...MORE CODE
}
```

This will lead to tokens that are locked/burned on Starknet to be unlocked to `address(0)` on the destination chain meaning that tokens are lost, without a way to be refunded or the function to revert because of 0 passed as to_token.

The function should check this like in Solidity:

[ChakraSettlementHandler.sol#L111-L121](https://github.com/code-423n4/2024-08-chakra/blob/d0d45ae1d26ca1b87034e67180fac07ce9642fd9/solidity/handler/contracts/ChakraSettlementHandler.sol#L111-L121)

```solidity
function cross_chain_erc20_settlement(
    string memory to_chain,
    uint256 to_handler,
    uint256 to_token,
    uint256 to,
    uint256 amount
) external {
    require(amount > 0, "Amount must be greater than 0");
    require(to != 0, "Invalid to address");
    require(to_handler != 0, "Invalid to handler address");
    require(to_token != 0, "Invalid to token address");
```

**Recommendation:**

Add check, preventing users from passing 0 as an argument as a destination recipient:

```diff
fn cross_chain_erc20_settlement(ref self: ContractState, to_chain: felt252, to_handler: u256, to_token: u256, to: u256, amount: u256) -> felt252{
      assert(self.support_handler.read((to_chain, to_handler)), 'not support handler');
+     assert(to != 0, '0 address is not possible');
+     assert(to_token != 0, '0 address is not possible');     
      let settlement = IChakraSettlementDispatcher {contract_address: self.settlement_address.read()};
      let from_chain = settlement.chain_name();
      let token = IERC20Dispatcher{contract_address: self.token_address.read()};
      let token_burnable = IERC20MintDispatcher{contract_address: self.token_address.read()};
}
```

## [QA-12] `cross_chain_erc20_settlement` is missing zero amount check

**Issue Description:**

`cross_chain_erc20_settlement` in `Cairo` is missing check for 0 amount tokens and nothing prev