### Project Setup and Build Commands
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/AGENTS.md
Standard commands for setting up the project, starting the development server, building for production, linting, and running TypeScript checks.
```bash
yarn
yarn start
yarn build
yarn lint
yarn ts
```
--------------------------------
### Install Dependencies and Start Dev Server
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
Use 'yarn install' to install project dependencies. Start the development server with 'yarn start', which typically runs on localhost:5173.
```bash
yarn install
yarn start # Dev server on localhost:5173
```
--------------------------------
### Start Development Server
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/README.md
Start the development server for the Rainbow Swap frontend interface.
```bash
yarn start
```
--------------------------------
### Install Dependencies
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/README.md
Install project dependencies using Yarn.
```bash
yarn
```
--------------------------------
### Dispatch Wallet Actions Examples
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Examples demonstrating how to dispatch wallet actions using a Redux store's dispatch function. These include loading token balances, checking task completion status, and setting pending swap details.
```typescript
// Load token balances
dispatch(loadBalancesActions.submit('EQA1234...'));
// Check task completion
dispatch(checkTaskActions.submit({
taskType: TaskTypeEnum.Twitter
}));
// Set pending swap
dispatch(setPendingSwapAction({
bocHash: 'abc123',
expectedMessageCount: 2
}));
```
--------------------------------
### useTooltip Hook Usage Example
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
Example demonstrating how to use the `useTooltip` hook to manage tooltip state and integrate it with a `Tooltip` component. It shows configuration options like `initialOpen`, `placement`, and `onOpenChange`.
```jsx
function InfoButton() {
const tooltip = useTooltip({
initialOpen: false,
placement: 'bottom',
onOpenChange: (open) => console.log('Tooltip:', open)
});
return (
Help text here
);
}
```
--------------------------------
### Assets Record Lookup Example
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Example demonstrating how to use the `useAssetsRecordSelector` to access a specific asset using its address as a key.
```typescript
const assets = useAssetsRecordSelector();
const usdt = assets['EQCxE6m...'];
```
--------------------------------
### Local Development Server
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/architecture.md
Start the Vite development server locally using `yarn start`. This command runs Vite on localhost for rapid development.
```bash
yarn start # Vite dev server on localhost
```
--------------------------------
### Example Usage of copyToClipboard
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-utils.md
Shows how to call the copyToClipboard function with a sample string.
```typescript
await copyToClipboard('EQA1234...');
```
--------------------------------
### Asset List Component Example
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Example of a React component that uses the `useAssetsListSelector` to fetch and render a list of assets.
```typescript
function AssetList() {
const assets = useAssetsListSelector();
return assets.map(a => );
}
```
--------------------------------
### Vite Development Server
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/configuration.md
Starts the Vite development server, accessible on all network interfaces.
```bash
vite --host
```
--------------------------------
### useTooltipContext Hook Example
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
Example demonstrating the usage of the useTooltipContext hook within a TooltipContent component. It shows how to access and use the `onOpenChange` function to close the tooltip.
```jsx
function TooltipContent() {
const tooltip = useTooltipContext();
return (
);
}
```
--------------------------------
### Usage Example for useSendTransaction
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Demonstrates how to use the `useSendTransaction` hook within a React component to execute a swap. It includes error handling for wallet connection and transaction cancellation. The example shows how to construct the `Message` array and call the `sendTransaction` function.
```typescript
import {useSendTransaction} from '@/hooks/use-send-transaction.hook';
import {Message} from '@/types/message.type';
function SwapExecutor() {
const sendTransaction = useSendTransaction();
const executeSwap = async (messages: Message[]) => {
try {
const info = await sendTransaction(messages);
if (info) {
console.log('Transaction sent:', info.bocHash);
// Track transaction status
await trackSwapTransaction(info.bocHash);
} else {
console.log('Transaction cancelled');
}
} catch (err) {
console.error('Wallet not connected:', err);
}
};
return (
);
}
```
--------------------------------
### Connect Wallet with TON Connect UI
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Example of using useTonConnectUI to open the TON Connect modal. Ensure TonConnectUIProvider is set up.
```typescript
function MyComponent() {
const tonConnectUI = useTonConnectUI();
const handleConnect = () => {
tonConnectUI.openModal();
};
return ;
}
```
--------------------------------
### Connect Wallet Button
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Example of how to use the useTonConnectUI hook to open the wallet connection modal when no wallet is connected.
```typescript
import {useTonConnectUI} from '@/tonconnect/useTonConnectUI';
function WalletConnector() {
const tonConnectUI = useTonConnectUI();
const handleConnect = async () => {
if (!tonConnectUI.wallet) {
tonConnectUI.openModal();
}
};
return ;
}
```
--------------------------------
### Display Wallet Addresses in Different Formats
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Example of how to use the useTonAddress hook to display both user-friendly and raw wallet addresses.
```typescript
import {useTonAddress} from '@/tonconnect/useTonAddress';
function AddressDisplay() {
const friendly = useTonAddress(); // EQA1234...
const raw = useTonAddress(false); // 0:abc...
return (
User-friendly: {friendly}
Raw: {raw}
);
}
```
--------------------------------
### Specific Asset Selection Example
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Example of using the `useAssetSelector` hook to retrieve a specific asset, like USDT, by providing its address.
```typescript
const usdt = useAssetSelector('EQCxE6m...';
```
--------------------------------
### Setup TonConnectUIProvider
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
This code demonstrates the required wrapper for TonConnectUIProvider in your main application file (e.g., main.tsx). Ensure the `manifestUrl` points to a valid tonconnect-manifest.json file.
```typescript
import TonConnectUIProvider from '@/tonconnect/TonConnectUIProvider';
export function Root() {
return (
);
}
```
--------------------------------
### Dispatching Settings Actions
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Examples of how to dispatch actions to update various settings. Ensure the correct action and payload are used for each setting.
```typescript
dispatch(setMaxSlippageAction('2.5'));
dispatch(setRiskToleranceAction(RiskTolerance.Risky));
dispatch(setMaxSplitsAction(6));
dispatch(toggleDisabledDexGroupAction(DexGroupIdEnum.STON));
dispatch(setThemeAction(Theme.Light));
```
--------------------------------
### Example Usage of formatTimestamp
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-utils.md
Demonstrates calling formatTimestamp with a sample Unix timestamp.
```typescript
formatTimestamp(1704379800000); // '14:30, Jan 5' (if current year)
```
--------------------------------
### Application Context Providers Setup
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
This demonstrates the required order for wrapping the main App component with various context providers for Redux, persistence, TON Connect, modals, and swap form state.
```typescript
{/* Redux */}
{/* Redux-Persist */}
{/* Modal visibility */}
{/* Form state */}
```
--------------------------------
### Example Usage of bocToHash
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-utils.md
Demonstrates how to use the bocToHash function with a sample BOC data string.
```typescript
const bocData = 'te6ccGEC...'; // transaction boc
const hash = await bocToHash(bocData);
```
--------------------------------
### Dispatch Swap Routes Action
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Example of dispatching the `loadSwapRoutesActions.submit` action to calculate a swap route. Ensure all required parameters are provided.
```typescript
dispatch(loadSwapRoutesActions.submit({
requestId: 'req-001',
inputAssetAmount: '100000000',
inputAssetAddress: 'ton',
outputAssetAddress: 'USDT',
senderAddress: 'EQA1234...',
riskTolerance: RiskTolerance.Normal,
maxSplits: 4,
maxSlippage: 1,
disabledDexGroups: []
}));
```
--------------------------------
### Example Usage of getAsset
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-utils.md
Demonstrates how to use the getAsset function to retrieve and log asset properties like symbol, decimals, and exchange rate.
```typescript
const asset = getAsset('EQCxE6mUtQJKFnGfaROTKOt1lZb...', assetsRecord);
console.log(asset.symbol, asset.decimals, asset.exchangeRate);
```
--------------------------------
### ModalsProvider Usage
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
Example of how to wrap the main application component with `ModalsProvider` to enable modal functionality throughout the app.
```typescript
```
--------------------------------
### Example Usage of useSendTransaction Hook
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
This example demonstrates how to use the `useSendTransaction` hook within a React component to create a 'Swap' button. It shows how to call the `sendTransaction` function and handle success or failure scenarios, including logging the transaction hash or error messages.
```typescript
function SwapButton() {
const sendTransaction = useSendTransaction();
const handleSwap = async () => {
try {
const info = await sendTransaction([{
address: 'EQ...',
amount: '100000000'
}]);
if (info) {
console.log('Transaction sent:', info.bocHash);
}
} catch (err) {
console.error('Send failed:', err);
}
};
return ;
}
```
--------------------------------
### Example Usage of findAssetBySlug
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-utils.md
Shows how to find assets using their slugs (e.g., 'USDT', 'TON') and handle cases where an asset might not be found.
```typescript
const usdt = findAssetBySlug('USDT', assetsRecord);
const ton = findAssetBySlug('TON', assetsRecord);
if (!usdt) console.log('USDT not found');
```
--------------------------------
### Dispatch Load Assets List Action
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Example of how to dispatch the action to load the assets list. It specifies a request ID and a limit for the number of assets to retrieve.
```typescript
dispatch(loadAssetsListActions.submit({
requestId: 'req-001',
limit: 100
}));
```
--------------------------------
### Display Connected Wallet Information
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Example of how to use the useTonWallet hook to display connected wallet information or a 'Not connected' message.
```typescript
import {useTonWallet} from '@/tonconnect/useTonWallet';
function WalletStatus() {
const wallet = useTonWallet();
if (!wallet) {
return
Not connected
;
}
return (
Connected to {wallet.name}
Account: {wallet.account.address}
);
}
```
--------------------------------
### Example Usage of App Status Selector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Demonstrates how to use the `useAppStatusSelector` hook to conditionally display a swap button or a message indicating swaps are disabled.
```typescript
function SwapButton() {
const status = useAppStatusSelector();
if (!status.isSwapsEnabled) {
return
Swaps disabled: {status.message}
;
}
return ;
}
```
--------------------------------
### Display TON Wallet Address in Different Formats
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Demonstrates using useTonAddress to get and display both user-friendly and raw wallet addresses. Returns an empty string if no wallet is connected.
```typescript
function AddressDisplay() {
const friendlyAddress = useTonAddress(); // Returns "EQA1234..."
const rawAddress = useTonAddress(false); // Returns "0:abc123..."
return
{friendlyAddress}
;
}
```
--------------------------------
### Redux Store Testing
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
Example of testing Redux store logic, including dispatching actions and asserting state changes.
```javascript
describe('Wallet Store', () => {
it('should load balances', () => {
const {store} = createStore();
store.dispatch(loadBalancesActions.submit('EQA...'));
// Assert state
});
});
```
--------------------------------
### Using Settings Selectors in a Component
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
An example of a React component that uses the settings selectors to retrieve and display user preferences. This demonstrates how to integrate selectors into the UI.
```typescript
function SettingsPanel() {
const slippage = useMaxSlippageSelector();
const risk = useRiskToleranceSelector();
const theme = useThemeSelector();
return
Slippage: {slippage}%, Risk: {risk}
;
}
```
--------------------------------
### SwapInput Component Usage Example
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
Demonstrates how to use the `useSwapForm` hook within a React component to manage and display input field values and symbols. Ensure the `SwapFormProvider` is an ancestor of this component.
```typescript
import {useSwapForm} from './contexts/swap-form/swap-form.hook';
function SwapInput() {
const {
inputAsset,
inputAssetAmount,
setInputAssetAmount,
outputAsset
} = useSwapForm();
return (
);
}
```
--------------------------------
### Display Connected Wallet Address
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Example of using useTonWallet to display the connected wallet's address. Handles the case where no wallet is connected.
```typescript
function WalletStatus() {
const wallet = useTonWallet();
if (!wallet) {
return
Wallet not connected
;
}
return
Connected: {wallet.account.address}
;
}
```
--------------------------------
### Access TON Connect UI Instance
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Use this hook to get the TON Connect UI instance for wallet interactions. It must be used within a TonConnectUIProvider.
```typescript
export const useTonConnectUI = () => {
const tonConnectUI = useContext(TonConnectUIContext);
if (!tonConnectUI) {
throw new TonConnectProviderNotSetError(
'You should add on the top of the app...'
);
}
return tonConnectUI;
};
```
--------------------------------
### Get Current Wallet Address
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Get the current wallet address in either user-friendly or raw format. Returns an empty string if not connected.
```typescript
export function useTonAddress(userFriendly = true): string {
const wallet = useTonWallet();
return useMemo(() => {
if (wallet) {
return userFriendly
? toUserFriendlyAddress(
wallet.account.address,
wallet.account.chain === CHAIN.TESTNET
)
: wallet.account.address;
} else {
return '';
}
}, [wallet, userFriendly]);
}
```
--------------------------------
### Build Smart Contracts and Frontend
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
Use 'yarn build:contract' to compile smart contracts and 'yarn build' to generate the production-ready frontend assets.
```bash
yarn build:contract # Build smart contracts
yarn build # Build frontend
```
--------------------------------
### Get All Token Balances with useBalancesRecordSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
This hook retrieves all token balances for the currently connected wallet. It returns a mapping of token addresses to their balance strings. Useful for displaying a comprehensive list of user's assets.
```typescript
export const useBalancesRecordSelector = () =>
useSelector(({wallet}) => wallet.balances.data);
```
```typescript
function BalanceDisplay() {
const balances = useBalancesRecordSelector();
return Object.entries(balances).map(([addr, balance]) => (
{addr}: {balance}
));
}
```
--------------------------------
### Get Current Wallet with Updates
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Get the current wallet with automatic updates on connection changes. Returns the connected wallet or null if disconnected.
```typescript
export function useTonWallet():
| Wallet
| (Wallet & WalletInfoWithOpenMethod)
| null {
const tonConnectUI = useTonConnectUI();
const [wallet, setWallet] = useState<...>(tonConnectUI.wallet);
useEffect(() => {
tonConnectUI.onStatusChange((value: ConnectedWallet | null) => {
setWallet(value);
});
}, [tonConnectUI]);
return wallet;
}
```
--------------------------------
### Get Wallet Address Hook (TypeScript)
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Use this hook to get the connected wallet address. It returns undefined if the wallet is not connected. Ensure the wallet is connected before calling this hook.
```typescript
export const useWalletAddress = () => {
const walletAddress = useTonAddress();
return useMemo(
() => (isNotEmptyString(walletAddress) ? walletAddress : undefined),
[walletAddress]
);
};
```
--------------------------------
### useTonAddress
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Get current wallet address in specified format.
```APIDOC
## useTonAddress
### Description
Get current wallet address in specified format.
### Method
`useTonAddress(userFriendly?: boolean): string`
### Parameters:
- **userFriendly** (`boolean`) - Optional - Default: `true` - Return user-friendly format
### Returns
`string` — Wallet address or empty string if not connected
### Address Formats:
- **User-friendly** - Checksummed address with prefix (e.g., EQA1234ABC...)
- **Raw** - Raw hex address (e.g., 0:abc123def...)
### Usage Example:
```typescript
import {useTonAddress} from '@/tonconnect/useTonAddress';
function AddressDisplay() {
const friendly = useTonAddress(); // EQA1234...
const raw = useTonAddress(false); // 0:abc...
return (
User-friendly: {friendly}
Raw: {raw}
);
}
```
```
--------------------------------
### Build Smart Contract
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/README.md
Build the 'Rainbow routing wallet' smart contract using Yarn.
```bash
yarn build:contract
```
--------------------------------
### useAssetBalanceSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector to get the balance of a specific asset identified by its address.
```APIDOC
## useAssetBalanceSelector
### Description
Selector to get the balance of a specific asset identified by its address.
### Parameters
#### Path Parameters
- **address** (string) - Required - The address of the token for which to retrieve the balance.
```
--------------------------------
### Clone Repository
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/README.md
Clone the Rainbow Swap repository and navigate into the project directory.
```bash
git clone https://github.com/0xblackbot/rainbow-swap.git && cd rainbow-swap
```
--------------------------------
### useTonWallet
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Get current wallet with automatic updates on connection changes.
```APIDOC
## useTonWallet
### Description
Get current wallet with automatic updates on connection changes.
### Method
`useTonWallet(): Wallet | (Wallet & WalletInfoWithOpenMethod) | null`
### Returns
`Wallet | null` — Connected wallet or null if disconnected
### Return Type Properties (when not null):
- **account.address** (`string`) - Raw account address (0:hex format)
- **account.chain** (`CHAIN`) - Chain (MAINNET or TESTNET)
- **account.publicKey** (`string`) - Public key
- **account.walletsVersion** (`string`) - Wallet contract version
- **name** (`string`) - Wallet name (e.g., "Tonkeeper")
- **image** (`string`) - Wallet logo URL
- **device** (`object`) - Device info (appName, appVersion, maxProtocolVersion)
### Usage Example:
```typescript
import {useTonWallet} from '@/tonconnect/useTonWallet';
function WalletStatus() {
const wallet = useTonWallet();
if (!wallet) {
return
Not connected
;
}
return (
Connected to {wallet.name}
Account: {wallet.account.address}
);
}
```
```
--------------------------------
### API Reference - Utilities
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/COMPLETION_SUMMARY.txt
Documentation for utility functions available in the rainbow-swap-sdk.
```APIDOC
## Utility Functions
This section details the utility functions provided by the rainbow-swap-sdk. These functions are designed to be called directly by users for various operations.
### Source File Location
`api-reference-utils.md`
### Statistics
- Exported Functions: 20+
- Code Examples: 100+
```
--------------------------------
### useRewardsStateSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector to get the loading state and data related to referral rewards.
```APIDOC
## useRewardsStateSelector
### Description
Selector to get the loading state and data related to referral rewards.
### Returns
Object with `isLoading` (boolean) and `rewardsState` (object containing referral data).
```
--------------------------------
### Rainbow Swap SDK Workflow
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/architecture.md
Details the steps from SDK route calculation to transaction confirmation, highlighting the role of the SDK and transaction sending mechanism.
```typescript
Store.swapRoutes.bestRouteResponse
↓
Redux-Observable epic
↓
SDK.getBestRoute(params)
↓
Route Calculation with 8 DEXes
↓
Returns swapMessages & displayData
↓
useSendTransaction() sends messages
↓
Transaction confirmed on chain
```
--------------------------------
### Directory Structure Overview
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/architecture.md
This outlines the project's directory structure, detailing the organization of source code, smart contracts, documentation, and public assets.
```tree
rainbow-swap/
├── src/
│ ├── app/ # Root app component
│ ├── assets/ # Icons and static assets
│ ├── components/ # React components
│ │ ├── swap-form/ # Swap interface components
│ │ ├── settings-modal/ # Settings modal
│ │ ├── header/ # Header with wallet menu
│ │ ├── history-modal/ # Swap history
│ │ ├── points-modal/ # Points/rewards
│ │ └── ...other modals
│ ├── contexts/ # React Context providers
│ │ ├── swap-form/ # Form state (non-Redux)
│ │ └── modals/ # Modal visibility state
│ ├── enums/ # TypeScript enums
│ ├── hooks/ # Custom React hooks
│ ├── interfaces/ # TypeScript interfaces
│ ├── screens/ # Page-level components
│ ├── shared/ # Reusable UI components
│ ├── store/ # Redux state management
│ │ ├── assets/ # Asset metadata state
│ │ ├── wallet/ # Wallet data & balances
│ │ ├── settings/ # User preferences
│ │ ├── swap-routes/ # Swap route calculation
│ │ ├── security/ # App security status
│ │ ├── trading-competition/ # Competition leaderboard
│ │ ├── dev/ # Dev-only features
│ │ ├── initialized/ # Runtime state
│ │ └── utils/ # Redux utilities
│ ├── tonconnect/ # Custom TON Connect hooks
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utility functions
│ ├── globals.ts # Global constants
│ ├── main.tsx # App entry point
│ ├── secrets.ts # Environment secrets
│ └── index.css # Global styles
├── contracts/ # FunC smart contracts
├── docs/ # Documentation
├── public/ # Static assets
├── package.json
└── tsconfig.json
```
--------------------------------
### useTaskSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector to get the state and points earned for a specific task type.
```APIDOC
## useTaskSelector
### Description
Selector to get the state and points earned for a specific task type.
### Parameters
#### Path Parameters
- **taskType** (TaskTypeEnum) - Required - The type of task to query the state for.
```
--------------------------------
### useWalletAddress
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Hook to get the connected wallet address. Returns undefined if the wallet is not connected.
```APIDOC
## useWalletAddress
### Description
Get wallet address, returns undefined if not connected.
### Parameters
None
### Returns
`string | undefined` — Connected wallet address or undefined
### Example
```typescript
function SwapForm() {
const address = useWalletAddress();
if (!address) {
return ;
}
return ;
}
```
```
--------------------------------
### User Swap Data Flow Steps
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
This outlines the sequence of events during a user swap operation, from input to confirmation.
```text
1. User enters input amount → Component calls setInputAssetAmount()
2. useSwapForm() updates context state
3. Input amount triggers route calculation
4. dispatch(loadSwapRoutesActions.submit({...params...}))
5. Redux-Observable epic intercepts action
6. Epic calls SDK.getBestRoute(params)
7. SDK calculates optimal routes across 8 DEXes
8. Epic dispatches success with swapMessages and displayData
9. Reducer updates swapRoutes state
10. Component re-renders with new rates and messages
11. User clicks swap → dispatch(setPendingSwapAction())
12. Component calls useSendTransaction()
13. useSendTransaction() opens wallet for confirmation
14. User approves in wallet app
15. Wallet returns signed BOC
16. Component converts BOC to hash
17. dispatch(setPendingSwapHistoryDataAction()) with hash
18. Backend polls for confirmation
19. dispatch(updateSwapHistoryAction()) when confirmed
20. Component shows success message
```
--------------------------------
### useNumberOfReferralsSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector to get the total count of referrals, combining both users and wallets referred.
```APIDOC
## useNumberOfReferralsSelector
### Description
Selector to get the total count of referrals, combining both users and wallets referred.
### Returns
`number` — The total number of users and wallets referred.
```
--------------------------------
### useAssetBalanceSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector hook to get the balance for a specific asset (token) by its address. Returns '0' if the asset is not found.
```typescript
export const useAssetBalanceSelector = (address: string) =>
useSelector(({wallet}) => wallet.balances.data[address] ?? '0');
```
--------------------------------
### useSendTransaction
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Hook to send transaction messages and get transaction hash. It handles wallet connection checks and transaction submission through TonConnectUI.
```APIDOC
## useSendTransaction
### Description
Sends transaction messages and returns the transaction hash. This hook abstracts the process of interacting with TonConnectUI for sending transactions.
### Method Signature
`useSendTransaction(): (messages: Message[]) => Promise`
### Parameters
This hook does not take any direct parameters.
### Returns
- A function that accepts an array of `Message` objects and returns a `Promise` that resolves to `TransactionInfo` (containing `senderRawAddress` and `bocHash`) upon successful transaction, or `undefined` if the user cancels the transaction.
### Throws
- `Error`: If the wallet is not connected when the function is called.
### Example
```typescript
function SwapButton() {
const sendTransaction = useSendTransaction();
const handleSwap = async () => {
try {
const info = await sendTransaction([
{
address: 'EQ...',
amount: '100000000'
}
]);
if (info) {
console.log('Transaction sent:', info.bocHash);
}
} catch (err) {
console.error('Send failed:', err);
}
};
return ;
}
```
### Source
`src/hooks/use-send-transaction.hook.ts`
```
--------------------------------
### API Reference - Hooks
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/COMPLETION_SUMMARY.txt
Documentation for React hooks provided by the rainbow-swap project.
```APIDOC
## React Hooks
This section lists and describes the custom React hooks available in the project. These hooks encapsulate reusable logic and state management for components.
### Source File Location
`api-reference-hooks.md`
### Statistics
- Catalogued React Hooks: 30+
```
--------------------------------
### useNumberOfReferralsSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector hook to get the total count of referred users and wallets. This combines both direct user referrals and wallet referrals.
```typescript
export const useNumberOfReferralsSelector = () =>
useSelector(
({wallet}) =>
wallet.pointsState.walletPoints.data.rewardsState.usersReferred +
wallet.pointsState.walletPoints.data.rewardsState.walletsReferred
);
```
--------------------------------
### TypeScript Build Command
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/configuration.md
Use this command to compile TypeScript with pretty-printed output.
```typescript
tsc --pretty
```
--------------------------------
### Load Swap Routes
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Calculates the optimal swap route based on provided input and output assets, risk tolerance, and other parameters.
```APIDOC
## Load Swap Routes
### Description
Calculates the optimal swap route based on provided input and output assets, risk tolerance, and other parameters.
### Method
`loadSwapRoutesActions.submit()`
### Parameters
#### Request Body
- **requestId** (string) - Required - A unique identifier for the request.
- **inputAssetAmount** (string) - Required - The amount of the input asset to swap.
- **inputAssetAddress** (string) - Required - The address or symbol of the input asset.
- **outputAssetAddress** (string) - Required - The address or symbol of the output asset.
- **senderAddress** (string) - Optional - The address of the sender.
- **riskTolerance** (RiskTolerance) - Required - The user's risk tolerance level.
- **maxSplits** (number) - Required - The maximum number of splits allowed for the route.
- **maxSlippage** (number) - Required - The maximum acceptable slippage.
- **disabledDexGroups** (DexGroupIdEnum[]) - Required - A list of DEX groups to exclude.
### Request Example
```typescript
dispatch(loadSwapRoutesActions.submit({
requestId: 'req-001',
inputAssetAmount: '100000000',
inputAssetAddress: 'ton',
outputAssetAddress: 'USDT',
senderAddress: 'EQA1234...',
riskTolerance: RiskTolerance.Normal,
maxSplits: 4,
maxSlippage: 1,
disabledDexGroups: []
}));
```
### Response
#### Success Response (200)
- **bestRouteResponse** (object) - Contains the best route details.
- **swapMessages** (string[]) - BOC-encoded messages for the swap transaction.
- **displayData** (DisplayData) - UI display data including rates and amounts.
- **messageCount** (number) - The number of transaction messages.
#### Response Example
```json
{
"bestRouteResponse": {
"swapMessages": ["message1", "message2"],
"displayData": {
"rate": "0.001",
"amountIn": "100000000",
"amountOut": "100"
},
"messageCount": 2
}
}
```
```
--------------------------------
### Configuration Constants
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/COMPLETION_SUMMARY.txt
Reference for configuration constants used in the project.
```APIDOC
## Configuration Constants
This section lists all configuration constants used across the application. These constants define various settings and parameters that can be adjusted.
### Source File Location
`configuration.md`
### Statistics
- Configuration Constants: 30+
```
--------------------------------
### Get Asset Details by Address
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-utils.md
Retrieves asset details from a record using its address. If the asset is not found, it returns a placeholder object with the address.
```typescript
export const getAsset = (address: string, assetsRecord: AssetsRecord): Asset =>
assetsRecord[address] != null
? assetsRecord[address]
: {...EMPTY_ASSET, address};
```
--------------------------------
### API Reference - Store
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/COMPLETION_SUMMARY.txt
Documentation for Redux store modules, actions, and selectors.
```APIDOC
## Redux Store
This section covers the Redux Toolkit store configuration, including modules, actions, and selectors. It details how to interact with the application's state management.
### Source File Location
`api-reference-store.md`
### Statistics
- Documented Store Modules: 8
- Redux Actions: 30+
- Redux Selectors: 20+
```
--------------------------------
### Bundle Analysis with Vite
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/architecture.md
To generate a bundle report for analysis, set the `VITE_ANALYZE` environment variable to `true` before running the Vite build command.
```bash
VITE_ANALYZE=true vite build # Generate bundle report
```
--------------------------------
### useWalletAddress
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Gets the user-friendly wallet address or undefined if the user is not connected. This hook simplifies the process of checking connection status and retrieving the address.
```APIDOC
## useWalletAddress
### Description
Gets the user-friendly wallet address or undefined if the user is not connected.
### Parameters
None
### Returns
`string | undefined` — The wallet address if connected, otherwise undefined.
### Usage Example
```typescript
import {useWalletAddress} from '@/hooks/use-wallet-address.hook';
function SwapForm() {
const address = useWalletAddress();
if (!address) {
return ;
}
return ;
}
```
```
--------------------------------
### useSwapForm
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Accesses the swap form state, including input/output assets and amounts, along with their respective setter functions.
```APIDOC
## useSwapForm
### Description
Accesses swap form state (input/output assets and amounts) and setters.
### Method Signature
`useSwapForm(): SwapFormContextValues`
### Returns
`SwapFormContextValues` — An object containing the swap form state and setter functions.
### Return Object Properties
- **inputAssetAddress** (string): Input token address.
- **setInputAssetAddress** ((addr: string) => void): Function to set the input token address.
- **outputAssetAddress** (string): Output token address.
- **setOutputAssetAddress** ((addr: string) => void): Function to set the output token address.
- **inputAssetAmount** (string): Input amount as a string.
- **setInputAssetAmount** ((amount: string) => void): Function to set the input amount.
- **inputAsset** (Asset): Metadata for the input token.
- **outputAsset** (Asset): Metadata for the output token.
### Example
```typescript
function SwapInterface() {
const {
inputAsset,
outputAsset,
inputAssetAmount,
setInputAssetAmount
} = useSwapForm();
return (
);
}
```
```
--------------------------------
### HeaderButtons Component Usage
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
Example of how to use the `useModals` hook within a React component to open modals based on user interactions, such as button clicks.
```typescript
import {useModals} from './contexts/modals/modals.hook';
function HeaderButtons() {
const {
openPointsModal,
openSettingsModal,
openHistoryModal
} = useModals();
return (
);
}
```
--------------------------------
### SwapFormProvider Usage
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
Illustrates how to wrap child components with `SwapFormProvider` to enable context-based state management for the swap form. This should be placed at a higher level in the component tree.
```jsx
```
--------------------------------
### Settings Initial State
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/configuration.md
Defines the initial state for user settings, which are persisted in localStorage. Includes defaults for slippage, risk tolerance, theme, and more.
```typescript
export const settingsInitialState: SettingsState = {
maxSlippage: '1.00',
riskTolerance: RiskTolerance.Normal,
maxSplits: 4,
disabledDexGroups: [],
theme: Theme.Dark,
explorer: Explorer.Tonviewer
};
```
--------------------------------
### API Client Configuration
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/configuration.md
Creates an Axios instance configured with the base URL for all API requests to the `/api/*` endpoints.
```typescript
export const API = axios.create({
baseURL: 'https://api.rainbow.ag/api'
});
```
--------------------------------
### Sibling Communication via Context
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/architecture.md
Example of how one component can trigger an action in another sibling component by accessing a shared context, such as opening a settings modal.
```typescript
const {openSettingsModal} = useModals();
// Any sibling can call this to open settings
```
--------------------------------
### useRewardsStateSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector hook to get the current state of referral rewards, including loading status and reward data. It aggregates information about rewards earned from referrals.
```typescript
export const useRewardsStateSelector = () =>
useSelector(({wallet}) => ({
isLoading: wallet.pointsState.walletPoints.isLoading,
data: wallet.pointsState.walletPoints.data.rewardsState
}));
```
--------------------------------
### Track Page Views and Button Clicks
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
Import and use `useTrackPageView` for tracking screen views and `trackButtonClick` for tracking user interactions with buttons. Ensure the `isOpen` prop is passed to `useTrackPageView` for conditional tracking.
```typescript
import {useTrackPageView, trackButtonClick} from '@/hooks/use-analytics.hook';
function Modal({isOpen}) {
useTrackPageView('Settings Modal', isOpen);
const handleClick = () => {
trackButtonClick('Save Settings');
// ... save logic
};
return ;
}
```
--------------------------------
### Telegram Mini App Initialization
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/architecture.md
Shows how Telegram Mini App data is accessed for user authentication and managing UI elements during transactions.
```javascript
window.Telegram.WebApp.initData
↓
Used for User Auth API
↓
Verify user identity
↓
Load wallet points/rewards
↓
Disable main button during transactions
↓
Show back button in modals
```
--------------------------------
### Access Modal Functions
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
Use the `useModals` hook to get functions for opening specific modals, such as `openSettingsModal` and `openPointsModal`. These can then be attached to UI elements like buttons.
```typescript
import { useModals } from '@/hooks/use-modals';
const {openSettingsModal, openPointsModal} = useModals();
return (
<>
>
);
```
--------------------------------
### Get User Authentication Status
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-utils.md
Verifies user authenticity using Telegram Web App initData. Requires initData and optionally accepts a referrer address.
```typescript
export const getUserAuth = (params: GetUserAuthParams) =>
API.get('/user-auth', {params}).then(response => response.data);
```
```typescript
const isAuthenticated = await getUserAuth({
initData: window.Telegram.WebApp.initData,
refParent: '0:abc...'
});
```
--------------------------------
### Send TON Transaction with Loading and Cancellation Handling
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-tonconnect.md
Demonstrates how to send a transaction using `useSendTransaction`. It includes loading state management and handling both successful transaction results and user cancellations.
```typescript
function TransactionFlow() {
const sendTransaction = useSendTransaction();
const [isLoading, setIsLoading] = useState(false);
const handleSwap = async (messages: Message[]) => {
setIsLoading(true);
try {
const result = await sendTransaction(messages);
if (result) {
// Success
console.log('Sent:', result.bocHash);
} else {
// Cancelled
console.log('User cancelled');
}
} finally {
setIsLoading(false);
}
};
return ;
}
```
--------------------------------
### API Reference - Context
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/COMPLETION_SUMMARY.txt
Documentation for React Context API providers and consumers.
```APIDOC
## React Context API
This section describes the React Context providers and the data they expose. It outlines how components can consume context values.
### Source File Location
`api-reference-context.md`
### Statistics
- Documented React Contexts: All
```
--------------------------------
### Recommended Provider Order
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
Nest providers from outermost to innermost, starting with Redux store and ending with leaf contexts like SwapForm. This order ensures dependencies are met.
```typescript
```
--------------------------------
### Mocking Context for Component Testing
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/architecture.md
Illustrates how to mock React context for component testing. By providing a mock value to the context provider, you can isolate the component under test.
```typescript
// Mock context
```
--------------------------------
### useTonWallet
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Get current connected wallet or null if disconnected. This hook returns the currently connected wallet's information, including account details and connection status.
```APIDOC
## useTonWallet
### Description
Get current connected wallet or null if disconnected.
### Parameters
None
### Returns
`Wallet | null` — Connected wallet object or null
### Example
```typescript
function WalletStatus() {
const wallet = useTonWallet();
if (!wallet) {
return
Wallet not connected
;
}
return
Connected: {wallet.account.address}
;
}
```
```
--------------------------------
### Environment Variables Configuration
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/README.md
Configure environment variables for the application. VITE_BASE_URL sets the asset base URL, and VITE_ANALYZE enables bundle analysis.
```dotenv
VITE_BASE_URL=https://example.com # Asset base URL
VITE_ANALYZE=true # Enable bundle analysis
```
--------------------------------
### useTooltip Hook
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-context.md
The useTooltip hook manages the open/close state of a tooltip and accepts optional configuration options.
```APIDOC
## useTooltip Hook
Manage tooltip open/close state.
### Parameters:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| options | TooltipOptions | No | Tooltip configuration |
| options.initialOpen | boolean | No | Initial open state |
| options.placement | Placement | No | @floating-ui placement |
| options.onOpenChange | (open: boolean) => void | No | Open state callback |
### Returns:
`{open: boolean, setOpen: (open: boolean) => void}`
### Usage Example:
```typescript
function InfoButton() {
const tooltip = useTooltip({
initialOpen: false,
placement: 'bottom',
onOpenChange: (open) => console.log('Tooltip:', open)
});
return (
Help text here
);
}
```
```
--------------------------------
### Use Asset Selector with Memoization
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
A selector hook to get a specific asset by its address, with custom memoization based on address and USD exchange rate to optimize re-renders.
```typescript
export const useAssetSelector = (address: string) =>
useSelector(
({assets}) => getAsset(address, assets.record),
(a, b) =>
a.address + '_' + a.usdExchangeRate ===
b.address + '_' + b.usdExchangeRate
);
```
--------------------------------
### useTaskSelector
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Selector hook to get the state of a specific task, identified by its type. Returns the task's state including points earned, or a default empty state if not found.
```typescript
export const useTaskSelector = (taskType: TaskTypeEnum) =>
useSelector(
({wallet}) => wallet.pointsState.tasks[taskType] ?? EMPTY_TASK_STATE
);
```
--------------------------------
### Base URL Configuration
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/configuration.md
Defines the base URL for asset serving, utilizing Vite's environment variables. Defaults to '/' if the environment variable is not set.
```typescript
export const BASE_URL = import.meta.env.VITE_BASE_URL ?? '/';
```
--------------------------------
### Create Wallet Actions
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-store.md
Defines actions for various wallet operations including loading balances, user authentication, wallet data, task checking, reward claims, and managing pending swaps and swap history. Use these actions with a dispatch function to trigger state updates.
```typescript
export const loadBalancesActions = createActions(
'wallet/LOAD_BALANCES'
);
export const loadUserAuthActions = createActions(
'wallet/LOAD_USER_AUTH'
);
export const loadWalletDataActions = createActions<
GetWalletDataParams,
WalletDataResponse
>('wallet/LOAD_WALLET_DATA');
export const checkTaskActions = createActions<
{taskType: TaskTypeEnum; walletAddress?: string},
{taskType: TaskTypeEnum; data: number},
{taskType: TaskTypeEnum; error: string}
>('wallet/CHECK_TASK');
export const claimRewardsActions = createActions<
GetClaimRewardsParams,
boolean
>('wallet/CLAIM_REWARDS');
export const setPendingSwapAction = createAction<
{bocHash: string; expectedMessageCount: number} | undefined
>('wallet/SET_PENDING_SWAP');
export const setPendingSwapHistoryDataAction = createAction(
'wallet/SET_PENDING_SWAP_HISTORY_DATA'
);
```
--------------------------------
### Use Wallet Address Ref in Callback (TypeScript)
Source: https://github.com/0xblackbot/rainbow-swap/blob/main/_autodocs/api-reference-hooks.md
Demonstrates how to use the `useWalletAddressRef` hook to access the wallet address within a `useCallback` function. This ensures that the latest address is available even if the callback's dependencies don't include the address itself.
```typescript
function TransactionHandler() {
const addressRef = useWalletAddressRef();
const sendTx = useCallback(() => {
const addr = addressRef.current;
if (addr) {
// Use address in callback
}
}, [addressRef]);
return ;
}
```