Skip to content

Conversation

@rudewalt
Copy link
Contributor

@rudewalt rudewalt commented Feb 12, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new token swap adapter that enables efficient conversions within the Pendle ecosystem, offering users additional flexibility in asset exchanges.
  • Refactor

    • Streamlined adapter configuration and parameter handling for a more modular and maintainable token exchange workflow.
  • Tests

    • Added comprehensive test cases covering various swap scenarios—including pre- and post-maturity conditions—to ensure robust and reliable performance.

@coderabbitai
Copy link

coderabbitai bot commented Feb 12, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduce a new adapter type for handling Pendle Principal Token to Asset swaps. A new interface and corresponding types have been added to the deployment configuration files. The deployment flow now supports the Pendle adapter with added type guards and parameter creation methods. Additionally, a new smart contract implementing the swap functionality is introduced along with comprehensive tests and an update to the Dex enumeration.

Changes

File(s) Change Summary
packages/deploy/src/config.ts Added new interface PendlePtToAssetAdapterPair and updated AdapterPair to include it alongside PendleCurveRouterAdapterPair.
packages/deploy/src/deployer/MarginlyRouterDeployer.ts
packages/deploy/src/deployer/configs.ts
Introduced new type PendlePtToAssetAdapterParam, added corresponding type guard isPendlePtToAssetAdapter, and refactored adapter parameter creation via new methods including createPendlePtToAssetAdapterParam and createAdapterParam.
packages/router/contracts/adapters/PendlePtToAssetAdapter.sol Added new smart contract implementing the Pendle Principal Token to Asset swap functionality with methods for adding pools, swapping (exact input/output), redeeming leftover tokens, and error handling.
packages/router/test/int/PendlePtToAsset.eth.spec.ts
packages/router/test/shared/utils.ts
Added comprehensive unit tests for the new adapter and updated the Dex object to include a new entry PendlePtToAsset with a value of 33.

Sequence Diagram(s)

sequenceDiagram
    participant D as MarginlyRouterDeployer
    participant T as Adapter Type Guard
    participant C as createAdapterParam
    participant A as Adapter Contract

    D->>T: Check if adapter is PendlePtToAsset
    T-->>D: Return true/false
    alt PendlePtToAsset adapter
        D->>C: Build adapter parameters using PendlePtToAssetAdapterParam
        C-->>D: Return args array
        D->>A: Deploy adapter with Pendle-specific args
    else Other adapter
        D->>A: Deploy using existing adapter logic
    end
Loading
sequenceDiagram
    participant U as User
    participant A as PendlePtToAssetAdapter
    participant M as Market Data Handler

    U->>A: Call swapExactInput/swapExactOutput
    A->>M: Validate pool and fetch market data
    A->>A: Execute pre-/post-maturity swap logic
    A->>U: Return swap result (amount in/out)
Loading

Possibly related PRs

  • pendleCurve adapter #203: Involves modifications to the AdapterPair type and related interfaces, directly connecting to the changes introduced here.

Suggested reviewers

  • optifat

Poem

I'm a bunny coding in the glen,
Hopping through fields of code with a grin.
Pendle swaps and adapters come into play,
New interfaces spring to brighten the day.
With a twitch of my nose and joyful leaps,
I celebrate these changes in bounds and peeps!
🐰✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@rudewalt
Copy link
Contributor Author

@CodeRabbit review

@coderabbitai
Copy link

coderabbitai bot commented Feb 12, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
packages/router/contracts/adapters/PendlePtToAssetAdapter.sol (3)

20-28: Consider clarifying the slippage data type to avoid confusion.

Storing slippage as a uint8 and restricting its value to < 100 (via input.slippage >= ONE) is a practical approach, but it may be helpful to explicitly document that this represents a percentage-based slippage in the range 0–99. This can improve clarity for future maintainers.


127-133: Improve error context in _getMarketDataSafe.

When reverting with UnknownPair(), consider appending more context (e.g., the token addresses) to aid debugging. This can save time when troubleshooting misconfigurations.

- if (address(marketData.market) == address(0)) revert UnknownPair();
+ if (address(marketData.market) == address(0)) {
+   revert UnknownPair(); // or revert UnknownPair(tokenA, tokenB);
+ }

322-349: Consider minimizing leftover tokens in _pendleMintSy.

The comment notes that a small amount of SY may remain in the contract. You may want to track or emit an event for leftover tokens to simplify asset reconciliation. Alternatively, you can design logic (if feasible) to handle micro remainders once the swap is completed.

packages/deploy/src/deployer/configs.ts (2)

226-232: PendlePtToAssetAdapterParam interface definition is clear.

All necessary fields (pendleMarket, ptToken, assetToken, slippage) are well-defined. Consider a docstring explaining that slippage is in a percentage-like format (0–99).


673-692: Use explicit class references in createAdapterParam to avoid this usage in a static context.

The static analysis tools warn about using this in a static method. Replace this with the class name (e.g., StrictMarginlyDeployConfig) for clarity and to conform to the recommended practice.

- const adapterParam = this.createAdapterParam(adapter.adapterName, pool, tokens, dexId);
+ const adapterParam = StrictMarginlyDeployConfig.createAdapterParam(adapter.adapterName, pool, tokens, dexId);
🧰 Tools
🪛 Biome (1.9.4)

[error] 680-680: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 682-682: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 684-684: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 686-686: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 688-688: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 690-690: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

packages/router/test/int/PendlePtToAsset.eth.spec.ts (1)

266-271: Consider making slippage configurable.

The slippage value is hardcoded to 35. Consider making it configurable through the test case configuration for better flexibility.

Apply this diff:

  const poolInput: PendlePtToAssetAdapter.PoolInputStruct = {
    ptToken: ptToken.address,
    asset: assetToken.address,
    pendleMarket: testCase.pendleMarket,
-   slippage: 35,
+   slippage: testCase.slippage || 35, // Default to 35 if not specified
  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c08f33 and 65b32c6.

📒 Files selected for processing (6)
  • packages/deploy/src/config.ts (2 hunks)
  • packages/deploy/src/deployer/MarginlyRouterDeployer.ts (2 hunks)
  • packages/deploy/src/deployer/configs.ts (7 hunks)
  • packages/router/contracts/adapters/PendlePtToAssetAdapter.sol (1 hunks)
  • packages/router/test/int/PendlePtToAsset.eth.spec.ts (1 hunks)
  • packages/router/test/shared/utils.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/deploy/src/deployer/configs.ts

[error] 619-619: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 680-680: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 682-682: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 684-684: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 686-686: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 688-688: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 690-690: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

packages/router/test/int/PendlePtToAsset.eth.spec.ts

[error] 316-316: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

🔇 Additional comments (12)
packages/router/contracts/adapters/PendlePtToAssetAdapter.sol (2)

108-126: Evaluate safeguards against re-entrancy in swapCallback.

The contract requires msg.sender == marketData.market, which is a good start. However, since this callback triggers external calls (e.g., IMarginlyRouter(data.router).adapterCallback), it may benefit from having a stronger re-entrancy guard in place if there is any risk that these external calls could re-enter this contract unexpectedly.


371-406: Validate asset compatibility more thoroughly in _addPools.

Currently, the checks for ptToken, asset, and pendleMarket references and whether sy.isValidTokenIn(...) are good. However, consider verifying that the same asset and pt do not already map to a different PendleMarketData. Otherwise, repeated calls to addPools could unintentionally override existing pairs.

packages/deploy/src/deployer/configs.ts (4)

4-26: New adapter pair integration looks good.

The addition of PendlePtToAssetAdapterPair extends the existing adapters effectively. The approach is consistent with other adapter pair definitions.


178-179: Extended AdapterParam union.

Including PendlePtToAssetAdapterParam here is consistent with the other adapter parameter types. No issues spotted.


242-244: Helper guard function is consistent.

isPendlePtToAssetAdapter aligns well with the type-guard naming conventions used throughout this codebase.


761-784: createPendlePtToAssetAdapterParam logic aligns well with adapter creation patterns.

The method properly checks for missing tokens and slippage. The usage of EthAddress.parse(...) is consistent. No further issues spotted.

packages/router/test/shared/utils.ts (1)

30-30: New Dex entry for PendlePtToAsset is consistent.

Adding PendlePtToAsset: 33 follows the established enumeration pattern. There are no apparent issues with referencing or usage of this new Dex constant.

packages/deploy/src/deployer/MarginlyRouterDeployer.ts (2)

13-13: LGTM! New adapter types are properly imported.

The new adapter type PendlePtToAssetAdapterParam and its type guard isPendlePtToAssetAdapter are correctly imported, maintaining consistency with other adapter types.

Also applies to: 18-18


65-76: LGTM! New adapter deployment logic follows established patterns.

The deployment logic for PendlePtToAssetAdapter is well-structured and follows the same pattern as other adapters, correctly handling the required parameters:

  • pendleMarket
  • slippage
  • ptToken
  • assetToken
packages/deploy/src/config.ts (2)

387-388: LGTM! AdapterPair type correctly updated.

The AdapterPair type is properly extended to include the new PendlePtToAssetAdapterPair interface.


432-437: LGTM! New adapter interface is well-defined.

The PendlePtToAssetAdapterPair interface is properly defined with all necessary properties:

  • tokenAId: string
  • tokenBId: string
  • pendleMarket: string
  • slippage: number
packages/router/test/int/PendlePtToAsset.eth.spec.ts (1)

315-541: LGTM! Comprehensive test coverage.

The test suite is well-structured with thorough coverage:

  • Pre-maturity tests for exact input/output swaps
  • Post-maturity tests including forbidden operations
  • Multiple test cases with different tokens
  • Proper balance checks and gas usage monitoring
🧰 Tools
🪛 Biome (1.9.4)

[error] 316-316: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

}

// Tests for running in ethereum mainnet fork
describe.only('PendlePtToAssetAdapter', async () => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove .only to enable all tests.

The .only modifier is typically used during development for debugging purposes and should be removed before merging.

Apply this diff:

-describe.only('PendlePtToAssetAdapter', async () => {
+describe('PendlePtToAssetAdapter', async () => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe.only('PendlePtToAssetAdapter', async () => {
describe('PendlePtToAssetAdapter', async () => {
🧰 Tools
🪛 Biome (1.9.4)

[error] 316-316: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

} else {
// this clause is realized when pt tokens is output
// we need to mint SY from Asset and send to pendle
_pendleMintSy(marketData, msg.sender, uint256(-syToAccount), data);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pt out -> exactInput -> swapCallback -> _pendleMintSy scenario causes double sy.previewDeposit call

I don't think this call is too gas pricey, however I'd research a possibility to place it into CallbackData struct

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure it would be significant reducing

Copy link
Contributor

@optifat optifat Feb 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I thought about that, moreover it'll make other calls worse because of more unnecessary memory allocations in those case

However I think on average the gas consumption will reduce (because the mentioned scenario seems to be common enough, occurring in deposit + flip), but the decrease should be insignificant enough

);
amountIn = ptAmountIn;
// use amountOut here, because actualSyAmountOut a little bit more than amountOut
_pendleRedeemSy(marketData, address(this), actualSyAmountOut);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not to redeem estimatedSyOut amount to recipient and save gas on one additional transfer?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

However this change may cause those rounding issues with that (PENDLE_ONE * assetAmount + assetsPerSyUnit - 1) / assetsPerSyUnit line

}

///@dev Calc how much asset need to deposit and get exact amount of SY
function _syToAssetUpForDeposit(PendleMarketData memory marketData, uint256 syAmount) private view returns (uint256) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this and _assetToSyUpForRedeem methods should be moved somewhere lower (to _redeemPY?) to at least preserve public methods -> swap implementation order (right now they are in between _swapExactInputPostMaturity and _swapExactOutputPostMaturity)

uint256 index = marketData.yt.pyIndexCurrent();
amountIn = Math.mulDiv(estimatedSyAmountOut, index, PENDLE_ONE, Math.Rounding.Up);
uint256 syAmountOut = _redeemPY(marketData.yt, msg.sender, amountIn, data);
_pendleRedeemSy(marketData, address(this), syAmountOut);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

similar to the previous comment: why not to redeem estimatedSyAmountOut?

@rudewalt rudewalt merged commit f9a2e69 into feature/marginly-pendle Feb 18, 2025
3 checks passed
@rudewalt rudewalt deleted the feature/pendle-pt-to-asset-adapter branch February 18, 2025 09:28
@coderabbitai coderabbitai bot mentioned this pull request Feb 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants