getPriceImpact utility function.

What You’ll Accomplish
By the end of this guide, you’ll have:- ✅ Understanding of price impact and its importance
- ✅ Implementation of price impact calculations for bonded tokens
- ✅ Implementation of price impact calculations for unbonded tokens
- ✅ Test cases for validating price impact calculations
- ✅ Real-world examples using actual token data
What is Price Impact?
Price impact represents how much a trade will affect the token’s price. It’s expressed as a percentage and indicates:- Higher price impact = Your trade will significantly move the price
- Lower price impact = Your trade will have minimal effect on the price
- Traders: Understanding the cost of their trades
- UI/UX: Showing users the expected price change
- Risk Management: Warning users about large trades
Price Impact Function
ThegetPriceImpact function calculates price impact differently depending on whether a token is bonded or unbonded:
- Bonded Tokens: Use AMM (Automated Market Maker) liquidity pool calculations
- Unbonded Tokens: Use bonding curve mathematics
Function Signature
Installation and Setup
First, ensure you have the required utilities:Example 1: Bonded Token (ODINDOG)
Bonded tokens use liquidity pool calculations. Here’s an example with ODINDOG:Example 2: Unbonded Token
Unbonded tokens use bonding curve calculations:Understanding Different Scenarios
Currency Types
The function supports two currency types:- “btc”: Calculate impact when trading with Bitcoin
- “token”: Calculate impact when trading with token amounts
Trade Types
- Buy (isBuy: true): Purchasing tokens
- Sell (isBuy: false): Selling tokens
Token States
- Bonded (bonded: true): Token has graduated to AMM liquidity pool
- Unbonded (bonded: false): Token is still on the bonding curve
Error Handling
The function returnsnull in several error cases:
Practical Implementation
Here’s a complete implementation you might use in a trading interface:Best Practices
- Show Users Impact: Always display price impact to users before they confirm trades
- Set Thresholds: Warn users when price impact exceeds reasonable thresholds (e.g., 5% or 10%)
- Handle Errors: Gracefully handle
nullreturns from the function - Test Thoroughly: Use the provided test cases and create additional ones for your specific use cases
- Monitor Real-time: Price impact can change rapidly, so recalculate frequently for active trading interfaces
Next Steps
Slippage Calculation
Coming soon - Learn how to calculate and handle slippage for token trades
Minimum Received Amount
Coming soon - Calculate minimum amounts users will receive for token trades
The code used in this guide is published at https://github.com/Toniq-Labs/odin-docs/tree/main/demo/getting-started.