# Carbon DeFi Transaction Encoding

This page documents how to independently verify unsigned transactions returned by the Carbon DeFi MCP server or REST API. Use this to confirm that calldata matches what you requested before signing.

***

### Contract Addresses

All write operations target the CarbonController contract above. The `to` field in every unsigned transaction must match the address for the requested chain.

{% hint style="info" %}
Contract addresses can be found in the "[Mainnet Contracts](https://docs.carbondefi.xyz/contracts-and-functions/contracts/deployments/mainnet-contracts)" section
{% endhint %}

***

### Function Signatures

| Function                                                                                        | Selector     | Use                                        |
| ----------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------ |
| `createStrategy(address,address,(uint128,uint128,uint64,uint64)[2])`                            | `0xf727473a` | Create a new strategy                      |
| `updateStrategy(uint256,(uint128,uint128,uint64,uint64)[2],(uint128,uint128,uint64,uint64)[2])` | varies       | Edit/reprice/pause/resume/deposit/withdraw |
| `deleteStrategy(uint256)`                                                                       | `0x7831c1d7` | Delete a strategy                          |
| `tradeBySourceAmount(address,address,(uint256,uint128)[],uint256,uint128)`                      | `0xf1c5e014` | Swap — spend exact source amount           |
| `tradeByTargetAmount(address,address,(uint256,uint128)[],uint256,uint128)`                      | varies       | Swap — receive exact target amount         |

The first 4 bytes of the `data` field identify which function is being called.

***

### Order Encoding

Each strategy order is encoded as a struct with four fields:

```
struct Order {
  uint128 y;   // current token balance (liquidity) in wei
  uint128 z;   // capacity (max token balance) in wei
  uint64  A;   // encodeFloat(sqrt(highRate) - sqrt(lowRate)) * 2^48
  uint64  B;   // encodeFloat(sqrt(lowRate)) * 2^48
}
```

#### Price Encoding Pipeline

Prices in the Carbon DeFi protocol are stored as sqrt-rates using a custom float encoding. Here is the full pipeline:

**Step 1 — Normalize the price**

Prices are always expressed as `quote per base`. For the sell order (order0), prices are inverted and adjusted for token decimals:

```
normalizedRate = price * 10^(baseDecimals - quoteDecimals)
invertedRate = 1 / normalizedRate   # for sell order
```

The buy order (order1) uses the normalized rate directly.

**Step 2 — Convert to sqrt-rate**

```
sqrtRate = sqrt(normalizedRate)   # or sqrt(invertedRate) for sell
```

**Step 3 — Float encoding**

Carbon uses a custom 64-bit float encoding with a 48-bit mantissa and 16-bit exponent:

```
function encodeFloat(value):
  if value == 0: return 0
  exponent = floor(log2(value)) - 47   # so mantissa fits in 48 bits
  mantissa = round(value / 2^exponent)
  return (exponent + 2^15) << 48 | mantissa   # biased exponent
```

**Step 4 — Encode A and B**

```
A = encodeFloat(sqrtHighRate - sqrtLowRate)
B = encodeFloat(sqrtLowRate)
```

Where `sqrtHighRate` and `sqrtLowRate` are the sqrt-rates of the high and low prices respectively.

**Step 5 — Budget encoding**

```
y = parseUnits(budget, tokenDecimals)   # standard ERC20 wei conversion
z = y   # for new orders; may differ after partial fills
```

***

### Verification Checklist

When you receive an unsigned transaction from the MCP server:

1. **Check `to`** — must match the CarbonController address for the requested chain
2. **Check function selector** — first 4 bytes of `data` must match the expected function
3. **Check token addresses** — next 32-byte slots encode source/target or base/quote token addresses
4. **Check `value`** — must be 0 for ERC20 source tokens; must equal budget in wei for ETH as source
5. **Check order prices** — decode A and B fields and reverse the pipeline above to recover human-readable prices
6. **Check budget** — y field in wei must match the requested budget

***

### SDK Source References

For the exact encoding implementation:

* Price encoding: `@bancor/carbon-sdk` — `src/utils/encoders.ts`
* Float encoding: `@bancor/carbon-sdk` — `src/utils/numerics.ts`
* Strategy building: `@bancor/carbon-sdk` — `src/strategy-management/utils/index.ts`

***

### Trust Model

The MCP server returns unsigned transactions. It never signs or broadcasts. The user or their wallet signs and broadcasts.

If you are verifying a transaction from the MCP server, use the steps outlined in this page for further verification.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.carbondefi.xyz/developer-guides/carbon-defi-transaction-encoding.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
