# gFARM2 NFTs Source: https://docs.gains.trade/archived/nfts Historical reference for the deprecated gFARM2 NFTs and their redemption. ## **As of v6.4.1, our gFARM2 NFTs are deprecated.** Our gFARM2 NFTs have been consolidated into the \$GNS token, and you can redeem your NFTs for \$GNS accordingly. The role of NFT bots has been transitioned to our chainlink oracle network. ### **How does NFT redemption work?** You can redeem NFTs by visiting [gains.trade/nft-redemption](https://gains.trade/nft-redemption) and choosing one of two options: 1. **Receive linearly vested \$GNS over 6 months**, beginning from the date of redemption (staked throughout the vesting period) 2. **Receive the \$GNS immediately against a 25% penalty** (penalty directed to the gov fund to be used strategically and/or burned, as decided by the community) The amount of \$GNS received for each tier NFT is as follows: 1. **Bronze:** 800 \$GNS 2. **Silver:** 1,200 \$GNS 3. **Gold:** 1,800 \$GNS 4. **Platinum:** 3,700 \$GNS 5. **Diamond:** 12,000 \$GNS You can read more about this in our [Medium article](https://medium.com/gains-network/gns-tokenomics-plan-q3-2023-260c64ddd560). ### Distribution All NFTs were claimed by liquidity providers who supplied at least 1% of the total liquidity. They were rewarded with NFT credits, not ERC-20 tokens, which allowed them to mint these NFTs. The diamond NFTs required the most amount of credits, and bronze NFTs the least. ### What are gNFTs? These do not offer the benefits above. They have a separate use: representing positions of locked gDAI within the vault. Learn more on the [gDAI Vault](/liquidity-farming-pools/gtoken-vaults#gnft) page. # Arbitrum <-> Polygon Bridge Source: https://docs.gains.trade/bridges/arbitrum-less-than-greater-than-polygon-bridge Bridge your $GNS tokens or NFTs between Arbitrum and Polygon The native LayerZero bridge lets you move GNS tokens and NFTs between Arbitrum and Polygon: [https://www.gains.trade/bridge](https://www.gains.trade/bridge). 1. Select the source network in the upper-right corner. The example below bridges from Polygon to Arbitrum, but the flow is the same in either direction. 2. Select whether you want to bridge \$GNS or an NFT, enter the amount, click **Approve**, then click **Transfer**. 3. Bridging usually takes 20-40 minutes, depending on network congestion. A 6-hour epoch limits total bridged volume to 1,000,000 \$GNS and 50 NFTs. The current limit usage appears above the bridge panel. # Changelog Source: https://docs.gains.trade/changelog Day-to-day product releases, protocol updates, and operational notes. This changelog tracks the day-to-day work shipped by the Gains Network team. Use it for product releases, protocol changes, API updates, market additions, fixes, and operational notes that users or integrators should know about. Larger protocol launches remain linked in the historical archive below. ## Release format Each update should be short, dated, and practical: * **Added**: New product, protocol, market, API, or documentation surface. * **Changed**: Behavior, parameters, UX, integrations, or defaults that moved. * **Fixed**: User-facing bugs, integration issues, or reliability improvements. * **Operations**: Migrations, monitoring, infrastructure, chain support, or rollout notes. * **Risk**: Compatibility notes, known limitations, or action needed. ## Day-to-day releases ### 2026-08-02 - Mobile trade history timestamp overflow fix **Fixed**: Timestamps with seconds no longer overflow the time column in trade history on mobile screens. ### 2026-07-31 - Remove Get Funds popover, fix news leverage cap **Changed**: Removed the announcement popover overlaying the Get Funds button. **Fixed**: News event leverage cap was failing to restore after the event window closed, allowing trades at higher leverage than intended. Now correctly resets when the window ends. ### 2026-07-30 - MegaETH badge removed, testnet renamed to Demo Trading **Changed**: Removed the "NEW" badge from MegaETH in the network dropdown. Renamed the testnet network label to "Demo Trading". ### 2026-07-28 - New pairs, holding fees in Regular layout, social preview fix **Added**: Four new trading pairs launched — CASHCAT (pair 482), DOGEDEGEN (483), LINKDEGEN (484), and JPM (485) — with depth and spread routing. CASHCAT also has EVM on-chain depth via Mobula (source 8). Token logos added for CASHCAT and LINKDEGEN. **Changed**: Holding fees are now displayed in the Regular trading layout. **Fixed**: Corrected "markerts" typo in OG social preview image. ### 2026-07-27 - Trade history labels and positions table readability **Changed**: Trade history now tells market opens and closes apart. The Type column reads `MARKET OPEN` or `MARKET CLOSE` instead of a single `MARKET` for both, in the table and in the CSV export, and timestamps include seconds so fills within the same minute stay in order. **Changed**: Unrealized PnL and holding fees on open positions are shown as dollar amounts (`$0.92`) for collateral pegged to USD, instead of repeating the ticker. WETH, APE, and GNS collateral keep their symbol, since those amounts are not dollars. **Fixed**: The PnL cell in the positions table no longer splits the value, collateral, and percentage across three lines. **Fixed**: The **Get Funds** button now reads as a button. Its surface and border were almost indistinguishable from the black trading panel and hovering gave no feedback, so it looked like plain text. ### 2026-07-26 - Pair search opens on All markets **Changed**: The pair search modal now opens on **All** markets instead of **Trending**, and returns to All when a search is cleared. Trending is still one click away. ### 2026-07-23 - Chart overlay lines **Fixed**: The chart no longer shows duplicate or stale liquidation and entry lines. A single open position could previously draw two or more `LIQ` lines, entry lines could leak between markets, and restoring a saved chart layout left stale copies behind while the real stop-loss and entry lines disappeared. ### 2026-07-21 - Account equity, price impact, and new markets **Added**: The trading panel now shows an account-level **Total Equity** figure — wallet balance plus position collateral plus unrealized PnL — alongside its unrealized PnL and wallet balance components, so the full account value is visible in one place. **Added**: CASHCAT/USD, DOGEDEGEN/USD, LINKDEGEN/USD, and JPM/USD (pairs 482–485) are prepared for listing. They stay delisted until activation. **Fixed**: The **Price impact** row now includes the base skew component, so the percentage shown reconciles with the estimated open price directly above it. The previous figure omitted a component that is applied on-chain, making it read lower than the execution price implied. **Fixed**: Leaderboard win rates are correct again. Win and loss counts arrived from the database as text and were joined instead of added, which pinned nearly every trader's win rate to roughly 1%, 9%, or 10% regardless of actual performance. ### 2026-07-19 - Depth sources and Solana bridge safety **Added**: BP/USD gains a Backpack price feed and an on-chain depth source, so it is no longer priced from a single feed and no longer shows 0% spread with unlimited depth. **Changed**: ANSEM now uses depth-based virtual order book pricing instead of the fixed-spread fallback. **Fixed**: Solana bridge flows now wait for the transaction to be confirmed on-chain before being marked complete. Previously a transaction that had not landed within the polling window could still finalize the flow, making the claim button disappear while the funds were still claimable. ### 2026-07-17 - Share PnL cards, chart persistence, and trade panel defaults **Added**: The Share PnL card is now customizable — Wallet, Price, and Size blocks can each be toggled on or off, and the choice persists. A share button next to unrealized PnL opens it in one click, and a copy-text action produces a ready-to-post caption with your referral link. **Changed**: New traders now see both collateral and size inputs in the trade panel by default. Existing traders keep the input mode they are used to, whether they picked it explicitly or not. **Fixed**: Chart drawings and technical analysis now survive a page refresh. Autosave silently failed on any chart layout that had never been explicitly named, which meant an ordinary session saved nothing. **Fixed**: Scrolling the mouse wheel over the chart's price axis now rescales the price axis vertically instead of zooming the time scale. **Fixed**: The **Get Funds** button now wraps below the token balances when they are too wide, instead of spilling over the positions table. ### 2026-07-14 - Trading History CSV timestamps **Changed**: The downloadable Trading History CSV now includes the time of day in its date column (for example, `15/07/2026 14:32:05` instead of just the date), matching the on-screen history table so exported records are easier to reconcile. ### 2026-07-13 - Whale Watch, forex hours, and trade history **Added**: Gains Whale Watch is live on X ([@GainsTradeBot](https://x.com/GainsTradeBot)) — real-time posts for \$10k+ wins and losses, large-position alerts, and a rolling seven-day leaderboard, each linking back to the trader's page. **Fixed**: Forex markets no longer open an hour early — or close an hour early on Fridays — during US daylight saving time. Sessions now hold the correct 5:00 PM New York boundary, so orders are not admitted while price coverage is sparse. **Fixed**: Trade history now preserves the opening fee on very short-lived trades. Previously a trade that opened and closed almost instantly could show a zero opening fee, with both fees appearing on the closing row. ### 2026-07-11 - Virtual order book depth and link fixes **Added**: A new guide documents the virtual order book and how its synthetic depth is generated. **Added**: A live RWA depth source now feeds the depth data used across markets. **Operations**: The one-percent depth updater schedule was enabled and the depths-bot ECS shards were deployed. ### 2026-07-10 - Solana claim reliability **Fixed**: Solana claim failures are now surfaced and monitored, making claim issues easier to diagnose. ### 2026-07-09 - Pricing and pair-selector polish **Fixed**: The pair selector keeps its bottom rows visible and scrollable on desktop. **Fixed**: Noisy pricing feed warnings are throttled to reduce log spam. **Changed**: Samsung and SKHYNIX leverage remains disabled. **Operations**: The depth updater Lambda now ships with its required SDK runtime dependencies. ### 2026-07-08 - Trending search and SKHYNIX pricing **Added**: Trending pair search now ranks results by 24h volume and includes an **All** tab. **Fixed**: Stale custom max-leverage overrides are reset so leverage limits stay correct. ### 2026-07-07 - Market hours, charts, and docs accuracy **Added**: Token logos were added or refreshed for every listed pair that was still missing an icon. Site and docs social preview images were also replaced with the current Gains visuals. **Changed**: Trading availability now follows pair-specific market hours more consistently across the frontend and pricing services. SKHYNIX uses KRX market hours, and 24/7 pair overrides remain active when market sessions are cleared. **Fixed**: Charts now keep the latest candle attached on timeframes above 1 minute, avoid sparse-candle resets, and continue to guard realtime candle updates when a pair is unavailable. **Fixed**: Open-position data refreshes are more resilient when upstream responses take longer than expected. **Fixed**: The pair selector keeps the request-pair action pinned at the bottom, and the account footer stays aligned above the status bar when a banner is shown. **Changed**: The spread and fee documentation was updated for BTC/ETH spread behavior and per-asset fee accuracy. ### 2026-07-06 - Market data feeds **Added**: The stats aggregator now exposes synthetic depth and spread data for the CoinGecko feed. ### 2026-07-04 - TradingView layouts, BOT pricing, and brand polish **Added**: TradingView layouts can now persist for traders, and TradingView no longer prompts for signatures during normal use. **Added**: BOT uses official logo assets with 24/7 chart sessions. **Changed**: The old gTrade update banner was removed. SEO metadata and the fee-reduction banner were updated to use Gains branding. **Fixed**: Pair explorer metrics now sort globally, token logo rendering handles missing symbols, and BOT charts stay smoother across sparse 24/7 candle data. ### 2026-07-03 - Pair search, BOT pricing, and trading UX polish **Added**: BOT/USD now has 24/7 Hyperliquid pricing support and a token logo in the trading interface. Equity pricing coverage was expanded with Pyth feeds. **Changed**: Pair search now prioritizes recent searches, trending markets, and new listings. The no-results state now opens the listing request form directly. **Changed**: Account balances were moved into compact chips next to **Get Funds**, trade detail rows were reordered for easier scanning, and promotional notices were removed from the trade panel. **Changed**: Trading history CSV exports now split PnL into trading PnL and fees, so downloaded records are easier to reconcile. **Fixed**: Clicking a pair from active trades, active orders, or history now opens the matching chart and keeps the details modal flow intact. **Fixed**: The pair selector keeps sort state consistent, Edit SL/TP closes after successful updates, and newly listed pairs resolve correctly in the stats aggregator API. ### 2026-07-02 - Markets, price impact, and trading fixes **Added**: New markets were listed and activated for BOT/USD, BB/USD, LPTH/USD, ABCL/USD, IOVA/USD, XDC/USD, ADI/USD, BRUN/USD, WYFI/USD, SHAZ/USD, BE/USD, NBIS/USD, CRWV/USD, and IREN/USD. The pair list documentation now includes pairs 454-481. **Changed**: The trading panel now defaults to size-based input and right-side placement for new users, while preserving existing user preferences. Trading pairs shown in open positions, pending orders, and trade history can now be clicked to open the corresponding chart without opening trade details. **Changed**: The trade panel spread row was updated to a price impact view with a component breakdown for fixed spread, liquidity impact, and skew. The price impact docs, FAQ, and glossary were updated to match the current v10 model. **Changed**: The SL/TP update modal now shows take-profit controls before stop-loss controls. **Fixed**: Trader stats volume now follows the protocol event model instead of counting every history row at full notional. The selected stats window also loads enough history for 1D, 7D, 30D, and 1Y periods before displaying final values. **Fixed**: Open positions on trader pages now receive live price snapshots correctly after direct page loads and route navigation, fixing frozen current price, liquidation price, and uPnL values. ### 2026-07-01 - PnL cards **Added**: Traders can generate shareable PnL cards from open or closed trades. Cards include the market, direction, leverage, wallet, entry price, current/exit price, size, and PnL. **Changed**: The share flow renders the card client-side with the new visual treatment and supports percent or USD PnL display when applicable. PnL card preview **Operations**: Cards are rendered client-side as PNG images. Traders can download the card or copy it to the clipboard, and uploaded backgrounds are processed locally in the browser. **Risk**: Clipboard image support varies by browser. Download remains available when image copying is unsupported. ## Historical major releases [Gains v10 is live: built to scale](https://medium.com/gains-network/gtrade-v10-is-live-built-to-scale-22dbd635de20) [v9.4: new innovations and returning classics](https://medium.com/gains-network/v9-4-new-innovations-returning-classics-37d3e105dcbf) [v9.2: enhanced spread formula and competitive liquidations](https://medium.com/gains-network/v9-2-enhanced-spread-formula-and-competitive-liquidations-9cd99ea3497e) [Evolving Gains Network tokenomics: introducing buyback and distribute](https://medium.com/gains-network/evolving-gains-network-tokenomics-introducing-buyback-and-distribute-c15ce1fa8fdb) [v9: elevating trade management](https://medium.com/gains-network/v9-elevating-trade-management-19d9cd123f82) [Introducing Gains v8: diamond refactor and smart contract integration](https://medium.com/gains-network/introducing-gtrade-v8-diamond-refactor-and-smart-contract-integration-a175b96ccb82) [Introducing Gains v7: gETH, gUSDC, and multi-collateral deposits](https://medium.com/gains-network/introducing-gtrade-v7-geth-gusdc-and-multi-collateral-deposits-b4dabcf9b991) [Price impact expiration v6.4.2: enhancing altcoin trading](https://medium.com/gains-network/price-impact-expiration-v6-4-2-enhancing-altcoin-trading-8d84b039dcce) [Gains v6.4: lookbacks, guaranteed order execution, and borrowing fee updates](https://medium.com/gains-network/gtrade-v6-4-lookbacks-guaranteed-order-execution-and-borrowing-fee-updates-a6fda8fbc4f8) [Introducing gToken Vaults](https://medium.com/gains-network/introducing-gtoken-vaults-ea98f10a49d5) [GNS staking, a new referral system, and more](https://gainsnetwork-io.medium.com/gns-staking-a-new-referral-system-and-much-more-v6-1-1-b6c8166ad210) [Gains v6.1 in-depth](https://medium.com/gains-network/gtrade-v6-1-in-depth-b06c0b93fad1) # Gains Guardians Source: https://docs.gains.trade/community/gtrade-guardians Become a Gains Guardian and champion the future of DeFi ## Mission The Gains Guardians program is designed to create a strong sense of family and belonging within a global community of passionate individuals. Representation of Gains in the digital world is being redefined, with Guardians empowered to track their progress and grow through tangible achievements. Support is provided to help Guardians craft creative content that inspires, educates, and amplifies the vision of the Gains platform. ## Get Involved 1. **Sign Up** – Please fill out this Google form: [https://docs.google.com/forms/d/e/1FAIpQLSftE8n3u7KOhNcC03FerjJryb-ggw5-w3uA7r-P9\_MlOtqgHw/viewform](https://docs.google.com/forms/d/e/1FAIpQLSftE8n3u7KOhNcC03FerjJryb-ggw5-w3uA7r-P9_MlOtqgHw/viewform) 2. **Vetting Process** – A Gains representative will review your application. 3. **One-on-One Interview** – If you’re selected for the program, you will receive an invite for an interview as the final step in your vetting process. ## Onboarding What to expect when first starting: * **Access** to dedicated Gains Ambassador **Telegram group** – Share content, get feedback and connect with others. * **Program Details** – Guidelines, incentives, tier system * **Monthly Group Calls** – Learn about Gains, content creation and program updates. ## KPIs and Rewards *Create Content, Unlock Rewards!* Meet the KPI requirements and receive the corresponding benefits: **⭐️ 10,000 monthly views** * Referral link (optional) * Gains Guardian Discord/Telegram role * Dedicated GNS-chan NFT showcasing Guardian status **⭐️ 25,000 monthly views** * Verified blue checkmark * Content promotion via official channels and Gains Guardian account **⭐️ 50,000 monthly views** * Exclusive Gains merch **⭐️ 100,000 monthly views** * Invitation to Gains events * Access to, and ability to give feedback on, coming updates * Higher revenue share **⭐️ 500,000 monthly views** * Ability to earn \$GNS rewards * Ability to run an official Gains related account (e.g. Gains Lifestyle and Gains Gym) * Recognition as part of the Gains family ***Also, posts are always eligible to be tipped!***\ \ Here are some of the criteria Gains will look at: * Most creative post * ATH in views * Best likes-to-view ratio * Most KPIs reached * High engagement * Highest amount of views * Highest amount of likes A monthly review of the Gains Guardian’s performance will be conducted, e.g. tracking number of views. ## Minimum Requirement The Gains Guardian Ambassador program requires you to post Gains and Gains Network-related content 4 times per month. ## Content Guidelines As a Gains Guardian, your content helps shape the community and spreads the word about Gains Network. Encourage creativity and humor while ensuring that all content aligns with community values. Please keep the following guidelines in mind: **Be inclusive and respectful.** * No racism or discrimination: We have zero tolerance for racism, sexism, homophobia, or any other form of discrimination. Your content should be welcoming and respectful of everyone, regardless of their background. * No harassment or bullying: Harassment, bullying, or any form of intimidation is strictly prohibited. We want a positive and supportive community, so make sure your content reflects that. **Encourage creativity and humor.** * Memes and jokes are welcome: We love creativity! Feel free to share memes, jokes, and lighthearted content. Just ensure it’s in good taste and doesn’t cross the line into offensive or harmful territory. * Stay true to the brand: While having fun, remember to keep your content aligned with the values and mission of Gains Network and Gains. Focus on the positive aspects of the platform and the DeFi space. **Promote positive interaction.** * Constructive Criticism: When offering feedback or criticism, keep it constructive and aimed at fostering improvement. A positive tone helps maintain a strong and supportive community. * Engage Responsibly: Interact with others online in a way that builds the community. Avoid getting involved in conflicts or negative exchanges. **Respect legal and ethical boundaries.** * No Misinformation: Share accurate and reliable information. Avoid spreading rumors or unverified claims. * Copyright and Attribution: Ensure your content is original or properly credited. Respect others’ intellectual property. **Use official hashtags.** * Hashtag & Tag Use: When posting about Gains, use the official hashtags (#Gains, #GainsNetwork & @GainsNetwork\_Io) to connect with the community and amplify your reach. **Report issues.** * Flag Inappropriate Content: If you see content that doesn’t align with these guidelines, report it to the Gains Network team. # Acknowledge VIP Status Source: https://docs.gains.trade/developer/api-reference/endpoint/ack-vip-status post /api/vip/{address}/ack Acknowledges that the wallet has seen the VIP prompt. ### Endpoint `POST /api/vip/{address}/ack` Acknowledges that the wallet has seen the VIP prompt. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------- | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/vip/0x0000000000000000000000000000000000000000/ack" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Get APR Info Source: https://docs.gains.trade/developer/api-reference/endpoint/apr get /api/apr Returns APR and TVL data for staking, vault, burn, and collateral rewards. ### Endpoint `GET /api/apr` Returns APR and TVL data for staking, vault, burn, and collateral rewards. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/apr?chainId=42161" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 503, 500. Error responses generally return an `error` or `message` field. # Associate Wallet Source: https://docs.gains.trade/developer/api-reference/endpoint/associate-wallet post /api/dapp/wallet/associate Creates a wallet association after signature verification. ### Endpoint `POST /api/dapp/wallet/associate` Creates a wallet association after signature verification. ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/dapp/wallet/associate" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Get Batch Wallet Trading History Source: https://docs.gains.trade/developer/api-reference/endpoint/batch-personal-trading-history post /api/personal-trading-history/batch Returns paginated trading history for multiple wallets. ### Endpoint `POST /api/personal-trading-history/batch` Returns paginated trading history for multiple wallets. ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/personal-trading-history/batch" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses generally return an `error` or `message` field. # Get Batch Wallet Trading Stats Source: https://docs.gains.trade/developer/api-reference/endpoint/batch-personal-trading-stats post /api/personal-trading-history/stats Returns trading statistics for multiple wallet addresses. ### Endpoint `POST /api/personal-trading-history/stats` Returns trading statistics for multiple wallet addresses. ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/personal-trading-history/stats" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses generally return an `error` or `message` field. # Get Bridge Flow By Hash Source: https://docs.gains.trade/developer/api-reference/endpoint/bridge-flow-by-hash get /api/dapp/bridge/flows/hash/{srcHash} Returns one bridge flow by source transaction hash. ### Endpoint `GET /api/dapp/bridge/flows/hash/{srcHash}` Returns one bridge flow by source transaction hash. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------------------ | | `srcHash` | path | Yes | string | Source transaction hash. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/bridge/flows/hash/0xSOURCE_HASH" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Get Bridge Flows By Address Source: https://docs.gains.trade/developer/api-reference/endpoint/bridge-flows-by-address get /api/dapp/bridge/flows/{address} Returns bridge flows associated with a wallet address. ### Endpoint `GET /api/dapp/bridge/flows/{address}` Returns bridge flows associated with a wallet address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------- | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/bridge/flows/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Check Campaign Eligibility Source: https://docs.gains.trade/developer/api-reference/endpoint/campaign-eligibility get /api/campaigns/eligibility/{address} Checks broad EVM address eligibility across active campaigns. ### Endpoint `GET /api/campaigns/eligibility/{address}` Checks broad EVM address eligibility across active campaigns. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------------- | | `address` | path | Yes | string | EVM wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/campaigns/eligibility/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Check Campaign Eligibility By ID Source: https://docs.gains.trade/developer/api-reference/endpoint/campaign-eligibility-by-id get /api/campaigns/{campaignId}/eligibility/{address} Checks EVM address eligibility for a specific campaign. ### Endpoint `GET /api/campaigns/{campaignId}/eligibility/{address}` Checks EVM address eligibility for a specific campaign. ### Parameters | Parameter | Location | Required | Type | Description | | ------------ | -------- | -------- | ------ | ------------------- | | `campaignId` | path | Yes | string | Campaign ID. | | `address` | path | Yes | string | EVM wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/campaigns/campaign-id/eligibility/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Get Circle Messages Source: https://docs.gains.trade/developer/api-reference/endpoint/circle-messages get /api/dapp/circle/messages/{domainId}/{txHash} Returns Circle CCTP messages for a transaction. ### Endpoint `GET /api/dapp/circle/messages/{domainId}/{txHash}` Returns Circle CCTP messages for a transaction. ### Parameters | Parameter | Location | Required | Type | Description | | ---------- | -------- | -------- | ------ | ------------------------ | | `domainId` | path | Yes | string | Circle source domain ID. | | `txHash` | path | Yes | string | Source transaction hash. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/circle/messages/0/0xTRANSACTION_HASH" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Get Contest Details Source: https://docs.gains.trade/developer/api-reference/endpoint/contest-details get /api/contests/{id} Returns details, rewards, and aggregate stats for a contest. ### Endpoint `GET /api/contests/{id}` Returns details, rewards, and aggregate stats for a contest. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ----------- | | `id` | path | Yes | string | Contest ID. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/contests/contest-id" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 404, 503, 500. Error responses generally return an `error` or `message` field. # Get Contest Leaderboard Source: https://docs.gains.trade/developer/api-reference/endpoint/contest-leaderboard get /api/contests/{id}/leaderboard Returns a contest leaderboard sorted by PnL or volume. ### Endpoint `GET /api/contests/{id}/leaderboard` Returns a contest leaderboard sorted by PnL or volume. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------- | -------------------------- | | `id` | path | Yes | string | Contest ID. | | `sortBy` | query | No | string | Sort field: pnl or volume. | | `limit` | query | No | integer | Items to return. | | `offset` | query | No | integer | Pagination offset. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/contests/contest-id/leaderboard" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 404, 503, 500. Error responses generally return an `error` or `message` field. # Get Contest Trader Stats Source: https://docs.gains.trade/developer/api-reference/endpoint/contest-trader-stats get /api/contests/{id}/leaderboard/{trader} Returns stats, rankings, and estimated rewards for a trader in a contest. ### Endpoint `GET /api/contests/{id}/leaderboard/{trader}` Returns stats, rankings, and estimated rewards for a trader in a contest. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ---------------------- | | `id` | path | Yes | string | Contest ID. | | `trader` | path | Yes | string | Trader wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/contests/contest-id/leaderboard/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 404, 503, 500. Error responses generally return an `error` or `message` field. # List Contests Source: https://docs.gains.trade/developer/api-reference/endpoint/contests get /api/contests Lists trading contests. ### Endpoint `GET /api/contests` Lists trading contests. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/contests" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 404, 503, 500. Error responses generally return an `error` or `message` field. # Get Open Trades Source: https://docs.gains.trade/developer/api-reference/endpoint/core-open-trades get /open-trades Returns all known open trades. ### Endpoint `GET /open-trades` Returns all known open trades. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/open-trades" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Open Trades By Address Source: https://docs.gains.trade/developer/api-reference/endpoint/core-open-trades-by-address get /open-trades/{address} Returns known open trades for one address. ### Endpoint `GET /open-trades/{address}` Returns known open trades for one address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ---------------------- | | `address` | path | Yes | string | Trader wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/open-trades/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Open Trades Info Source: https://docs.gains.trade/developer/api-reference/endpoint/core-open-trades-info get /open-trades-info Returns metadata and indexes for known open trades. ### Endpoint `GET /open-trades-info` Returns metadata and indexes for known open trades. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/open-trades-info" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Pending Events Source: https://docs.gains.trade/developer/api-reference/endpoint/core-pending-events get /pending-events Returns pending backend event queue data. ### Endpoint `GET /pending-events` Returns pending backend event queue data. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/pending-events" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Trading Variable Keys Source: https://docs.gains.trade/developer/api-reference/endpoint/core-trading-variable-keys get /trading-variables-keys Returns available trading variable keys. ### Endpoint `GET /trading-variables-keys` Returns available trading variable keys. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/trading-variables-keys" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Trading Variables Source: https://docs.gains.trade/developer/api-reference/endpoint/core-trading-variables get /trading-variables Returns core trading variables needed by integrators. ### Endpoint `GET /trading-variables` Returns core trading variables needed by integrators. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/trading-variables" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get All Trading Variables Source: https://docs.gains.trade/developer/api-reference/endpoint/core-trading-variables-all get /trading-variables/all Returns all cached trading variables. ### Endpoint `GET /trading-variables/all` Returns all cached trading variables. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/trading-variables/all" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Trading Variables By Keys Source: https://docs.gains.trade/developer/api-reference/endpoint/core-trading-variables-by-keys get /trading-variables/{keys} Returns selected trading variable keys. ### Endpoint `GET /trading-variables/{keys}` Returns selected trading variable keys. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------------- | | `keys` | path | Yes | string | Comma-separated keys. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/trading-variables/pairs,groups" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get User Trading Variables Source: https://docs.gains.trade/developer/api-reference/endpoint/core-user-trading-variables get /user-trading-variables/{address} Returns user-specific trading variables, pending market orders, fee tiers, and price impact data. ### Endpoint `GET /user-trading-variables/{address}` Returns user-specific trading variables, pending market orders, fee tiers, and price impact data. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ---------------------- | | `address` | path | Yes | string | Trader wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/user-trading-variables/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Create Bridge Flow Source: https://docs.gains.trade/developer/api-reference/endpoint/create-bridge-flow post /api/dapp/bridge/flows Creates a cross-chain bridge flow record. ### Endpoint `POST /api/dapp/bridge/flows` Creates a cross-chain bridge flow record. ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/dapp/bridge/flows" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 201, 400, 404, 500. Error responses generally return an `error` or `message` field. # Delete Bridge Flow Source: https://docs.gains.trade/developer/api-reference/endpoint/delete-bridge-flow delete /api/dapp/bridge/flows/{srcHash} Deletes a bridge flow record. ### Endpoint `DELETE /api/dapp/bridge/flows/{srcHash}` Deletes a bridge flow record. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------------------ | | `srcHash` | path | Yes | string | Source transaction hash. | ### Usage Example ```bash theme={null} curl -X DELETE "https://backend-global.gains.trade/api/dapp/bridge/flows/0xSOURCE_HASH" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Dismiss Notification Source: https://docs.gains.trade/developer/api-reference/endpoint/dismiss-notification post /api/notifications/{address}/dismiss Marks one notification as acknowledged. ### Endpoint `POST /api/notifications/{address}/dismiss` Marks one notification as acknowledged. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------- | | `address` | path | Yes | string | Wallet address. | ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/notifications/0x0000000000000000000000000000000000000000/dismiss" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses generally return an `error` or `message` field. # Finalize Bridge Flow Source: https://docs.gains.trade/developer/api-reference/endpoint/finalize-bridge-flow patch /api/dapp/bridge/flows/finalize Marks a bridge flow as finalized. ### Endpoint `PATCH /api/dapp/bridge/flows/finalize` Marks a bridge flow as finalized. ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X PATCH "https://backend-global.gains.trade/api/dapp/bridge/flows/finalize" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Health Check Source: https://docs.gains.trade/developer/api-reference/endpoint/health get /health Check backend service health. ### Endpoint `GET /health` Check backend service health. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/health" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Holding Rates Source: https://docs.gains.trade/developer/api-reference/endpoint/holding-rates get /api/holding-rates/{collateralIndex}/{pairIndex} Returns historical borrowing and funding rates for a collateral and pair. ### Endpoint `GET /api/holding-rates/{collateralIndex}/{pairIndex}` Returns historical borrowing and funding rates for a collateral and pair. ### Parameters | Parameter | Location | Required | Type | Description | | ----------------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `collateralIndex` | path | Yes | integer | Collateral index. | | `pairIndex` | path | Yes | integer | Trading pair index. | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/holding-rates/1/0?chainId=42161" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 503, 500. Error responses generally return an `error` or `message` field. # Get Latest Dapp Version Source: https://docs.gains.trade/developer/api-reference/endpoint/latest-dapp get /api/dapp/latest Returns latest frontend version metadata for a dapp mode. ### Endpoint `GET /api/dapp/latest` Returns latest frontend version metadata for a dapp mode. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ----------- | | `dapp` | query | No | string | Dapp mode. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/latest?dapp=evm" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Get Latest Dapp Version By Mode Source: https://docs.gains.trade/developer/api-reference/endpoint/latest-dapp-by-mode get /api/dapp/latest/{mode} Returns latest frontend version metadata for a mode path parameter. ### Endpoint `GET /api/dapp/latest/{mode}` Returns latest frontend version metadata for a mode path parameter. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ----------- | | `mode` | path | Yes | string | Dapp mode. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/latest/evm" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Get Trader Leaderboard Source: https://docs.gains.trade/developer/api-reference/endpoint/leaderboard get /api/leaderboard/{period} Returns trader leaderboard for a period or all supported periods. ### Endpoint `GET /api/leaderboard/{period}` Returns trader leaderboard for a period or all supported periods. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `period` | path | Yes | string | Period in days, or all. | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/leaderboard/7?chainId=42161" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 503, 500. Error responses generally return an `error` or `message` field. # Get Legacy Contest Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest get /contest Returns legacy contest metadata. ### Endpoint `GET /contest` Returns legacy contest metadata. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/contest" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Update Legacy Contest Cache Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest-cache-update put /contest/cache-update Updates legacy contest cache data. ### Endpoint `PUT /contest/cache-update` Updates legacy contest cache data. ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X PUT "https://backend-arbitrum.gains.trade/contest/cache-update" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Legacy Final Open PnL Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest-final-open-pnl get /contest/final-open-pnl Returns final open PnL snapshots for legacy contests. ### Endpoint `GET /contest/final-open-pnl` Returns final open PnL snapshots for legacy contests. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/contest/final-open-pnl" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Legacy Contest Leaderboard Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest-leaderboard get /contest/leaderboard Returns legacy contest leaderboard cache. ### Endpoint `GET /contest/leaderboard` Returns legacy contest leaderboard cache. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/contest/leaderboard" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Legacy Contest PnL Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest-pnl get /contest/pnl Returns legacy contest PnL history cache. ### Endpoint `GET /contest/pnl` Returns legacy contest PnL history cache. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/contest/pnl" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Legacy Contest PnL Percent Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest-pnl-percent get /contest/pnl-percent Returns legacy contest percentage PnL history cache. ### Endpoint `GET /contest/pnl-percent` Returns legacy contest percentage PnL history cache. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/contest/pnl-percent" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Legacy Contest Results Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest-results get /contest/results Returns legacy contest results data. ### Endpoint `GET /contest/results` Returns legacy contest results data. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/contest/results" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Legacy Contest Rewards Source: https://docs.gains.trade/developer/api-reference/endpoint/legacy-contest-rewards get /contest/rewards Returns legacy contest rewards data. ### Endpoint `GET /contest/rewards` Returns legacy contest rewards data. ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/contest/rewards" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Notifications Source: https://docs.gains.trade/developer/api-reference/endpoint/notifications get /api/notifications/{address} Returns active notifications for a wallet. ### Endpoint `GET /api/notifications/{address}` Returns active notifications for a wallet. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------- | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/notifications/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Get Pending Bridge Flows Source: https://docs.gains.trade/developer/api-reference/endpoint/pending-bridge-flows get /api/dapp/bridge/flows/pending/{address} Returns non-finalized bridge flows associated with a wallet address. ### Endpoint `GET /api/dapp/bridge/flows/pending/{address}` Returns non-finalized bridge flows associated with a wallet address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------- | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/bridge/flows/pending/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Get Wallet Trading History Source: https://docs.gains.trade/developer/api-reference/endpoint/personal-trading-history get /api/personal-trading-history/{address} Returns paginated trading history for one wallet. ### Endpoint `GET /api/personal-trading-history/{address}` Returns paginated trading history for one wallet. ### Parameters | Parameter | Location | Required | Type | Description | | ----------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `address` | path | Yes | string | Trader wallet address. | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | | `cursor` | query | No | integer | Pagination cursor. | | `limit` | query | No | integer | Items to return. | | `startDate` | query | No | string | Optional ISO start date. | | `endDate` | query | No | string | Optional ISO end date. | | `pair` | query | No | string | Optional pair filter. | | `action` | query | No | string | Optional action filter. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/personal-trading-history/0x0000000000000000000000000000000000000000?chainId=42161&limit=50" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses generally return an `error` or `message` field. # Get Wallet Trading Stats Source: https://docs.gains.trade/developer/api-reference/endpoint/personal-trading-stats get /api/personal-trading-history/{address}/stats Returns all-time and 30-day trading statistics for a wallet. ### Endpoint `GET /api/personal-trading-history/{address}/stats` Returns all-time and 30-day trading statistics for a wallet. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `address` | path | Yes | string | Trader wallet address. | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/personal-trading-history/0x0000000000000000000000000000000000000000/stats?chainId=42161" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses generally return an `error` or `message` field. # Resolve Referral Address Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-address-link get /api/referrals/addresses/{address}/link Resolves a referral address to a slug. ### Endpoint `GET /api/referrals/addresses/{address}/link` Resolves a referral address to a slug. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ----------------- | | `address` | path | Yes | string | Referrer address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/addresses/0x0000000000000000000000000000000000000000/link" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 404, 500. Error responses generally return an `error` or `message` field. # Bind Code Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-bind-code post /api/referrals/bind Attaches a referrer to a wallet from an EIP-712 signature. ### Endpoint `POST /api/referrals/bind` Attaches a referrer to a wallet from an EIP-712 signature. Only accepted while the wallet has never traded on a covered chain. Afterwards it returns `409 AlreadyTraded`, permanently. Bind at onboarding, before the wallet reaches the exchange. See [Referrals](/developer/integrators/referrals). ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/referrals/bind" \ -H "Content-Type: application/json" \ -d '{"message":{...},"signature":"0x..."}' ``` ### Response Structure The generated API panel lists the response schema for status codes: 201, 400, 401, 403, 409, 429, 503. Error responses return an `error` field. # Resolve Binding Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-binding get /api/referrals/binding/{address} The referrer this address is bound to. ### Endpoint `GET /api/referrals/binding/{address}` The referrer this address is bound to. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | Returns `null` when unbound. Bindings are set once and permanent. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/binding/0x1111111111111111111111111111111111111111" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses return an `error` field. # Resolve Code Owner Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-code-owner get /api/referrals/code/{code}/address The address that owns a referral code. ### Endpoint `GET /api/referrals/code/{code}/address` The address that owns a referral code. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | -------------------------------------------------- | | `code` | path | Yes | string | Referral code. Trimmed and lowercased server-side. | Returns `null` when the code is unregistered. Use this to pre-flight a bind: binding to an unknown code returns `409 CodeUnknown`. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/code/mycode/address" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses return an `error` field. # Referral Config Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-config get /api/referrals/config Returns the EIP-712 domain values and the standard reward rates. ### Endpoint `GET /api/referrals/config` Returns the EIP-712 domain values and the standard reward rates. Probe this endpoint to detect whether referrals are enabled on a deployment. Any non-200 means the feature is unavailable there. Read `chainId` and `distributor` from here at runtime rather than hardcoding them. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/config" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 503. Error responses return an `error` field. # Referral History Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-history get /api/referrals/history/{address} Daily accruals and payments received. ### Endpoint `GET /api/referrals/history/{address}` Daily accruals and payments received. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | `daily` is ascending by day; `claims` is descending by block. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/history/0x1111111111111111111111111111111111111111" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses return an `error` field. # Resolve Referral Link Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-link-address get /api/referrals/links/{link}/address Resolves a referral slug to an address. ### Endpoint `GET /api/referrals/links/{link}/address` Resolves a referral slug to an address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | -------------- | | `link` | path | Yes | string | Referral slug. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/links/referral-code/address" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 404, 500. Error responses generally return an `error` or `message` field. # Resolve Address Code Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-owner-code get /api/referrals/address/{address}/code The referral code owned by an address. ### Endpoint `GET /api/referrals/address/{address}/code` The referral code owned by an address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | Returns `null` when the address owns no code. One code per address. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/address/0x1111111111111111111111111111111111111111/code" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses return an `error` field. # Claim Proof Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-proof get /api/referrals/proof/{address} Merkle proof against the batch currently active on the distributor. ### Endpoint `GET /api/referrals/proof/{address}` Merkle proof against the batch currently active on the distributor. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | A `404` means nothing is claimable yet. That is a normal state, not an error. Pass `cumulativeMicroUsdc` to `claim` unchanged; the contract computes the delta against what you have already claimed. Re-fetch immediately before sending, because a proof goes stale when a new batch is published. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/proof/0x1111111111111111111111111111111111111111" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses return an `error` field. # Referred Wallets Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-referred get /api/referrals/referred/{address} The referrer of this address, and the addresses referred at level 1 and level 2. ### Endpoint `GET /api/referrals/referred/{address}` The referrer of this address, and the addresses referred at level 1 and level 2. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/referred/0x1111111111111111111111111111111111111111" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses return an `error` field. # Referred Wallet Detail Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-referred-detail get /api/referrals/referred/{address}/detail Per-wallet rows for the referred set. ### Endpoint `GET /api/referrals/referred/{address}/detail` Per-wallet rows for the referred set. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | `earnedUsd` is what the referrer earned **from** that wallet, not what the wallet earned. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/referred/0x1111111111111111111111111111111111111111/detail" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses return an `error` field. # Register Code Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-register-code post /api/referrals/code Registers a referral code from an EIP-712 signature. ### Endpoint `POST /api/referrals/code` Registers a referral code from an EIP-712 signature. See [Referrals](/developer/integrators/referrals) for the EIP-712 domain, the struct, and the GET transport for clients behind an edge that blocks POST. Only `201` is success. There is no API key: the signature is the sole authority. ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/referrals/code" \ -H "Content-Type: application/json" \ -d '{"message":{...},"signature":"0x..."}' ``` ### Response Structure The generated API panel lists the response schema for status codes: 201, 400, 401, 403, 409, 429, 503. Error responses return an `error` field. # Referral Rewards Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-rewards get /api/referrals/rewards/{address} Earnings totals for one address. ### Endpoint `GET /api/referrals/rewards/{address}` Earnings totals for one address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | Two of these field names are misleading. `claimableMicroUsdc` is lifetime gross earnings, and `unpaidMicroUsdc` includes amounts no published batch carries yet. Neither is the claimable amount; use the [claim proof](/developer/api-reference/endpoint/referral-proof). ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/rewards/0x1111111111111111111111111111111111111111" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses return an `error` field. # Referral Summary Source: https://docs.gains.trade/developer/api-reference/endpoint/referral-summary get /api/referrals/summary/{address} Dashboard composite for one address. ### Endpoint `GET /api/referrals/summary/{address}` Dashboard composite for one address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------ | | `address` | path | Yes | string | EVM address. | `vip` is `null` when no tier snapshot exists. `effectiveRate` reports the standard programme rate; a negotiated partner rate is applied to earnings but is not reflected in this field. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/referrals/summary/0x1111111111111111111111111111111111111111" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses return an `error` field. # Get All Rewards By Address Source: https://docs.gains.trade/developer/api-reference/endpoint/rewards-all-by-address get /rewards/all/{configId}/{epoch}/{address} Returns all rewards for one address. ### Endpoint `GET /rewards/all/{configId}/{epoch}/{address}` Returns all rewards for one address. ### Parameters | Parameter | Location | Required | Type | Description | | ---------- | -------- | -------- | ------ | ----------------- | | `configId` | path | Yes | string | Reward config ID. | | `epoch` | path | Yes | string | Epoch ID. | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/rewards/all/config-id/1/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Rewards By Address Source: https://docs.gains.trade/developer/api-reference/endpoint/rewards-by-address get /rewards/{configId}/{epoch}/{address} Returns rewards for one address. ### Endpoint `GET /rewards/{configId}/{epoch}/{address}` Returns rewards for one address. ### Parameters | Parameter | Location | Required | Type | Description | | ---------- | -------- | -------- | ------ | ----------------- | | `configId` | path | Yes | string | Reward config ID. | | `epoch` | path | Yes | string | Epoch ID. | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/rewards/config-id/1/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Rewards Root Source: https://docs.gains.trade/developer/api-reference/endpoint/rewards-root get /rewards/root/{configId}/{epoch} Returns the rewards Merkle root for a config and epoch. ### Endpoint `GET /rewards/root/{configId}/{epoch}` Returns the rewards Merkle root for a config and epoch. ### Parameters | Parameter | Location | Required | Type | Description | | ---------- | -------- | -------- | ------ | ----------------- | | `configId` | path | Yes | string | Reward config ID. | | `epoch` | path | Yes | string | Epoch ID. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/rewards/root/config-id/1" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get All Rewards Roots Source: https://docs.gains.trade/developer/api-reference/endpoint/rewards-root-all get /rewards/root/all/{configId}/{epoch} Returns all rewards Merkle roots matching a config and epoch. ### Endpoint `GET /rewards/root/all/{configId}/{epoch}` Returns all rewards Merkle roots matching a config and epoch. ### Parameters | Parameter | Location | Required | Type | Description | | ---------- | -------- | -------- | ------ | ----------------- | | `configId` | path | Yes | string | Reward config ID. | | `epoch` | path | Yes | string | Epoch ID. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-arbitrum.gains.trade/rewards/root/all/config-id/1" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Check Solana Campaign Eligibility Source: https://docs.gains.trade/developer/api-reference/endpoint/solana-campaign-eligibility get /api/campaigns/eligibility/solana/{address} Checks broad Solana address eligibility across active campaigns. ### Endpoint `GET /api/campaigns/eligibility/solana/{address}` Checks broad Solana address eligibility across active campaigns. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ---------------------- | | `address` | path | Yes | string | Solana wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/campaigns/eligibility/solana/7gcMVtk3vQh4aJwJizxmmDTVXcJLRXKrqXyPcU2ZJq5j" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Check Solana Campaign Eligibility By ID Source: https://docs.gains.trade/developer/api-reference/endpoint/solana-campaign-eligibility-by-id get /api/campaigns/{campaignId}/eligibility/solana/{address} Checks Solana address eligibility for a specific campaign. ### Endpoint `GET /api/campaigns/{campaignId}/eligibility/solana/{address}` Checks Solana address eligibility for a specific campaign. ### Parameters | Parameter | Location | Required | Type | Description | | ------------ | -------- | -------- | ------ | ---------------------- | | `campaignId` | path | Yes | string | Campaign ID. | | `address` | path | Yes | string | Solana wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/campaigns/campaign-id/eligibility/solana/7gcMVtk3vQh4aJwJizxmmDTVXcJLRXKrqXyPcU2ZJq5j" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Get Solana Token Balance Source: https://docs.gains.trade/developer/api-reference/endpoint/solana-usdc-balance get /api/dapp/solana/usdc-balance/{address} Returns a Solana SPL token balance and token account using backend RPC fallbacks. ### Endpoint `GET /api/dapp/solana/usdc-balance/{address}` Returns a Solana SPL token balance and token account using backend RPC fallbacks. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ----------------------------------------- | | `address` | path | Yes | string | Solana wallet address. | | `mint` | query | No | string | SPL token mint. Defaults to mainnet USDC. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/solana/usdc-balance/7gcMVtk3vQh4aJwJizxmmDTVXcJLRXKrqXyPcU2ZJq5j" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 502. Error responses generally return an `error` or `message` field. # Get Chain Stats Source: https://docs.gains.trade/developer/api-reference/endpoint/stats get /api/stats Returns protocol and trading statistics for a chain. ### Endpoint `GET /api/stats` Returns protocol and trading statistics for a chain. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/stats?chainId=42161" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 503, 500. Error responses generally return an `error` or `message` field. # Get GNS Total Supply Source: https://docs.gains.trade/developer/api-reference/endpoint/total-supply get /api/total-supply Returns the latest GNS total supply from cached stats. ### Endpoint `GET /api/total-supply` Returns the latest GNS total supply from cached stats. ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/total-supply" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200. Error responses generally return an `error` or `message` field. # Get Trading History Window Source: https://docs.gains.trade/developer/api-reference/endpoint/trading-history get /api/trading-history/{window} Returns all trades for a recent time window. ### Endpoint `GET /api/trading-history/{window}` Returns all trades for a recent time window. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `window` | path | Yes | string | Time window: 24h, 48h, or 72h. | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/trading-history/24h?chainId=42161" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses generally return an `error` or `message` field. # Get Trading History Stats Source: https://docs.gains.trade/developer/api-reference/endpoint/trading-history-stats get /api/trading-history/{window}/stats Returns precomputed trading stats for a recent time window. ### Endpoint `GET /api/trading-history/{window}/stats` Returns precomputed trading stats for a recent time window. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------- | --------------------------------------------------------------------------- | | `window` | path | Yes | string | Supported values: 24h, 48h, 72h. | | `chainId` | query | Yes | integer | Blockchain chain ID. Common values: 42161 Arbitrum, 8453 Base, 137 Polygon. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/trading-history/24h/stats?chainId=42161" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 500. Error responses generally return an `error` or `message` field. # Create Transak Widget URL Source: https://docs.gains.trade/developer/api-reference/endpoint/transak-widget-url post /api/dapp/transak/widget-url Creates a Transak on-ramp widget URL. ### Endpoint `POST /api/dapp/transak/widget-url` Creates a Transak on-ramp widget URL. ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X POST "https://backend-global.gains.trade/api/dapp/transak/widget-url" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Update Bridge Flow Source: https://docs.gains.trade/developer/api-reference/endpoint/update-bridge-flow put /api/dapp/bridge/flows/{srcHash} Updates fields on a bridge flow record. ### Endpoint `PUT /api/dapp/bridge/flows/{srcHash}` Updates fields on a bridge flow record. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | ------------------------ | | `srcHash` | path | Yes | string | Source transaction hash. | ### Request Body Send JSON matching the schema shown in the generated API panel. ### Usage Example ```bash theme={null} curl -X PUT "https://backend-global.gains.trade/api/dapp/bridge/flows/0xSOURCE_HASH" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 400, 404, 500. Error responses generally return an `error` or `message` field. # Get VIP Status Source: https://docs.gains.trade/developer/api-reference/endpoint/vip-status get /api/vip/{address} Returns VIP status for a wallet. ### Endpoint `GET /api/vip/{address}` Returns VIP status for a wallet. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------- | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/vip/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Get Wallet Associations Source: https://docs.gains.trade/developer/api-reference/endpoint/wallet-associations get /api/dapp/wallet/associated/{address} Returns wallets associated with an address. ### Endpoint `GET /api/dapp/wallet/associated/{address}` Returns wallets associated with an address. ### Parameters | Parameter | Location | Required | Type | Description | | --------- | -------- | -------- | ------ | --------------- | | `address` | path | Yes | string | Wallet address. | ### Usage Example ```bash theme={null} curl -X GET "https://backend-global.gains.trade/api/dapp/wallet/associated/0x0000000000000000000000000000000000000000" ``` ### Response Structure The generated API panel lists the response schema for status codes: 200, 500. Error responses generally return an `error` or `message` field. # Backend API Reference Source: https://docs.gains.trade/developer/api-reference/introduction REST reference for Gains Network backend services. Gains exposes two public backend surfaces: * `backend-global.gains.trade` for cross-chain statistics, personal trading history, contests, dapp helper APIs, campaigns, VIP, and notifications. * `backend-.gains.trade` for chain-specific trading variables, open trades, rewards, and legacy contest caches. No authentication is required for public read endpoints. Some write/helper endpoints are intended for the Gains frontend and may enforce rate limits or signature validation. Use the generated endpoint pages in this section for parameters, examples, and response schemas. # Integrators Source: https://docs.gains.trade/developer/integrators Overview for dApp and contract integrations Docs are under development and actively being updated. Please reach out to the team through Discord or Telegram with questions. This will speed up your integration and help the team prioritize doc improvements. The following resources begin to detail the services and call patterns required to effectively provide information, place and manage trades for users. There are four separate systems: * **Trading contracts**: Interacting with trading protocol directly * **Delegated trading**: Submitting trades from an approved agent wallet or backend signer * **Backend services**: Historical data and proxy for on-chain data (active trades and live events) * **Price feed**: Access to Gains' Decentralized Oracle Network (DON) for accurate pricing data # Backend Source: https://docs.gains.trade/developer/integrators/backend Details how to fetch trade data from off-chain services Backend services, for the purpose of managing trades, do not provide anything that can't be fetched or listened to directly on-chain. It is recommended to use Gains backends when possible however to improve resilience against RPC issues - service is optimized for uptime. ## DNS Common DNS syntax - `backend-.gains.trade` * Arbitrum: [https://backend-arbitrum.gains.trade](https://backend-arbitrum.gains.trade/trading-variables) * Base: [https://backend-base.gains.trade](https://backend-base.gains.trade) * Polygon: [https://backend-polygon.gains.trade](https://backend-polygon.gains.trade/trading-variables) * Sepolia: [https://backend-sepolia.gains.trade](https://backend-sepolia.gains.trade/trading-variables) * Arbitrum WS: `wss://backend-arbitrum.gains.trade` * Base WS: `wss://backend-base.gains.trade` * Polygon WS: `wss://backend-polygon.gains.trade` * Sepolia WS: `wss://backend-sepolia.gains.trade` *NOTE: No auth is required for accessing REST GET endpoints and the WebSocket event stream. However, rate limiting is in place, so please fetch data only as necessary and rely on the event stream to keep your data updated.* ## Backend types You can find backend return types [HERE](#backend-types) ## v10 Update As of v10, the SDK now offers normalization for both trading variables and trades. Current version: [@gainsnetwork/sdk@1.0.0-rc1](https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.0.0-rc1) For most SDK interactions you will need `tradingVariables` object. Learn below how to fetch it and transform it to use within SDK. #### Example: fetching and transforming trading variables ```javascript theme={null} import { transformGlobalTradingVariables } from '@gainsnetwork/sdk'; // fetch const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`); const tradingVariablesBackend = await tradingVariablesResponse.json(); // transform const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend); ``` #### For detailed \`/trading-variables\` information, see "Common Endpoints" section below #### Example: getting all trades for current address ```javascript theme={null} import { transformGlobalTradingVariables, transformGlobalTrades } from '@gainsnetwork/sdk'; // fetch const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`); const tradingVariablesBackend = await tradingVariablesResponse.json(); // transform const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend); const { pairs, collaterals } = globalTradingVariables; const transformedTradesForTrader = transformGlobalTrades( tradingVariablesBackend.allTrades, pairs, , collaterals ); ``` #### Example: converting [TradeContainerBackend](/developer/technical-reference/backend/backend-types#tradecontainerbackend) to [TradeContainer](/developer/technical-reference/sdk/client-types#tradecontainer) ```javascript theme={null} import { transformGlobalTradingVariables, convertTradeContainer } from '@gainsnetwork/sdk'; // fetch const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`); const tradingVariablesBackend = await tradingVariablesResponse.json(); // transform const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend); // example of single TradeContainerBackend const someTradeBackend = tradingVariablesBackend.allTrades[0]; const tradeConverted = convertTradeContainer(someTradeBackend, globalTradingVariables.collaterals); // returns TradeContainer ``` #### Example: converting array of [FeeBackend](/developer/technical-reference/backend/backend-types#feebackend) to [FeeFrontend](/developer/technical-reference/sdk/client-types#fee) ```typescript theme={null} import { transformGlobalTradingVariables, convertFees } from '@gainsnetwork/sdk'; // fetch const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`); const tradingVariablesBackend = await tradingVariablesResponse.json(); // transform const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend); const fees = tradingVariablesBackend.fees; // FeeBackend[] const feesConverted = convertFees(fees); // returns Fee[] ``` ## Common Endpoints ### Trading Variables **Deprecation notice:** Since October 27, 2025, `allTrades` is no longer returned by the `/trading-variables` endpoint. Use the `/open-trades/` endpoint to fetch open trades. Provides main data necessary for opening, closing, and managing trades. Payload also contains all active trades (`allTrades`). Request: `GET /trading-variables` Response: ```ts theme={null} { lastRefreshed: "2024-05-20T21:07:02.133Z", // string, timestamp refreshId: 6180, // number, unique identifier tradingState: 0, // ITradingStorage.TradingActivated, 0: Activated, 1: CloseOnly, 2: Paused maxGainP: 1000000, // deprecated; Maximum PNL % is no longer enforced marketOrdersTimeoutBlocks: 200, // number of blocks after which an unsuccessful order's collateral can be reclaimed globalTradeFeeParams: { // object, breakdown of how `fees[feeIndex].totalPositionSizeFeeP` is split per category in 1e3 precision (%) referralFeeP: "5000", govFeeP: "24500", triggerOrderFeeP: "4000", gnsOtcFeeP: "56500", gTokenFeeP: "15000" }, pairs : [ // array, containing objects for each trading pair { from: "ETH", to: "USD", spreadP: "400000000", groupIndex: "0", feeIndex: "0" }, // Other trading pairs... ], groups: [ // array, containing objects for each trading group { name: "crypto", minLeverage: "2", maxLeverage: "150" }, // Other trading groups... ], fees: [ // array, containing objects for each fee category { totalPositionSizeFeeP: "600000000", // % in 1e10 precision totalLiqCollateralFeeP: "100000000000", // % in 1e10 precision oraclePositionSizeFeeP: "20000000", // % in 1e10 precision minPositionSizeUsd: "1250000" // USD in 1e3 precision, fee floor position size }, // Other fee categories... ], pairInfos: { maxLeverages: [], // array, leverage overrides for each pair index for risk management pairDepths: [] // array, 1% depth (in USD) for current price per each pair index pairFactors: [] // array, protection close & cumulative factors for each pair index }, collaterals: [ // array, containing objects for each supported collateral { collateralIndex: 1, collateral: "0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1", // string, collateral token address e.g., WETH, USDC, DAI symbol: "DAI", isActive: true, prices: {}, // collateral / GNS USD prices collateralConfig: {}, // collateral precision and decimals gToken: {}, // address and market cap of gToken e.g., gWETH, gUSDC, gDAI borrowingFees: {}, // fees for every group and pair index fundingFees: {}, // funding fee & skew params for each pair pairOis: {}, // all OIs in collateral & token size for each pair pairSkewDepths: {} }, // Other collaterals... ], counterTradeSettings: {} // max leverage and fee discount for each pair if opened as counter trade sssTokenBalance: "23314652901338666091114242", // string, amount of $GNS staked in single-side staking sssLegacyTokenBalance: "112675327174399043872284", // string, legacy single-side staking balance sssRewardTokens: ["0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1", ...], // array, addresses of tokens (collaterals) distributed as rewards vaultClosingFeeP: "50", // number, vault closing fee percentage maxNegativePnlOnOpenP: 400000000000, // number, maximum negative PnL threshold upon trade opening blockConfirmations: 1, // number, required block confirmations oiWindowsSettings: { // object, settings for cumulative volume windows startTs: 1704401556, windowsDuration: 150, windowsCount: 4 }, oiWindows: [ // array, cumulative volume window objects for each trading pair { "1645": { oiLongUsd: "8484501256212500000000", // open longs + close shorts oiShortUsd: "17262712465625000000000" // close longs + open shorts }, // Other windows... }, // Other trading pairs... ], feeTiers: { // object, gCredit system fee tiers tiers: [ // array, all possible point tiers/thresholds { feeMultiplier: "975", pointsThreshold: "6000000" }, // Other tiers... ], multipliers: [ // array, point multipliers for each trading group (by index) "8000", // Other multipliers... ] }, // @deprecated please use `/open-trades` to fetch open trades allTrades: [ // array, objects representing each active trade/order { trade: { user: "0x7152BC14A1eFBfD553D1Cbc7D4E49e63Dae5A669", index: "0", // user's trade index pairIndex: "19", leverage: "150000", // number, leverage supports up to 3 decimals long: true, isOpen: true, collateralIndex: "1", tradeType: "2", // number, 0 - MARKET, 1 - LIMIT, 2 - STOP collateralAmount: "550000000000000000000", openPrice: "7700000000", tp: "8162000000", sl: "0", positionSizeToken: "0", isCounterTrade: false // }, tradeInfo: { createdBlock: "192695790", tpLastUpdatedBlock: "192695790", slLastUpdatedBlock: "192695790", maxSlippageP: "1000", lastOiUpdateTs: 0, collateralPriceUsd: "0" }, initialAccFees: { accPairFee: "0", accGroupFee: "0", block: "0" }, liquidationParams: {}, tradeFeesData: {}, uiRealizedPnlData: {} }, // Other trades... ], currentBlock: 213452457, currentL1Block: 19916646, isForexOpen: true, isStocksOpen: false, isIndicesOpen: false, isCommoditiesOpen: true, } ``` ### Open Trades Returns all open trades (matches deprecated `allTrades` output from `/trading-variables` endpoint). Optionally specify trader address for filtering. Request: `GET /open-trades`\ `GET /open-trades/
`\ \ Response: ``` // array, objects representing each active trade/order // when
is provided, only open trades that match the address are returned [ { trade: { user: "0x7152BC14A1eFBfD553D1Cbc7D4E49e63Dae5A669", index: "0", // user's trade index pairIndex: "19", leverage: "150000", // number, leverage supports up to 3 decimals long: true, isOpen: true, collateralIndex: "1", tradeType: "2", // number, 0 - MARKET, 1 - LIMIT, 2 - STOP collateralAmount: "550000000000000000000", openPrice: "7700000000", tp: "8162000000", sl: "0", positionSizeToken: "0", isCounterTrade: false // }, tradeInfo: { createdBlock: "192695790", tpLastUpdatedBlock: "192695790", slLastUpdatedBlock: "192695790", maxSlippageP: "1000", lastOiUpdateTs: 0, collateralPriceUsd: "0" }, initialAccFees: { accPairFee: "0", accGroupFee: "0", block: "0" }, liquidationParams: {}, tradeFeesData: {}, uiRealizedPnlData: {} }, // Other trades... ], ``` ### User Trading Variables Provides useful trader specific data, such as pending order IDs and fee tiers. Request: `GET /user-trading-variables/
` Response: ```ts theme={null} { pendingMarketOrdersIds: [], pendingMarketOrders: [], // array, user's market orders that are currently being processed feeTiers: { // object, gCredit system details traderInfo: { lastDayUpdated: 19864, // number, last recorded day on-chain trailingPoints: "199553481323944469547134920" // string, cumulative user's gCredit points }, lastDayUpdatedPoints: "5397470676054960000000000", // string, user's on-chain points as of the last update inboundPoints: "5397470676054960000000000", // string, points expected to be added the next day outboundPoints: "0", // string, points expected to expire the next day expiredPoints: [] // array of strings, points for each expired day not yet recorded on-chain }, collaterals: [ // array, user holdings and allowances for each collateral { balance: "5000086815959570800000", // string, user's collateral balance allowance: "5000086815959570800000", // string, user's collateral allowance decimals: 18 // number, number of decimal places for the collateral }, // Other collaterals... ] } ``` ### Historical Trades Provides all historical trades (open & closed) for a given address Request: `GET /personal-trading-history-table/
` Provides all open & closed trades in last 24hrs `GET /trading-history-24h` Response (same for both historical endpoints): ```ts theme={null} [ { date: "2024-05-21T12:04:44.000Z", // string, timestamp pair: "W/USD", address: "0x1454A3be2322B60B813713E11af36bbAF4CfeeA7", action: "TradeOpenedMarket", // string, type of trade action (see TradeAction type below) price: 0.5697297128, collateralPriceUsd: 1.0003745, long: 1, // number, position direction (1 for long, 0 for short) size: 3160.946482, // number, trade collateral leverage: 7, pnl_net: 0, // number, net profit and loss after fees tx: "0x7e71dd845bb791803c16b13e4e5fe6c1a764dec4aef8205dd1f7ab8c91309aff", collateralIndex: 1, collateralDelta: 5, // number if collateral updated through partials leverageDelta: 20, // number if leverage updated through partials marketPrice: 0.5837195234 // number, market price during position size update through partials }, // Other trades... ] // Possible values for TradeAction type TradeAction = [ 'TradeOpenedMarket', 'TradeClosedMarket', 'TradeOpenedLimit', 'TradeClosedTP', 'TradeClosedSL', 'TradeClosedLIQ' 'TradeLeverageUpdate', 'TradePosSizeIncrease', 'TradePosSizeDecrease' ]; ``` ## Event Stream As mentioned in [Trading Contracts](/developer/integrators/trading-contracts#events), backend event streams can serve as proxies for on-chain trade events. The stream will publish both unconfirmed and confirmed events. Unconfirmed events are published until the risk a block is reorged is negligible, at which point a confirmed event is sent. For most integrations, only confirmed events (`liveEvent`) need to be listened to. Backends also publish structured, post-processed events based on what on-chain event has just taken place. For example, `registerTrade` provides a full trade struct following the raw event `MarketOrderExecuted`. This is to limit how much clients need to fetch additional data. Structure: ```javascript theme={null} { name: , value: { }, } ``` Common event names: * `liveEvents` - raw on-chain events. Payload is identical to on-chain event. * `registerTrade` - trade has been registered * `unregisterTrade` - trade has been closed * `updateTrade` - trade SL/TP has been updated * `updateLeverage` - trade leverage updated (collateral removed or added) * `updatePositionSize` - trade position size updated (adding to position or partial close) * `tradingVariables` - updated `/trading-variables` payload * `currentBlock` - L2 block number for network * `currentL1Block` - L1 block number for network * `deepReorg` - Reorg has been detected - refresh data * `new-trade-history` - New trade history document # Contests Source: https://docs.gains.trade/developer/integrators/contests API endpoints for building trading contests and leaderboards on Gains data. ### Base URL ``` https://backend-global.gains.trade/api ``` ### Endpoints #### 1. List All Contests ``` GET /contests ``` **Response:** ```json theme={null} [ { "id": "trickortrade", "start": 1729608000000, "end": 1732026000000, "chains": ["arbitrum"], "isActive": true } ] ``` *** #### 2. Get Contest Details ``` GET /contests/:id ``` **Response:** ```json theme={null} { "id": "trickortrade", "start": 1729608000000, "end": 1732026000000, "chains": ["arbitrum"], "isActive": true, "stats": { "totalTraders": 1247, "totalTrades": 8931, "totalPnl": 125430.5, "totalVolumePoints": 9847231.25, "top300VolumePoints": 8234192.1 }, "rewards": { "pnlAbsolute": { "1": 40000, "2": 20000, "3": 15000 // ... ranks 1-50 }, "volume": { "proportional": true, "pool": 200000, "topN": 300 } } } ``` *** #### 3. Get Leaderboard ``` GET /contests/:id/leaderboard ``` **Query Parameters:** * `sortBy` (optional): `"pnl"` or `"volume"` (default: `"pnl"`) * `limit` (optional): Number of results to return (default: all) * `offset` (optional): Pagination offset (default: 0) **Example Request:** ``` GET /contests/trickortrade/leaderboard?sortBy=volume&limit=50&offset=0 ``` **Response:** ```json theme={null} { "contestId": "trickortrade", "sortBy": "volume", "pagination": { "total": 1247, "offset": 0, "limit": 50, "count": 50, "hasMore": true }, "leaderboard": [ { "traderAddress": "0x1234...5678", "pnlUsd": 12450.75, "volumeUsd": 2450000.0, "volumePoints": 984532.5, "tradeCount": 127, "lastUpdated": 1729123456789, "rank": 1 } // ... more traders ] } ``` *** #### 4. Get Trader Stats ``` GET /contests/:id/leaderboard/:trader ``` **Example Request:** ``` GET /contests/trickortrade/leaderboard/0x1234567890abcdef ``` **Response:** ```json theme={null} { "contestId": "trickortrade", "trader": "0x1234567890abcdef", "stats": { "pnlUsd": 12450.75, "volumeUsd": 2450000.0, "volumePoints": 984532.5, "tradeCount": 127, "lastUpdated": 1729123456789 }, "rankings": { "pnl": 5, "volume": 1 }, "rewards": { "pnl": 8500, "volume": 23894.5, "total": 32394.5 } } ``` *** ### Data Refresh Rates 60-90 seconds ### Notes * All timestamps are in Unix milliseconds (UTC) * Trader addresses are case-insensitive * Volume rewards are proportionally distributed among top 300 traders * PnL rewards are fixed amounts for top 50 traders * `volumePoints` represents time-weighted volume (used for rankings) * `volumeUsd` represents raw dollar volume (all opens/increases/decreases/closes) # Delegated Trading Source: https://docs.gains.trade/developer/integrators/delegated-trading Use an agent wallet or backend signer to submit trades for a trader Delegated trading lets a trader approve another EOA to submit trading transactions on their behalf. This is the on-chain primitive used by [One-Click Trading](/gtrade-leveraged-trading/one-click-trading-1ct), but it can also be used by backend services, bots, and partner integrations. The trader keeps custody of their collateral and positions. The delegated wallet signs and pays gas for transactions, while the protocol records the trade under the trader address. ## Flow 1. The trader approves an agent wallet with [`setTradingDelegate`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#settradingdelegate). 2. The agent wallet is funded with native gas token. 3. The backend builds the calldata for a normal trading action, such as [`openTrade`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#opentrade), [`closeTradeMarket`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#closetrademarket), [`updateSl`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#updatesl), or [`updateTp`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#updatetp). 4. The backend wraps that calldata in [`delegatedTradingAction`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#delegatedtradingaction), passing the trader address and the action calldata. 5. The agent wallet submits the wrapped transaction to `GNSMultiCollatDiamond`. During the delegated call, the trading facet resolves the effective sender as the trader address. Collateral transfers, trade ownership, and PnL accounting therefore remain tied to the trader. ## Approve a delegate The trader must approve the delegate from their own wallet: ```typescript theme={null} import { ethers } from "ethers"; const diamond = new ethers.Contract( GNS_MULTI_COLLAT_DIAMOND, [ "function setTradingDelegate(address delegate)", "function getTradingDelegate(address trader) view returns (address)", "function removeTradingDelegate()", ], traderSigner ); await diamond.setTradingDelegate(agentWalletAddress); const currentDelegate = await diamond.getTradingDelegate(await traderSigner.getAddress()); ``` Each trader has one active trading delegate. Calling `setTradingDelegate` replaces the previous delegate. Calling `removeTradingDelegate` clears it. ## Submit from a backend signer The agent wallet signs the wrapped transaction. The trader address is still passed into the wrapped call: ```typescript theme={null} import { Wallet } from "ethers"; import { TradingSDK, SupportedChainId } from "@gainsnetwork/trading-sdk"; const agentWallet = new Wallet(process.env.AGENT_PRIVATE_KEY!, provider); const trader = "0x..."; // user who approved agentWallet.address const tradingSdk = new TradingSDK({ chainId: SupportedChainId.Arbitrum, signer: agentWallet, }); await tradingSdk.initialize(); const openTradeTx = await tradingSdk.build.openTrade({ user: trader, pairIndex: 0, collateralAmount: 100_000_000n, openPrice: 66108.8, long: true, leverage: 2, tp: 0, sl: 0, collateralIndex: 3, tradeType: 0, maxSlippage: 1, }); const response = await tradingSdk.write.delegatedTradingAction({ trader, data: openTradeTx.data, }); await response?.wait(); ``` The trader must still satisfy the normal requirements for the underlying action. For example, `openTrade` with ERC-20 collateral requires the trader to have enough collateral and to have approved the diamond to pull that collateral. ## Direct contract call You can also build the wrapped calldata manually: ```typescript theme={null} import { ethers } from "ethers"; const diamond = new ethers.Contract( GNS_MULTI_COLLAT_DIAMOND, [ "function openTrade((address user,uint32 index,uint16 pairIndex,uint24 leverage,bool long,bool isOpen,uint8 collateralIndex,uint8 tradeType,uint120 collateralAmount,uint64 openPrice,uint64 tp,uint64 sl,uint192 __placeholder) trade,uint16 maxSlippageP,address referrer)", "function delegatedTradingAction(address trader, bytes callData) returns (bytes)", ], agentWallet ); const callData = diamond.interface.encodeFunctionData("openTrade", [ trade, maxSlippageP, ethers.ZeroAddress, ]); await diamond.delegatedTradingAction(trader, callData); ``` ## Supported actions Delegation is designed for trading and trade management. Common supported actions include: * `openTrade` * `closeTradeMarket` * `updateSl` * `updateTp` * `updateOpenOrder` * `cancelOpenOrder` * `updateLeverage` * `increasePositionSize` * `decreasePositionSize` * `updateMaxClosingSlippageP` * `cancelOrderAfterTimeout` The current contracts also allow a delegate to initiate `withdrawPositivePnl`. Any withdrawn PnL is transferred to the trader, not to the delegate. ## Unsupported actions Functions guarded by `notDelegatedAction` cannot be executed through `delegatedTradingAction`. This includes native-token wrapper flows and trigger-order flows: * `openTradeNative` * `increasePositionSizeNative` * `updateLeverageNative` * `triggerOrder` * `triggerOrderWithSignatures` * nested `delegatedTradingAction` Use ERC-20 collateral flows for delegated opens and position increases. On ApeChain, delegated trading requires wrapped collateral because native `$APE` does not follow ERC-20 `approve` and `transferFrom` semantics. ## Security notes Delegated trading is broad trading authority, not a granular permission system. A delegate cannot withdraw user funds to itself through the trading delegation flow, but it can submit trading actions that affect the trader's positions and collateral. Recommended practices: * Use a dedicated agent wallet per integration or user group. * Keep the agent wallet funded only with enough gas for expected operations. * Let users revoke access with `removeTradingDelegate`. * Enforce any additional policy, such as max trade size, allowed pairs, or disabled PnL withdrawals, in your backend before signing transactions. * Treat backend policy as off-chain protection. The current on-chain delegation model does not enforce per-function, per-market, per-size, or expiry-scoped permissions. ## References * [Trading Contracts](/developer/integrators/trading-contracts) * [`setTradingDelegate`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#settradingdelegate) * [`delegatedTradingAction`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#delegatedtradingaction) * [`getTradingDelegate`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#gettradingdelegate) # Guides Source: https://docs.gains.trade/developer/integrators/guides Examples of common use cases ## How-to guides ## Migration guides # Backend Endpoint Refactor Source: https://docs.gains.trade/developer/integrators/guides/backend-endpoint-refactor Backend endpoint refactor (Oct 2025): leaner trading-variables and the new open-trades endpoints. Since October 27, 2025, in an effort to reduce the size of payloads returned, the `/trading-variables` endpoint omits `allTrades`. Use the endpoints below to fetch open trades and a leaner version of trading variables.\ \ **TLDR**: * `GET /trading-variables` partially deprecated * Currently returns the `allTrades` property. * `allTrades` property was removed on 10/27/2025. * `GET /trading-variables/all` new * Returns trading variables with an empty `allTrades` property. * Significantly reduces payload size and speeds up request time. * `GET /open-trades/` new * Returns an array of open trades. Trade container types remain the same. * Replaces `allTrades` payload from deprecated `/trading-variables` endpoint. * *Optional:* provide an address to filter returned trades. Significantly reduces payload size. * Important: If provided, `address` **MUST** be checksummed. # Building the virtual order book Source: https://docs.gains.trade/developer/integrators/guides/building-the-virtual-order-book How to derive the gTrade virtual order book from public trading variables, live prices, and SDK price-impact helpers. gTrade does not expose a public REST endpoint that returns the virtual order book (VOB) as a ready-made ladder. The VOB shown in the trading interface is derived client-side from public data: * trading variables from the chain-specific backend * the current price for the pair * SDK price-impact helpers The VOB is synthetic. gTrade does not match orders through a resting order book; it uses shared vault liquidity and deterministic price-impact rules. The VOB is a visualization of available execution liquidity at different price-impact levels. ## Public inputs Use the chain-specific trading backend for pair, fee, depth-band, OI, skew, and collateral state: ```bash theme={null} curl "https://backend-arbitrum.gains.trade/trading-variables/all" ``` For a smaller response, request only the fields needed for VOB construction: ```bash theme={null} curl "https://backend-arbitrum.gains.trade/trading-variables/pairInfos,depthBandsMapping,pairs,fees,collaterals,oiWindows,oiWindowsSettings" ``` The depth-band fields are: * `pairInfos.pairDepthBands` - per-pair depth-band slots * `depthBandsMapping` - global mapping for the 30 depth-band offsets Use the pricing backend for the current pair price: ```bash theme={null} curl "https://backend-pricing.eu.gains.trade/charts" ``` For a continuously updated VOB, fetch the initial `/charts` snapshot and then keep prices fresh with the price stream documented in [Live prices and OHLC snapshots](/developer/integrators/price-feed). ## High-level flow 1. Fetch trading variables from `backend-.gains.trade`. 2. Convert the raw backend response with `transformGlobalTradingVariables`. 3. Fetch current prices from `/charts` or maintain them from the pricing WebSocket. 4. Build the skew-adjusted market price with `buildMarketPriceContext` and `getCurrentMarketPrice`. 5. Probe opening price impact for a set of target impacts and position sizes. 6. Convert the probes into ask and bid levels. ## Example This example mirrors the approach used by the gTrade frontend: it creates a position-size ladder for one pair and one collateral. ```typescript theme={null} import { buildMarketPriceContext, buildTradeOpeningPriceImpactContext, ContractsVersion, getCurrentMarketPrice, getFixedSpreadP, getTradeOpeningPriceImpact, transformGlobalTradingVariables, } from "@gainsnetwork/sdk"; type VobLevel = { price: number; sizeUsd: number; cumulativeUsd: number; impactPct: number; }; type VirtualOrderBook = { marketPrice: number; asks: VobLevel[]; bids: VobLevel[]; }; const TARGET_IMPACTS_PCT = [ 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.02, 0.03, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, ]; const TARGET_SIZES_USD = [ 1_000, 5_000, 10_000, 25_000, 50_000, 75_000, 100_000, 150_000, 250_000, 500_000, 750_000, 1_000_000, 2_500_000, 5_000_000, 10_000_000, ]; const MIN_LEVEL_SIZE_USD = 2_000; const MAX_LEVELS = 15; const MAX_IMPACT_PCT = 2; const IMPACT_SIMILARITY_THRESHOLD = 0.0001; async function buildVirtualOrderBook( chainBackendUrl: string, pairIndex: number, collateralIndex: number ): Promise { const [rawTradingVariables, charts] = await Promise.all([ fetch(`${chainBackendUrl}/trading-variables/all`).then((res) => res.json()), fetch("https://backend-pricing.eu.gains.trade/charts").then((res) => res.json()), ]); const { globalTradingVariables, blockNumber } = transformGlobalTradingVariables(rawTradingVariables); const oraclePrice = charts.closes[pairIndex]; const pair = globalTradingVariables.pairs?.[pairIndex]; const collateral = globalTradingVariables.collaterals?.[collateralIndex - 1]; const fee = pair ? globalTradingVariables.fees?.[pair.feeIndex] : undefined; if (!oraclePrice || !pair || !fee || !collateral) { return null; } const marketPriceContext = buildMarketPriceContext(collateral, pairIndex); const currentMarketPrice = getCurrentMarketPrice( pairIndex, oraclePrice, marketPriceContext ); const marketPrice = marketPriceContext.skewDepth > 0 ? currentMarketPrice.marketPrice : oraclePrice; const pairDepthBands = globalTradingVariables.pairDepthBands?.[pairIndex]; const hasDepth = (pairDepthBands?.above?.totalDepthUsd ?? 0) > 0 || (pairDepthBands?.below?.totalDepthUsd ?? 0) > 0; const hasSkew = (collateral.pairSkewDepths?.[pairIndex] ?? 0) > 0; if (!hasDepth && !hasSkew) { const halfSpreadPct = getFixedSpreadP(pair.spreadP, true, true); return { marketPrice, asks: [ { price: marketPrice * (1 + halfSpreadPct / 100), sizeUsd: 0, cumulativeUsd: 0, impactPct: halfSpreadPct, }, ], bids: [ { price: marketPrice * (1 - halfSpreadPct / 100), sizeUsd: 0, cumulativeUsd: 0, impactPct: -halfSpreadPct, }, ], }; } const impactContext = buildTradeOpeningPriceImpactContext( globalTradingVariables, collateralIndex, pairIndex, { currentBlock: blockNumber ?? 0, contractsVersion: ContractsVersion.V10, protectionCloseFactorWhitelist: false, } ); if (!impactContext) { return null; } const impactForSizeUsd = (sizeUsd: number, long: boolean): number | null => { try { const result = getTradeOpeningPriceImpact( { collateralIndex, pairIndex, long, collateralAmount: sizeUsd / impactContext.collateralPriceUsd, leverage: 1, openPrice: oraclePrice, pairSpreadP: pair.spreadP, fee, contractsVersion: ContractsVersion.V10, isCounterTrade: false, }, impactContext ); return result.totalPriceImpactPFromMarketPrice; } catch { return null; } }; const sizeForImpactUsd = (targetImpactPct: number, long: boolean): number => { let minSizeUsd = 100; let maxSizeUsd = 50_000_000; const tolerance = Math.max(targetImpactPct * 0.1, 0.0001); for (let i = 0; i < 20 && maxSizeUsd - minSizeUsd > 100; i++) { const midSizeUsd = (minSizeUsd + maxSizeUsd) / 2; const impactPct = impactForSizeUsd(midSizeUsd, long); if (impactPct === null) { maxSizeUsd = midSizeUsd; continue; } const absImpactPct = Math.abs(impactPct); if (Math.abs(absImpactPct - targetImpactPct) < tolerance) { return midSizeUsd; } if (absImpactPct < targetImpactPct) { minSizeUsd = midSizeUsd; } else { maxSizeUsd = midSizeUsd; } } return (minSizeUsd + maxSizeUsd) / 2; }; const buildSide = (long: boolean): VobLevel[] => { const bands: Array<{ cumulativeUsd: number; impactPct: number }> = []; const addBand = (cumulativeUsd: number) => { if (bands.length >= MAX_LEVELS || cumulativeUsd < MIN_LEVEL_SIZE_USD) { return; } const impactPct = impactForSizeUsd(cumulativeUsd, long); if (impactPct === null || Math.abs(impactPct) > MAX_IMPACT_PCT) { return; } if ( bands.some( (band) => Math.abs(band.impactPct - impactPct) < IMPACT_SIMILARITY_THRESHOLD ) ) { return; } bands.push({ cumulativeUsd, impactPct }); }; for (const targetImpactPct of TARGET_IMPACTS_PCT) { addBand(sizeForImpactUsd(targetImpactPct, long)); } for (const targetSizeUsd of TARGET_SIZES_USD) { addBand(targetSizeUsd); } return bands .sort((a, b) => a.cumulativeUsd - b.cumulativeUsd) .slice(0, MAX_LEVELS) .map((band, index, sortedBands) => ({ price: marketPrice * (1 + band.impactPct / 100), sizeUsd: band.cumulativeUsd - (index > 0 ? sortedBands[index - 1].cumulativeUsd : 0), cumulativeUsd: band.cumulativeUsd, impactPct: band.impactPct, })); }; return { marketPrice, asks: buildSide(true), bids: buildSide(false), }; } const btcUsdcVob = await buildVirtualOrderBook( "https://backend-arbitrum.gains.trade", 0, // BTC/USD 3 // USDC collateral on Arbitrum; verify the index from collaterals for your chain ); console.log(btcUsdcVob); ``` ## Price selection The frontend VOB uses the current pair price from the pricing feed and then applies skew-market-price logic through the SDK. For live integrations: * use `/charts` for the initial snapshot * subscribe to the price WebSocket for updates * rebuild or throttle the VOB when the selected pair price changes See [Mark + Index prices introduction](/developer/integrators/guides/mark-+-index-introduction) if your integration separates mark and index prices. ## Fixed-spread pairs Some pairs do not have depth bands or skew depth. For those markets, the VOB has no size-dependent ladder. Show the fixed long and short execution prices from `getFixedSpreadP` instead. ## Operational notes * No authentication is required for public read endpoints, but rate limits apply. * Prefer `GET /trading-variables/all` when you need `currentBlock`. Use keyed trading variables when you already have a current block from another source. * `collateralIndex` is 1-based in SDK helpers; array access is `collaterals[collateralIndex - 1]`. * The displayed ask side corresponds to opening longs. The displayed bid side corresponds to opening shorts. * Pair availability and collateral availability vary by chain. Always derive pair and collateral metadata from the same chain backend you are using for the VOB. # Calculating borrowing fees Source: https://docs.gains.trade/developer/integrators/guides/calculating-borrowing-fees Learn how to calculate trader's borrowing fees ## Overview * Borrowing fees are paid only by one side (either longs or shorts) which is decided by current open interest (higher OI pays the fee) * Each pair is part of a group, meaning that borrowing fee should be calculated for pair and pair's group and the higher of two should be charged (never both) * Borrowing fee is charged on trader's position size (collateral \* leverage) ## Borrowing fee per block The formula for borrowing fee per block is: ``` feePerBlock * (abs(longOi - shortOi) / maxOi) ** feeExponent ``` ### *Example:* Let's calculate the borrowing fee for **ENA/USD** pair (`pairIndex` is `219`) against USDC collateral (`collateralIndex` is `3`) #### 1) Fetching Open Interest and Fees Access current open interests and fees for given collateral and pair index via [`trading-variables`](/developer/integrators/backend#trading-variables) endpoint described [**here**](/developer/integrators/backend#trading-variables)**.** #### 2) Calculating Pair Borrowing Fees To calculate ENA/USD borrowing fees, we use the following object retrieved from Step 1: ```javascript theme={null} tradingVariables.collaterals[2].borrowingFees.pairs[219] // collaterals[2] because its 0 indexed ``` ```javascript theme={null} { "oi": { "long": "228761980790000", // 1e10 "short": "59904000000000", // 1e10 "max": "8806660000000000" // 1e10 }, "feePerBlock": "100236", // 1e10 "feeExponent": "1", "groups": [ { "groupIndex": "2", ... } ], ... } ``` With these values, we can calculate the pair's borrowing fee (per block): ```javascript theme={null} feePerBlock = 0.0000100236 longOi = 22876.198079 shortOi = 5990.4 maxOi = 880666 pairFeePerBlock = 0.0000100236 * Math.abs(22876.198079 - 5990.4) / 880666 ** 1 = 1.9219146149012726e-7 ``` #### 3) Calculating Group Borrowing Fees Now we need to do the same for group fee, reading the `groupIndex` from the same `trading-variables` response (for this example, `groupIndex` is `2`). The process is the same as for calculating pair fees, using `groups` values of `borrowingFees`: ```javascript theme={null} tradingVariables.collaterals[2].borrowingFees.groups[2] ``` ```javascript theme={null} { "oi": { "long": "7704464978990000", // 1e10 "short": "1841270854980000", // 1e10 "max": "50906510000000000" // 1e10 }, "feePerBlock": "16871", // 1e10 "feeExponent": "1" ... } ``` Therefore, the group's borrowing fee (per block) will be: ```javascript theme={null} feePerBlock = 0.0000016871 longOi = 770446.497899 shortOi = 184127.085498 maxOi = 5090651 groupFeePerBlock = 0.0000016871 * Math.abs(770446.497899 - 184127.085498) / 5090651 ** 1 = 1.9431296324610092e-7 ``` In this example, `groupFeePairBlock`is greater than `pairFeePerBlok` (`1.9431296324610092e-7 > 1.9219146149012726e-7`) so `groupFeePairBlock` is the effective `feePerBlock`. #### 4) Estimating Borrowing fee per hour To estimate the hourly paid fee, we need to multiply the number of blocks per hour `feePerBlock`. ```javascript theme={null} feePerHour = blocksPerHour * Math.max(pairFeePerBlock, groupFeePerBlock) ``` For this example, on **Arbitrum** (12000 blocks per hour), the estimated borrowing fee per hour is: ```javascript theme={null} feePerHour = 12000 * Math.max(1.9219146149012726e-7, 1.9431296324610092e-7) // 0.002331755558953211% Borrowing (L) ``` Which corresponds to the **Gains** UI: # Calculating liquidation price Source: https://docs.gains.trade/developer/integrators/guides/calculating-liquidation-price Learn how to calculate any trade's liquidation price > *Note: This guide uses **Arbitrum Sepolia**. Use the latest [@gainsnetwork/sdk](https://www.npmjs.com/package/@gainsnetwork/sdk) release — the snippet below was originally written against an older beta and may need minor adjustments.* To calculate liquidation price, we need to use [SDK's](/developer/technical-reference/sdk) `getLiquidationPrice()` function. getLiquidationPrice: (trade: [Trade](/developer/technical-reference/sdk/client-types#trade), fee: [Fee](/developer/technical-reference/sdk/client-types#fee), initialAccFees: [InitialAccFees](/developer/technical-reference/sdk/client-types#initialaccfees), context: GetLiquidationPriceContext) => number; ## TradeContainer To calculate trade's liquidation price, we need to find a trade and its [TradeContainer](/developer/technical-reference/sdk/client-types#tradecontainer) first. TradeContainer is unique object per single trade and is containing all its information. By inspecting `allTrades` of backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) response, we're able to find all open trades & orders (each represented by single, unique [TradingContainerBackend](/developer/technical-reference/backend/backend-types#tradecontainerbackend) object). Lets pick last market trade (`trade.type` = 0 ) at time of writing this guide, which is: ```typescript theme={null} { "trade": { "user": "0xa110CC27a19f6853e9Aa8Bb8e2C603D7b02ea2df", "index": "350", "pairIndex": "103", "leverage": "45000", "long": true, "isOpen": true, "collateralIndex": "3", "tradeType": "0", "collateralAmount": "1938800000", "openPrice": "47781798348", "tp": "57338158017", "sl": "0" }, "tradeInfo": { "createdBlock": "72595369", "tpLastUpdatedBlock": "72595369", "slLastUpdatedBlock": "72595369", "maxSlippageP": "0", "lastOiUpdateTs": "0", "collateralPriceUsd": "0", "contractsVersion": "1", "lastPosIncreaseBlock": "72595369" }, "liquidationParams": { "maxLiqSpreadP": "500000000", "startLiqThresholdP": "900000000000", "endLiqThresholdP": "650000000000", "startLeverage": "25000", "endLeverage": "60000" }, "initialAccFees": { "accPairFee": "1461579560", "accGroupFee": "828216663", "block": "72595369" } } ``` This response is of [TradeContainerBackend](/developer/technical-reference/backend/backend-types#tradecontainerbackend) type, therefore we need to properly convert it to [TradeContainer](/developer/technical-reference/sdk/client-types#tradecontainer) type first (SDK uses [client types](/developer/technical-reference/sdk/client-types)). Converted and normalised trade will look like this: ```typescript theme={null} { "trade": { "user": "0xa110CC27a19f6853e9Aa8Bb8e2C603D7b02ea2df", "index": 350, "pairIndex": 103, "leverage": 45, "long": true, "isOpen": true, "collateralIndex": 3, "tradeType": 0, "collateralAmount": 1938.8, "openPrice": 4.7781798348, "sl": 0, "tp": 5.7338158017 }, "tradeInfo": { "createdBlock": 72595369, "tpLastUpdatedBlock": 72595369, "slLastUpdatedBlock": 72595369, "maxSlippageP": 1, "lastOiUpdateTs": 1724162804, "collateralPriceUsd": 1.0000162, "contractsVersion": 1, "lastPosIncreaseBlock": 72595369 }, "liquidationParams": { "maxLiqSpreadP": 0.0005, "startLiqThresholdP": 0.9, "endLiqThresholdP": 0.65, "startLeverage": 25, "endLeverage": 60 }, "initialAccFees": { "accPairFee": 0.146157956, "accGroupFee": 0.0828216663, "block": 72595369 } } ``` Respective `trade` and `initialAccFees` objects will be used as first and third arguments of SDK's `getLiquidationPrice()` while `liquidationParams` and `tradeInfo` will be helpful when crafting fourth argument (`context`). ## Fee Lets focus on second `getLiquidationPrice()` argument now, which is [Fee](/developer/technical-reference/sdk/client-types#fee). To find proper [Fee](/developer/technical-reference/sdk/client-types#fee) object, we need to compute `feeIndex` for given trade first. By calling backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) we're getting `pairs` and `fees` arrays. Remember that backend values should be normalised, see [Pair](/developer/technical-reference/sdk/client-types#pair) vs [PairBackend](/developer/technical-reference/backend/backend-types#pairbackend) and [Fee](/developer/technical-reference/sdk/client-types#fee) vs [FeeBackend](/developer/technical-reference/backend/backend-types#feebackend) With `pairs` and trade's `pairIndex` we compute `feeIndex`: > pairs\[trade.pairIndex].feeIndex Now we are able to find our [Fee](/developer/technical-reference/sdk/client-types#fee) by simply accessing `fees[feeIndex]`. Resulting object should look similar to this: ```typescript theme={null} { "openFeeP": 0.0003, "closeFeeP": 0.0006, "minPositionSizeUsd": 10000, "triggerOrderFeeP": 0.0002 } ``` ## Context We've now covered 3 arguments and are left with last one, the `GetLiquidationPriceContext`. There are few context parameters that we can pass here. All of them are coming from backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) endpoint or [`TradeContainer`](#tradecontainer) discussed above. ```typescript theme={null} type GetLiquidationPriceContext = { currentBlock: number; groups: BorrowingFeeGroup[]; pairs: BorrowingFeePair[]; liquidationParams: LiquidationParams | undefined; pairSpreadP: number | undefined; collateralPriceUsd: number | undefined; contractsVersion: ContractsVersion | undefined; } ``` `currentBlock` Its current block of underlying network. Use any valid block or backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) response: > tradingVariables.currentBlock `groups` and `pairs` To get `groups` and `pairs` we need to inspect `collaterals` backend [`/trading-variables`](/developer/integrators/backend#trading-variables) response. It is an array of objects corresponding to each supported collateral. Use `trade.collateralIndex` to select proper collateral object, then access its `borrowingFees:` > tradingVariables.collaterals\[trade.collateralIndex - 1].borrowingFees Remember that backend values should be normalised, see [PairParamsBorrowingFees](/developer/technical-reference/sdk/client-types#pairparamsborrowingfees) vs [PairParamsBorrowingFeesBackend](/developer/technical-reference/backend/backend-types#pairparamsborrowingfeesbackend) `liquidationParams` Available directly on [TradeContainer](#tradecontainer) `pairSpreadP` To get `pairSpreadP` inspect `pairs` key of backends `/trading-variables` response. It is an array of objects corresponding to each pair. Use `trade.pairIndex` to select proper pair: > tradingVariables.pairs\[trade.pairIndex].spreadP Should be normalised, see [Pair](/developer/technical-reference/sdk/client-types#pair) vs [PairBackend](/developer/technical-reference/backend/backend-types#pairbackend) `collateralPriceUsd` Its similar to getting `groups` and `pairs` but select `prices` key after accessing proper `collaterals` entry: > tradingVariables.collaterals\[trade.collateralIndex - 1].prices.collateralPriceUsd `contractsVersion` Available on [TradeContainer](#tradecontainer): > tradeInfo.contractsVersion At the end, the context passed to `getLiquidationPrice()` should look similar to this: ```typescript theme={null} { "currentBlock": 72867071, "groups": [...], "pairs": [...], "liquidationParams": { "maxLiqSpreadP": 0.0005, "startLiqThresholdP": 0.9, "endLiqThresholdP": 0.65, "startLeverage": 25, "endLeverage": 60 }, "pairSpreadP": 0, "collateralPriceUsd": 1.0000328, "contractsVersion": 1 } ``` ## Calculate liquidation price Wrapping all of the above, we should pass `trade`, `fee`, `initialAccFees` and `context` to SDK's `getLiquidationPrice()`. This should return single, float number. Per example above the return liquidation price is: `4.702126243307295` which matches Gains' UI: # History Endpoints Migration Source: https://docs.gains.trade/developer/integrators/guides/history-endpoints-migration Migration to the new trading history endpoints with cursor-based pagination (Dec 2025). NOTE: The old endpoints were fully removed on December 1, 2025. Use the new endpoints below. ## Backend Global API Migration Guide ### Overview The trading history endpoints have been migrated from `backend-[network]` service to the new `backend-global` endpoints with improved caching, pagination, and new statistics endpoints. **Base URL Change:** * **Old:** `https://backend-[network].gains.trade` * **New:** `https://backend-global.gains.trade` *** ### Endpoint Migration Map #### 24-Hour Trading History
Old EndpointNew EndpointChanges
GET /trading-history-24hGET /api/trading-history/24h?chainId=\{id}Path prefix added, chainId support
**Migration:** ```diff theme={null} - GET https://backend-arbitrum.gains.trade/trading-history-24h + GET https://backend-global.gains.trade/api/trading-history/24h?chainId=42161 ``` **Response Format:** Unchanged (returns array of trades) *** #### Personal Trading History **Main History Endpoint**
Old EndpointNew EndpointChanges
GET /personal-trading-history-table/:addressGET /api/personal-trading-history/:address?chainId=XPath renamed, cursor-based pagination, limits
**Migration:** ```diff theme={null} - GET https://backend.gains.trade/personal-trading-history-table/0x123... + GET https://backend-global.gains.trade/api/personal-trading-history/0x123...?chainId=42161&limit=50 ``` **Response Format:** ```json theme={null} { "data": [...], // Array of trades (same as before) "pagination": { "hasMore": true, // Whether more data available "nextCursor": 123456, // Cursor for next page (null if no more) "limit": 50 // Limit used for this request, no higher than 200 } } ``` **Pagination:** * **Old:** No offset * **New:** Cursor-based (`?cursor=123456`) **To fetch next page:** ```javascript theme={null} // Old (offset-based) const page1 = await fetch( "/personal-trading-history-table/0x123?offset=0&limit=50" ); const page2 = await fetch( "/personal-trading-history-table/0x123?offset=50&limit=50" ); // New (cursor-based) const page1 = await fetch("/api/personal-trading-history/0x123?limit=50"); const { data, pagination } = await page1.json(); if (pagination.hasMore) { const page2 = await fetch( `/api/personal-trading-history/0x123?cursor=${pagination.nextCursor}&limit=50` ); } ``` **Query Parameters:** * `chainId` (required): Chain ID * `cursor` (optional): Pagination cursor (omit for first page) * `limit` (optional): Max trades per request (default: 50, max: 1000) * `startDate` (optional): ISO 8601 date filter * `endDate` (optional): ISO 8601 date filter * `pair` (optional): Trading pair filter * `action` (optional): Action type filter *** **Statistics Endpoint (NEW)** **New endpoint for trader statistics:** ```http theme={null} GET /api/personal-trading-history/:address/stats?chainId={id} ``` **Response:** ```json theme={null} { "totalVolume": 123456.78, "totalTrades": 42, "winRate": 65.5, "thirtyDayVolume": 12345.67 } ``` **Use case:** Get all-time stats without fetching full trade history. *** **Batch Statistics Endpoint (NEW)** **New endpoint for batched trader statistics:** ```http theme={null} POST /api/personal-trading-history/stats Content-Type: application/json { "addresses": ["0x123...", "0x456..."], "chainId": 42161 } ``` **Response:** ```json theme={null} { "0x123...": { "totalVolume": 123456.78, "totalTrades": 42, "winRate": 65.5, "thirtyDayVolume": 12345.67 }, "0x456...": { "totalVolume": 67890.12, "totalTrades": 12, "winRate": 40.13, "thirtyDayVolume": 2345.67 } } ``` **Use case:** Get all-time stats without fetching full trade history. *** **Batch Trading History Endpoint (NEW)** **New endpoint for fetching multiple addresses:** ```http theme={null} POST /api/personal-trading-history/batch Content-Type: application/json { "addresses": ["0x123...", "0x456..."], "chainId": 42161, "limit": 50, "cursors": {"0x123...": 123, "0x456...": null} } ``` **Response:** ```json theme={null} { "0x123...": { "data": [...], "pagination": { "hasMore": true, "nextCursor": 123, "limit": 50 } }, "0x456...": { "data": [...], "pagination": { "hasMore": false, "nextCursor": null, "limit": 50 } } } ``` *** ### Deprecated Endpoints #### ⚠️ DO NOT USE | Endpoint | Status | Replacement | | ---------------------------------------------- | -------------- | -------------------------------------------- | | `GET /personal-trading-history/:address` | **DEPRECATED** | Use `/api/personal-trading-history/:address` | | `GET /personal-trading-history-table/:address` | **DEPRECATED** | Use `/api/personal-trading-history/:address` | | `GET /trading-history-24h` | **DEPRECATED** | Use `/api/trading-history/24h` | **Note:** The old `/personal-trading-history/:address` (without `-table`) returned a flat array and is now deprecated. Use the new cursor-based endpoint instead. *** ### Migration Checklist * [ ] Update base URL from `backend.gains.trade` → `backend-global.gains.trade` * [ ] Add `/api` prefix to all endpoints * [ ] Rename `/personal-trading-history-table` → `/personal-trading-history` * [ ] Add cursor pagination * [ ] Update response parsing to handle `{ data, pagination }` structure * [ ] Use `/stats` endpoint if only statistics are needed *** ### Support For questions or issues with migration, please contact the Gains Network development team. # Mark + Index Introduction Source: https://docs.gains.trade/developer/integrators/guides/mark-+-index-introduction How the v4 pricing API separates mark prices from index prices, and how to migrate from v3. **tl;dr**: v3 continues to work. No immediate breaking changes. However, since **Feb 16, 2025**, the v4 pricing API separates mark prices (TP/SL, limits, PnL) from index prices (liquidations) and is the recommended format. Action required only if you perform liquidation calculations on volatile pairs (non-core crypto with futures feeds). Without updating, those calculations will use the wrong price. ## Mark & Index Price Separation (v4 API) ### Overview Since **February 16, 2025**, Gains provides a v4 format that separates **mark prices** from **index prices** to support more advanced market structures and align with industry norms. ### What Changed
Price TypeDescriptionUsed For
Mark PricePrice used for trade executionTP/SL, Limit Orders, Stop Orders, PnL calculations
Index PriceSpot price, unaffected by derivatives skewLiquidations only
#### How Prices Differ by Market Type
TypeMark PriceIndex PriceExamples
Coremarket (spot + skew)spotBTC, ETH (funding fees)
VolatilefuturesspotNon-core crypto
RegularspotspotForex, stocks, commodities, non-core crypto w/o futures
* **Core**: Crypto with funding fees. Mark includes skew adjustment (for now clients have to calculate). * **Volatile**: Crypto with futures feeds available. Mark sourced from futures. * **Regular**: All other markets. Spot price used for both mark and index. > For **Core** and **Regular** pairs, mark and index prices will be identical from Gains endpoints. For **Volatile** pairs, they may differ significantly. **Core** will still need mark/market price calculated on the client. *** ### API Changes #### Connection To use the v4 API, connect to the v4 endpoint: ``` # v3 (legacy) wss://backend-pricing.eu.gains.trade/v3 # v4 (new) wss://backend-pricing.eu.gains.trade/v4 ``` #### Message Format **v3 (Legacy)** ```json theme={null} // Timestamp checkpoint [1707580800000] // Price update (flat array: [pairIndex, price, pairIndex, price, ...]) [0, 45000.50, 1, 2500.25, 2, 150.75] ``` **v4 (New)** ```json theme={null} { "m": [0, 45000.50, 1, 2500.25, 2, 150.75], "i": [0, 44998.00, 1, 2499.80, 2, 150.75], "t": 1707580800000 } ```
FieldTypeDescription
mnumber\[]Mark prices as flat array \[pairIndex, price, ...]
inumber\[]Index prices as flat array \[pairIndex, price, ...]
tnumberTimestamp (milliseconds)
#### `/charts` Endpoint The `/charts` snapshot endpoint now includes an additional `indexPrices` field alongside the existing OHLC data. `/charts` returns the current OHLC snapshot for each pair. It is not a historical OHLCV candles API. The response does not include volume, interval, `from`, or `to` parameters. **Before:** ```json theme={null} { "opens": [45000.50, 2500.25, ...], "highs": [45100.00, 2510.00, ...], "lows": [44900.00, 2490.00, ...], "closes": [45050.00, 2505.00, ...], "time": 1707580800 } ``` **After:** ```json theme={null} { "opens": [45000.50, 2500.25, ...], "highs": [45100.00, 2510.00, ...], "lows": [44900.00, 2490.00, ...], "closes": [45050.00, 2505.00, ...], "indexPrices": [44998.00, 2499.80, ...], "time": 1707580800 } ``` > `opens`, `highs`, `lows`, `closes` reflect **mark prices** (as before). `indexPrices` provides the latest **index price** per pair index. *** ### SDK Changes **`@gainsnetwork/sdk` v1.8.3** introduces: * `corePairIndices` — exported from `constants`, provides the list of core crypto pair indices (BTC, ETH, etc.) * `getMarketType(pairIndex)` — returns the market classification (`CORE`, `VOLATILE`, or `REGULAR`) for a given pair index These can be used to determine which price type applies to each pair: ```typescript theme={null} import { corePairIndices, getMarketType, MARKET_TYPE } from '@gainsnetwork/sdk'; const marketType = getMarketType(pairIndex); if (marketType === MARKET_TYPE.VOLATILE) { // Mark = futures, Index = spot — prices will differ } ``` *** ### Migration Guide **Example (TypeScript):** ```typescript theme={null} socket.onmessage = (msg) => { const data = JSON.parse(msg.data); // Parse mark prices (for TP/SL/limits) const markPrices = new Map(); for (let i = 0; i < data.m.length; i += 2) { markPrices.set(data.m[i], data.m[i + 1]); } // Parse index prices (for liquidations) const indexPrices = new Map(); for (let i = 0; i < data.i.length; i += 2) { indexPrices.set(data.i[i], data.i[i + 1]); } }; ``` *** ### Timeline | Date | Event | | ---------------- | ------------------------------------------------------------------------- | | **Feb 16, 2025** | v4 became the recommended format; index prices enabled for volatile pairs | | **TBD** | v3 deprecation (will be announced separately) | *** ### Impact of Not Updating If you continue using v3 or don't separate mark/index prices: * **Liquidation calculations will be incorrect** for volatile pairs, as they will use mark price instead of index price * **TP/SL/Limit orders** are unaffected (these use mark price, which v3 provides) * **Price display** is unaffected for most use cases > **Recommendation:** Evaluate your integration's use of price data. If you perform liquidation-related calculations, prioritize this update. The impact depends on your exposure to volatile pairs (non core crypto pairs with separate futures markets). *** ### Questions? Contact the Gains Network team on Discord if you have questions about the migration. # Support Endpoints Migration Source: https://docs.gains.trade/developer/integrators/guides/support-endpoints-migration Support endpoint migration Dec 2025 -> Jan 2026 #### Endpoint Migration Table | Category | Previous Endpoint `backend-{chain}.gains.trade` | New Endpoint `backend-global.gains.trade` | Notes | | ----------------- | ----------------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------- | | **Leaderboard** | `/leaderboard/:period` | `/api/leaderboard/:period?chainId={chainId}` | `chainId` is now a required query parameter. | | **Referrals** | `/referrals/links/:link/address` | `/api/referrals/links/:link/address` | Base path moved to `/api/referrals`. | | | `/referrals/addresses/:address/link` | `/api/referrals/addresses/:address/link` | | | **Holding Rates** | `/holding-rates/:collateralIndex/:pairIndex` | `/api/holding-rates/:collateralIndex/:pairIndex?chainId={chainId}` | `chainId` is now a required query parameter. | | **Stats** | `/stats` | `/api/stats?chainId={chainId}` | `chainId` is now a required query parameter. | | **APR** | `/apr` | `/api/apr?chainId={chainId}` | `chainId` is now a required query parameter. | | **Total Supply** | `/total-supply` | `/api/total-supply` | No `chainId` required (always returns total supply). | #### Timeline The old endpoints were retired on January 12, 2026 — make sure you are using the new ones below # v10 migration Source: https://docs.gains.trade/developer/integrators/guides/v10-migration Integrator migration guide for v10: funding fees, borrowing v2, partial closes, and more. > **Notice:** These documents are currently in progress. For any questions or clarifications, please contact the team. Current version: [https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.0.0-rc12](https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.0.0-rc12) ### v10 Changes - Overview * New funding fees (skew-based, only on v10 positions) * New borrowing fees v2 (alongside existing v1) * New P\&L withdrawal feature (withdraw profits without closing) * New counter trade type (fee discounts for improving skew) * New skew price impact * New market max skew limits * Fees no longer impact position size (exact position sizes) * Modified borrowing fees v1 (uses dynamic OI) * Modified partial update requirements (use effective leverage) * Modified liquidation, pnl, fees calculations * Pre and post v10 OI stored separately * Pre-v10 trades cannot partial add * New accounting: TradeFeesData and UiRealizedPnlData * New Trade fields: positionSizeToken and isCounterTrade ### Developer Notes - Overview * SDK has been updated to support v10 more effectively than previous versions * Backend transforms and converters are available (fetching is still separate) * Transform trading variables: `transformGlobalTradingVariables` * Transform global trades: `transformGlobalTrades` * All functions expect backend types * Additional feature support * Holding fees * Action fees * Price impact * PnL * Liquidations * Counter trade validation * Effective leverage * Market holding rates * Market leverage requirements * Market open interest * Market price * New context builders * More declarative development pattern * SDK functions mirror contract functions. But they don't fetch data, instead rely on all data provided * Provide large trading variables object and context builder will prepare struct for specific functions with all expected data ### Integration Guide NOTE: For `tradingVariables` and any trade struct (`trade`, `tradeInfo`, etc), consume from backends first: [Backend](/developer/integrators/backend#v10-update) #### 1. New Funding Fees Funding fees are skew-based fees that balance long/short exposure. **Trade-Specific Funding Fees:** ```typescript theme={null} import { buildFundingContext } from "@gainsnetwork/sdk/trade/fees/fundingFees/builder"; import { getTradeFundingFeesCollateral, getAvgFundingRatePerSecondP, } from "@gainsnetwork/sdk/trade/fees/fundingFees"; // Build funding context const fundingContext = buildFundingContext( tradingVariables, collateralIndex, pairIndex, currentTimestamp ); // Calculate funding fees for a trade const fundingFees = getTradeFundingFeesCollateral( trade, currentTimestamp, fundingContext ); // Get current funding rate const { avgFundingRatePerSecondP, currentFundingRatePerSecondP } = getAvgFundingRatePerSecondP(fundingContext, currentTimestamp); ``` **Display helpers:** ```typescript theme={null} import { convertRatePerSecondToAPR, formatHoldingFeeRate, } from "@gainsnetwork/sdk/markets/holdingFees"; import { fundingRateToAPR } from "@gainsnetwork/sdk/trade/fees/fundingFees/converter"; // Convert to annual percentage rate const apr = convertRatePerSecondToAPR(ratePerSecond); const fundingAPR = fundingRateToAPR(fundingRatePerSecond); // Format for display (e.g., "0.25%") const formatted = formatHoldingFeeRate(rate); ``` #### 2. New Borrowing Fees v2 Borrowing fees v2 work alongside funding fees with a simplified rate-based model. **Context Builder & Calculation:** ```typescript theme={null} import { buildBorrowingV2Context } from "@gainsnetworks/sdk/trade/fees/borrowingV2/builder"; import { getTradeBorrowingFeesCollateral } from "@gainsnetworks/sdk/trade/fees/borrowingV2"; // Build borrowing v2 context const borrowingV2Context = buildBorrowingV2Context( tradingVariables, collateralIndex, pairIndex, currentTimestamp ); // Calculate borrowing fees for a trade const borrowingFees = getTradeBorrowingFeesCollateral( trade, currentTimestamp, oraclePrice, borrowingV2Context ); ``` **Display helpers:** ```typescript theme={null} import { borrowingRateToAPR } from "@gainsnetworks/sdk/trade/fees/borrowingV2/converter"; // Convert borrowing rate to APR for display const borrowingAPR = borrowingRateToAPR(borrowingRatePerSecond); ``` #### 3. P\&L Withdrawal Feature Users can withdraw profits without closing their position. This maintains leverage while extracting gains. **Contract Interaction:** ```typescript theme={null} // Direct contract call (no SDK wrapper currently) const tx = await gnsMultiCollatDiamond.withdrawPositivePnl( tradeIndex, amountCollateral // in collateral precision (e.g., 6 decimals for USDC) ); ``` **Important behavior:** If `amountCollateral` exceeds available positive PnL, the contract will automatically withdraw only the maximum available amount (no revert). **To withdraw all available PnL:** ```typescript theme={null} const MAX_UINT120 = BigNumber.from(2).pow(120).sub(1); const tx = await gnsMultiCollatDiamond.withdrawPositivePnl( tradeIndex, MAX_UINT120 // Will be capped to available PnL ); ``` **Integration requirements:** * Calculate withdrawable P\&L: `tradeValue - initialCollateral` (when positive) * Show withdrawable amount in UI when position is in profit * Listen for `TradePositivePnlWithdrawn` event to update UI * Update position display after withdrawal: * `collateralAmount` increases * `positionSizeToken` remains unchanged * Track `pnlWithdrawnCollateral` for total withdrawn #### 4. Counter Trade Type Counter trades improve market balance and receive fee discounts. **Creating a Counter Trade:** ```typescript theme={null} // When opening a trade, set the isCounterTrade flag const tradeStruct = { // ... other trade parameters ... isCounterTrade: true, // Request counter trade discount }; // Open trade with counter trade flag const tx = await gnsMultiCollatDiamond.openTrade( tradeStruct, slippagePercent, referrer ); ``` **Note:** The contract will validate if the trade actually qualifies as a counter trade. If not, it will be rejected. If the trade size is larger than the max skew limit, it will be reduced in size but still opened. **Pre-validation:** ```typescript theme={null} import { validateCounterTrade } from "@gainsnetworks/sdk/trade/counterTrade/validateCounterTrade"; // Check if trade qualifies as counter trade before submitting const validation = validateCounterTrade( isLong, positionSizeCollateral, leverage, pairIndex, tradingVariables ); ``` **Detection (for existing trades):** ```typescript theme={null} // Check Trade struct field const isCounterTrade = trade.isCounterTrade; // boolean field in v10 trades ``` #### 5. Skew Price Impact Price impact based on market skew (imbalance between long/short OI). **NOTE:** The SDK offers wrapper utilities for open and close price impact which can be used to calculate all price impact data. More in SDK convenience functions. **Context Builder & Calculation:** ```typescript theme={null} import { buildSkewPriceImpactContext } from "@gainsnetwork/sdk/trade/priceImpact/skew/builder"; import { getTradeSkewPriceImpact } from "@gainsnetwork/sdk/trade/priceImpact/skew"; // Build context const skewContext = buildSkewPriceImpactContext( tradingVariables, collateralIndex, pairIndex ); // Calculate skew price impact const skewImpact = getTradeSkewPriceImpact( isLong, oraclePrice, positionSizeToken, skewContext ); ``` **Helper functions:** ```typescript theme={null} import { getNetSkewToken, getNetSkewCollateral, } from "@gainsnetwork/sdk/trade/priceImpact/skew"; // Get current market skew const skewToken = getNetSkewToken(pairOiData); const skewCollateral = getNetSkewCollateral(pairOiData, oraclePrice); ``` #### 6. Market Max Skew Limits Markets have maximum allowed skew to prevent excessive imbalance. **Check skew using computeOiValues:** ```typescript theme={null} import { computeOiValues } from "@gainsnetworks/sdk/markets/oi/converter"; // Compute current OI values including skew const { skewToken } = computeOiValues( pairOi, oraclePrice / collateralPriceUsd // Convert to token price in collateral ); // Get max skew from trading variables const maxSkewCollateral = tradingVariables.pairs[pairIndex]?.params?.maxSkewCollateral; // Convert skewToken to collateral for comparison const skewCollateral = Math.abs(skewToken) * (oraclePrice / collateralPriceUsd); const skewExceeded = skewCollateral > maxSkewCollateral; ``` **Note:** For counter trade validation and position sizing, use `validateCounterTrade` (see section 5). #### 7. Effective Leverage in Partial Updates Partial position updates now validate against effective leverage (accounts for unrealized P\&L). **Calculation:** ```typescript theme={null} import { getEffectiveLeverage } from "@gainsnetworks/sdk/trade/effectiveLeverage"; // Calculate effective leverage const effectiveLeverage = getEffectiveLeverage( trade.leverage, trade.collateralAmount, pnlCollateral ); ``` **Validation Requirements:** **For Position Increases (Partial Add):** * Effective leverage must not exceed `pairMaxLeverage` * Counter trades must not exceed `pairCounterTradeMaxLeverage` * Adjusted initial leverage must be between 0.1x and max uint24 (\~16,777x) * Pre-v10 trades cannot partial add **For Position Decreases (Partial Close):** * No effective leverage maximum check * Only validates adjusted initial leverage (≥ 0.1x) **For Leverage Increases:** * Same as position increases - effective leverage validated **For Leverage Decreases (Add Collateral):** * Same as position decreases - no effective leverage check ```typescript theme={null} // Example validation const maxLeverage = isCounterTrade ? tradingVariables.pairs[pairIndex].maxLeverageCounterTrade : tradingVariables.pairs[pairIndex].maxLeverage; const isValid = effectiveLeverage <= maxLeverage; const MIN_LEVERAGE = 0.1; // 0.1x minimum ``` #### 8. Modified Borrowing Fees v1 Borrowing fees v1 now use dynamic OI (position size adjusted by current price vs entry price). **Context Builder & Calculation:** ```typescript theme={null} import { buildBorrowingV1Context } from "@gainsnetworks/sdk/trade/fees/borrowing/builder"; import { getBorrowingFee } from "@gainsnetworks/sdk/trade/fees/borrowing"; // Build borrowing v1 context const borrowingV1Context = buildBorrowingV1Context( tradingVariables, collateralIndex, currentBlock ); // Calculate borrowing fee for a trade const borrowingFee = getBorrowingFee( positionSizeCollateral, pairIndex, isLong, initialAccFees, currentPairPrice, borrowingV1Context ); ``` **Utility functions:** ```typescript theme={null} import { borrowingFeeUtils } from "@gainsnetworks/sdk/trade/fees/borrowing"; // Get pending accumulated fees for a pair const pendingFees = borrowingFeeUtils.getPairPendingAccFees( pairs, pairGroups, groups, initialAccFees, pairIndex, currentBlock, feePerBlockCaps ); // Check if within max group OI const withinLimit = borrowingFeeUtils.withinMaxGroupOi( pairs, pairGroups, groups, positionSizeCollateral, pairIndex, isLong ); ``` #### 9. Modified Liquidation Calculations Liquidation now accounts for pending fees and realized P\&L. **Context Builder & Calculation:** ```typescript theme={null} import { buildLiquidationPriceContext } from "@gainsnetwork/sdk/trade/liquidation/builder"; import { getLiquidationPrice } from "@gainsnetwork/sdk/trade/liquidation"; // Build comprehensive context const liquidationContext = buildLiquidationPriceContext( tradingVariables, tradeContainer, { currentBlock, currentTimestamp, currentPairPrice, spreadP, traderFeeMultiplier, userPriceImpact, } ); // Calculate liquidation price const liqPrice = getLiquidationPrice(trade, liquidationContext); ``` **Additional functions:** ```typescript theme={null} import { getLiquidationPriceAfterPositionUpdate } from "@gainsnetwork/sdk/trade/liquidation"; // Calculate after position update const newLiqPrice = getLiquidationPriceAfterPositionUpdate( existingTrade, existingLiquidationContext, newCollateralAmount, newLeverage ); ``` #### 10. Modified PnL Calculations Comprehensive PnL includes all v10 components: funding fees, borrowing fees, and realized P\&L. **Context Builder & Calculation:** ```typescript theme={null} import { buildComprehensivePnlContext } from "@gainsnetwork/sdk/trade/pnl/builder"; import { getComprehensivePnl } from "@gainsnetwork/sdk/trade/pnl"; // Build context const pnlContext = buildComprehensivePnlContext( tradingVariables, tradeContainer, { currentBlock, currentTimestamp, traderFeeMultiplier, } ); // Calculate comprehensive PnL const pnl = getComprehensivePnl( trade, marketPrice, executionPrice, // price after spreads/impacts tradeInfo, pnlContext ); ``` **Helper functions:** ```typescript theme={null} import { getPnlPercent, getTradeValue } from "@gainsnetwork/sdk/trade/pnl"; // Calculate PnL percentage const pnlPercent = getPnlPercent(openPrice, currentPrice, isLong, leverage); // Get trade value (collateral + PnL) const tradeValue = getTradeValue(collateralAmount, pnlCollateral, 0); // pass 0 for raw trade value calculation ``` #### 11. New Trade Fields v10 trades have additional fields that must be parsed and stored. **New fields in Trade struct:** ```typescript theme={null} interface Trade { // ... existing fields ... positionSizeToken: bigint; // Position size in token units (1e18 precision) isCounterTrade: boolean; // Whether trade qualified for counter trade discount } ``` #### 12. V10 OI Tracking OI is tracked separately for pre-v10 and post-v10 trades. **OI Functions:** ```typescript theme={null} import { getPairTotalOisCollateral, getPairTotalOisDynamicCollateral, getPairV10OiTokenSkewCollateral, getPairV10OiDynamicSkewCollateral, } from "@gainsnetworks/sdk/markets/oi"; // Get total OI (pre-v10 only) const staticOI = getPairTotalOisCollateral(pairOi); // Get dynamic OI (pre-v10 + v10 adjusted by price) const dynamicOI = getPairTotalOisDynamicCollateral(pairOi, oraclePrice); // Get v10 skew in collateral const skewCollateral = getPairV10OiTokenSkewCollateral(pairOi, oraclePrice); // Get v10 dynamic skew const dynamicSkew = getPairV10OiDynamicSkewCollateral(pairOi, oraclePrice); ``` **Comprehensive OI Values:** ```typescript theme={null} import { computeOiValues } from "@gainsnetwork/sdk/markets/oi/converter"; // Get all computed OI values at once const oiValues = computeOiValues( pairOi, oraclePrice / collateralPriceUsd // Convert to token price in collateral ); ``` **Important notes:** * Funding fees only apply to v10 OI * Skew calculations use v10 OI only * Max OI checks use combined OI (pre-v10 + v10) * Counter trade validation uses v10 skew ### Market Price Concept Market price is a v10 feature that applies to markets with funding fees and skew price impact. It represents the oracle price adjusted for current market skew. **Calculate Market Price:** ```typescript theme={null} import { getCurrentMarketPrice } from "@gainsnetworks/sdk/markets/price/marketPrice"; import { buildMarketPriceContext } from "@gainsnetworks/sdk/markets/price/builder"; // Build context for market price calculation const marketPriceContext = buildMarketPriceContext(tradingVariables, pairIndex); // Calculate market price from oracle price const { marketPrice, skewImpactP } = getCurrentMarketPrice( pairIndex, oraclePrice, marketPriceContext ); ``` ### SDK Wrapper Functions The SDK provides high-level wrapper functions that combine multiple calculations for common operations. #### Price Impact **Opening a Trade:** ```typescript theme={null} import { getTradeOpeningPriceImpact } from "@gainsnetwork/sdk/trade/priceImpact/open"; import { buildTradeOpeningPriceImpactContext } from "@gainsnetwork/sdk/trade/priceImpact/open/builder"; // Build context with all required data const openContext = buildTradeOpeningPriceImpactContext( tradingVariables, collateralIndex, pairIndex, currentBlock ); // Calculate total price impact and execution price const openImpact = getTradeOpeningPriceImpact( oraclePrice, // Always pass oracle price isLong, positionSizeCollateral, leverage, openContext ); ``` **Understanding Price Impact Results:** ```typescript theme={null} // The function returns multiple price impact values: const { priceAfterImpact, // Final execution price totalPriceImpactP, // Total impact from oracle price totalPriceImpactPFromMarketPrice, // Total impact from market price baseSkewPriceImpactP, // Market skew before trade tradeSkewPriceImpactP, // Additional skew from this trade totalSkewPriceImpactP, // Total skew impact (base + trade) } = openImpact; // For UI display: // If showing market price: use totalPriceImpactPFromMarketPrice // If showing oracle price: use totalPriceImpactP ``` **Closing a Trade:** ```typescript theme={null} import { getTradeClosingPriceImpact } from "@gainsnetwork/sdk/trade/priceImpact/close"; import { buildTradeClosingPriceImpactContext } from "@gainsnetwork/sdk/trade/priceImpact/close/builder"; // Build context const closeContext = buildTradeClosingPriceImpactContext( tradingVariables, tradeContainer, currentBlock ); // Calculate price impact for closing const closeImpact = getTradeClosingPriceImpact( trade, oraclePrice, // Always pass oracle price closeContext ); // Similar to opening, returns multiple impact values const { priceAfterImpact, tradeValueCollateral, totalPriceImpactP, // From oracle price totalPriceImpactPFromMarketPrice, // From market price // ... other impact components } = closeImpact; ``` #### Action Fees (Trading Fees) **Calculate Total Trading Fees:** ```typescript theme={null} import { getTotalTradeFeesCollateral } from "@gainsnetwork/sdk/trade/fees/trading"; import { buildTradingFeesContext } from "@gainsnetwork/sdk/trade/fees/trading/builder"; // Build context const feesContext = buildTradingFeesContext( tradingVariables, collateralIndex, pairIndex ); // Calculate total fees const totalFees = getTotalTradeFeesCollateral( positionSizeCollateral, isCounterTrade, tradeTier, feesContext ); ``` **Get Detailed Fee Breakdown:** ```typescript theme={null} import { getTradeFeesCollateral } from "@gainsnetwork/sdk/trade/fees/trading"; // Get breakdown of all fee components const feeBreakdown = getTradeFeesCollateral( positionSizeCollateral, pairOpenFeeP, tradeTierMultiplier, referralFeeP, pairTriggerOrderFeeP, pairOtcFeeP, collateralPrecision ); // Returns: referralFees, govFees, triggerFees, gnsOtcFees, gTokenFees ``` **Calculate Pending Holding Fees:** ```typescript theme={null} import { getTradePendingHoldingFeesCollateral } from "@gainsnetwork/sdk/trade/fees/trading"; // Calculate all accumulated holding fees const holdingFees = getTradePendingHoldingFeesCollateral( trade, currentBlock, currentTimestamp, oraclePrice, collateralPrecision, holdingFeesContext // combines funding + borrowing contexts ); ``` ### Summary The SDK provides all necessary functions to integrate v10 features. Key patterns: 1. **Use Context Builders**: Most complex calculations require a context object built from trading variables 2. **Transform Backend Data**: Use `transformGlobalTradingVariables` and `transformGlobalTrades` before passing to SDK functions 3. **Handle Pre-v10 Trades**: Check `trade.contractsVersion` to determine if a trade uses v10 features 4. **Display Market Rates**: Use functions in "Current Market Rates" section for market-wide statistics # v10.2 migration Source: https://docs.gains.trade/developer/integrators/guides/v10.2-migration What changed for integrators in v10.2: the 30-band depth system for price impact. Version 10.2 introduces a new 30-band depth system for price impact calculations, replacing the previous single `onePercentDepthUsd` value. This provides more granular control over liquidity depth at different price levels. > **Notice:** These documents are currently in progress. For any questions or clarifications, please contact the team. **NOTE:** Live on all networks as of 10/21 Testnet: * Diamond contract: [https://louper.dev/diamond/0xB4F1B18b5679B42F2956dCBff3D7823A61F347C9?network=arbitrumSepolia#facets](https://louper.dev/diamond/0xB4F1B18b5679B42F2956dCBff3D7823A61F347C9?network=arbitrumSepolia#facets) * Backend endpoint: `https://backend-sepolia-release.gains.trade` SDK: * Version: [https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.5.0](https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.5.0) * Guide: [https://github.com/GainsNetwork-org/sdk/blob/feat/v10.2/docs/v10.2-migration.md](https://github.com/GainsNetwork-org/sdk/blob/feat/v10.2/docs/v10.2-migration.md) Contracts changelog: [v10.2 Update](/developer/technical-reference/contracts/changelogs/v10.2-update) # Live prices and OHLC snapshots Source: https://docs.gains.trade/developer/integrators/price-feed How to stream live prices and fetch current OHLC snapshots. This endpoint does not provide historical OHLCV candles. This page documents the **v3** feed format. Since **February 16, 2025**, the **v4** format separating mark prices from index prices is the recommended one — see the [Mark + Index introduction](/developer/integrators/guides/mark-+-index-introduction) for the v4 endpoints and migration details. ## DNS [https://backend-pricing.eu.gains.trade](https://backend-pricing.eu.gains.trade/charts) *NOTE: No auth is required for accessing REST GET endpoints and the WebSocket event stream. However, rate limiting is in place, so please fetch data only as necessary and rely on the event stream to keep price data updated.* ## Common Endpoint ### Current OHLC snapshots Fetch the current OHLC snapshot for each pair. `/charts` Format: * Comprehensive list of OHLCs * `pairId` is the index in the array. For example, BTC/USD `pairId = 0`, so `opens[0]`, `highs[0]`, `lows[0]`, and `closes[0]` construct the OHLC. * `{ time, opens: [], highs: [], lows: [], closes: [] }` `/charts` is a current OHLC snapshot endpoint. It is not a historical OHLCV candles API. It does not include volume, interval, `from`, or `to` parameters. For live price updates, use the event stream below. For recent executed trade data that you can use to derive gTrade volume, use the [trading history endpoints](/developer/integrators/guides/history-endpoints-migration). Those endpoints do not return price candles. For the v4 response shape with `indexPrices`, see the [Mark + Index introduction](/developer/integrators/guides/mark-+-index-introduction). ## Event Stream Subscribe for all price updates. The stream provides updates every 25ms. `wss://backend-pricing.eu.gains.trade` * Format: * Array of price updates for a given 25ms interval * All even indexes are pairIds, odd are pair prices * No particular order * `[,, , , , ...]` Every \~1000ms, the stream sends a single-item array as a ping message with an updated timestamp, for example: `[1724244390036]`. # Referrals Source: https://docs.gains.trade/developer/integrators/referrals Attribute traders to a referrer and let them claim USDC rewards The referral API lets you create referral codes, attach a trader to a referrer, read earnings, and claim rewards. Nothing here requires an API key, and nothing requires your users to send a transaction except the claim itself. Creating a code and applying a code are **EIP-712 signatures**. The signature is the only authority. Per-endpoint schemas live under [API Reference → Referrals](/developer/api-reference/endpoint/referral-config). This page covers what the schemas cannot tell you: how to sign, what breaks, and what to ask us for. This is the **self-serve referral API** served by `backend-global`. It is not the on-chain program documented in [GNSReferrals](/developer/technical-reference/contracts/core/facets/gnsreferrals) and [ReferralsUtils](/developer/technical-reference/contracts/libraries/referralsutils), and it is not the older KOL-slug system behind `/api/referrals/links/…`. Three different things share the word "referral". Do not mix them. ## Check availability first The API is enabled per deployment. Probe it at startup: ```bash theme={null} curl https://backend-global.gains.trade/api/referrals/config ``` ```json theme={null} { "result": { "chainId": 42161, "distributor": "0x…", "l1RateBps": 1000, "l2RateBps": 500 } } ``` Anything other than `200` means referrals are unavailable on that host. Disable the feature in your UI rather than falling back to stored values. [`GET /api/referrals/config`](/developer/api-reference/endpoint/referral-config) is the **only** valid readiness check. The read endpoints return `200` with zeroes whether or not the system is running, so they tell you nothing. `chainId` and `distributor` come from this endpoint at runtime by design. A distributor redeploy is meant to be a configuration change on our side, not a client rebuild on yours. Any address you pin elsewhere will eventually be wrong. ## Three rules that break integrations Once a wallet has traded on any chain covered by the program, [`POST /api/referrals/bind`](/developer/api-reference/endpoint/referral-bind-code) returns `409 AlreadyTraded` and no referrer can ever be attached. This is permanent. Bind at onboarding, before the wallet reaches the exchange. Binding shortly after the first trade earns nothing. There is no endpoint that answers "is this wallet still bindable". Derive it from trading history, and **ask us for the exact list of chain ids in the attribution window** so your check covers the same set as ours. Cover fewer chains than we do and you will show an eligible state that the API then refuses. Treat any chain you cannot resolve as **not eligible** and disable the bind UI. Failing open here produces a link that is accepted and then earns nothing. Read both from `/config` on every session. A stale `chainId` or `distributor` silently changes the EIP-712 domain. The recovered signer becomes a different address, so the failure surfaces as `401 unauthorized-signer` rather than as anything that mentions the domain. If you see that error and your subject really is the signer, re-fetch `/config` before looking anywhere else. Despite the names: * `claimableMicroUsdc` is **lifetime gross earnings**. It ignores everything already paid out. * `unpaidMicroUsdc` is lifetime minus already claimed. It still includes earnings that no published batch carries yet, which the contract will refuse to pay. Gate the claim on a `200` from [`/proof/{address}`](/developer/api-reference/endpoint/referral-proof) **and** a positive delta. See [Claiming](#claiming). ## Signing Both write operations share one EIP-712 domain. ```js theme={null} const domain = { name: "GainsReferral", version: "1", chainId: config.chainId, // from /api/referrals/config verifyingContract: config.distributor, }; ``` There is no `salt`, and you must not add `EIP712Domain` to the `types` object. ### Types Field order is part of the hash. Do not reorder. ```js theme={null} const RegisterCode = { RegisterCode: [ { name: "owner", type: "address" }, { name: "code", type: "string" }, { name: "nonce", type: "uint256" }, { name: "validUntil", type: "uint64" }, ], }; const BindCode = { BindCode: [ { name: "referee", type: "address" }, { name: "code", type: "string" }, { name: "nonce", type: "uint256" }, { name: "validUntil", type: "uint64" }, ], }; ``` The structs differ only in the first field name and are not interchangeable. ### Message fields | Field | Type | How to build it | | ------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------- | | `owner` / `referee` | `address` | The signing wallet. Anything else returns `401`. | | `code` | `string` | Must match `/^[a-z0-9_]{1,31}$/`. **Normalize with `trim().toLowerCase()` before signing** — we reject, we do not normalize. | | `nonce` | `uint256` | `Date.now()`, in **milliseconds**. Must be strictly greater than your last accepted nonce. | | `validUntil` | `uint64` | Unix **seconds**. Use `now + 600`. | `nonce` is milliseconds and `validUntil` is seconds. Swapping them gives `400 expiry-too-far` or `409 BadNonce`. The nonce high-water mark is **per signer and shared across both message kinds**. A bind sent after a register must carry a strictly larger nonce, and you must never have two writes in flight for the same wallet. `validUntil` is checked against our clock: it must be in the future and at most 900 seconds ahead. Sign immediately before submitting rather than pre-signing and queueing. Smart-contract wallets are not supported. Signatures are verified by ECDSA recovery only, with no EIP-1271 path, so the recovered address must be an EOA. ### Sending it Both transports are equivalent; the signature is the only thing that matters. ```ts POST theme={null} const res = await fetch(`${base}/api/referrals/code`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: { kind: "register_code", ...message }, signature }), }); ``` ```ts GET theme={null} // base64url, unpadded const encoded = btoa(JSON.stringify({ kind: "register_code", ...message })) .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); const res = await fetch( `${base}/api/referrals/code?message=${encodeURIComponent(encoded)}&signature=${encodeURIComponent(signature)}`, { method: "GET" } ); ``` Use `bind_code` and `/api/referrals/bind` to bind. `kind` must be present and must match the path, but it is **transport metadata only** and is not part of the signed struct. The GET transport exists so the request stays a CORS simple request and survives edge rules that block POST. If you use it, send **no custom headers**, or you reintroduce the preflight you were avoiding. Only `201` is success. ### Worked example ```ts theme={null} import { createWalletClient, custom } from "viem"; const cfg = await fetch(`${base}/api/referrals/config`) .then((r) => r.json()) .then((j) => j.result); const code = raw.trim().toLowerCase(); if (!/^[a-z0-9_]{1,31}$/.test(code)) throw new Error("invalid code"); const message = { referee: account, code, nonce: Date.now(), validUntil: Math.floor(Date.now() / 1000) + 600, }; const signature = await wallet.signTypedData({ account, domain: { name: "GainsReferral", version: "1", chainId: cfg.chainId, verifyingContract: cfg.distributor, }, types: { BindCode: [ { name: "referee", type: "address" }, { name: "code", type: "string" }, { name: "nonce", type: "uint256" }, { name: "validUntil", type: "uint64" }, ], }, primaryType: "BindCode", message, }); const res = await fetch(`${base}/api/referrals/bind`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: { kind: "bind_code", ...message }, signature }), }); ``` ## Write errors | Status | Error | Meaning | What to do | | ------ | ------------------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------- | | `400` | *prose* | Malformed field. These strings are not stable — do not switch on them. | Fix the client. | | `400` | `expired` | `validUntil` is in the past. | Re-sign. Check your clock. | | `400` | `expiry-too-far` | More than 900 seconds ahead. | Use `now + 600`. | | `400` | `malformed` | Signature could not be recovered. | Check encoding, domain and types. | | `401` | `unauthorized-signer` | Signer is not the subject. **Usually a stale `chainId` or `distributor`.** | Re-fetch `/config`. | | `403` | `origin not allowed` | Your `Origin` is not allowlisted. | Not retryable. Ask us to add it. | | `409` | `AlreadyTraded` | The wallet has traded. Bind only. | Terminal. | | `409` | `AlreadyBound` | Already has a referrer. | Terminal. | | `409` | `CodeUnknown` | Code is not registered. | Register first, or check spelling. | | `409` | `CodeTaken`, `OwnerHasCode`, `CodeReserved` | Register conflicts. | Choose another code. | | `409` | `SelfReferral`, `Cycle` | Not permitted. | Terminal. | | `409` | `BadNonce` | Nonce not strictly greater. | See below. | | `429` | `too many requests…` | 30 writes per minute. | Back off; read the `RateLimit-*` headers. | | `503` | `signed referral writes are disabled` | Not enabled on this host. | Disable the feature. | | `503` | `TradeHistoryUnavailable` | We could not check trade history, so we refused. | Retryable. | | `500` | `failed to apply signed write` | State is indeterminate. | Re-read before retrying. | **A `409` does not mean the write failed.** If a request times out and you retry, `BadNonce` means the original write already landed. So do `AlreadyBound` and `OwnerHasCode` when you retry with a fresh nonce. After any non-`201`, re-read [`/binding/{address}`](/developer/api-reference/endpoint/referral-binding) or [`/address/{address}/code`](/developer/api-reference/endpoint/referral-owner-code) before deciding what happened. ## Reading Every response is wrapped in `{"result": …}`; errors are `{"error": "…"}`. Reads are not rate limited and CORS is open, but there is no server-side cache, so poll conservatively. Accruals move at most every 30 seconds, and the claimable amount changes roughly once a day. ### Units `lifetimeUsd` and `claimableMicroUsdc` are the **same quantity in different units**. Do not add them, and do not divide `lifetimeUsd` by 1e6. * **Micro-USDC integers as strings** — divide by 1e6, parse with `BigInt`: `claimableMicroUsdc`, `settledMicroUsdc`, `unpaidMicroUsdc`, `cumulativeMicroUsdc`, `amountMicroUsdc`. * **Decimal USD strings**, already human-scaled: `lifetimeUsd`, `l1Usd`, `l2Usd`, `cashbackUsd`, `accruedUsd`, `earnedUsd`, `volume30dUsd`. * **Basis points** as integers, 10000 = 100%: `l1RateBps`, `l2RateBps`, `cashbackBps`. * **Unix seconds**: `boundAt`, nullable. **`YYYY-MM-DD` UTC**: `day`. ### What to display | Label | Value | | --------------- | -------------------------------------------------------------------- | | Ready to claim | `proof.cumulativeMicroUsdc − rewards.settledMicroUsdc`, floored at 0 | | Lifetime earned | `rewards.claimableMicroUsdc` ÷ 1e6 | | Claimed | `rewards.settledMicroUsdc` ÷ 1e6 | | Pending | `rewards.unpaidMicroUsdc` − ready to claim | | Rate | `effectiveRate.l1RateBps / 100` % | `effectiveRate` reports the standard programme rate. A negotiated partner rate is applied to actual earnings but is not reflected in that field today, so do not present it as a contractual rate. ## Claiming [`GET /api/referrals/proof/{address}`](/developer/api-reference/endpoint/referral-proof) returns `day`, `cumulativeMicroUsdc` and `proof`. A `404 nothing claimable` is a **normal state**, not an error. The contract pays `cumulativeAmount − claimed[account]`. Read it exactly with the `claimableAmount(account, cumulativeAmount)` view, or approximate it as `cumulativeMicroUsdc − settledMicroUsdc`. Prefer the on-chain view for the amount next to the button: `settledMicroUsdc` is only as fresh as our indexer, so it can over-report just after a claim. Call `claim` on `config.distributor`, on `config.chainId`. Pass `cumulativeMicroUsdc` unchanged — the contract computes the delta itself. ```json theme={null} { "type": "function", "name": "claim", "stateMutability": "nonpayable", "inputs": [ { "name": "account", "type": "address" }, { "name": "cumulativeAmount", "type": "uint256" }, { "name": "proof", "type": "bytes32[]" } ], "outputs": [] } ``` Payment is native USDC on the hub chain, 6 decimals. The call is permissionless: anyone can submit it and funds always go to `account`, so a relayer can pay the gas. Re-fetch the proof immediately before sending. Proofs go stale when a new batch is published, and a stale one reverts `InvalidProof`. Handle `NothingToClaim`, `InvalidProof` and `IsPaused`. ## Referral links To match the gTrade app: | | | | --------------- | ---------------------------- | | Query parameter | `ref` | | Cookie name | `referral_v2` | | Cookie value | the code, lowercased | | Lifetime | 604800 seconds (7 days) | | Precedence | `?ref=` wins over the cookie | Validate against `/^[a-z0-9_]{1,31}$/` before storing. The `by` and `referredBy` parameters and the `referral` cookie belong to the older KOL-link system and are unrelated to this API. ## Before you go live Ask us for the following. The first three are blocking. 1. **Your exact origins added to the write allowlist.** Matching is exact string comparison on the `Origin` header: no wildcards, no subdomain matching. Without it, every write returns `403`. Tell us whether you call from a browser or server-side, because a request with no `Origin` header is also rejected. 2. **Confirmation that signed writes are enabled** on the environment you target. 3. **Confirmation that accrual indexing is enabled.** If it is off, writes succeed and reads return zeroes indefinitely, with no HTTP signal to detect it. 4. **The API base host** for each environment. 5. **The chain ids in the attribution window**, so your eligibility check matches ours. 6. **Reserved code namespaces**, if you want branded codes protected from squatting. 7. **Rate-limit headroom**, if your traffic egresses from a small set of IPs. The limit is 30 writes per minute per IP, shared across both write endpoints and both transports. ## Integration checklist 1. Probe `/config`. Non-`200` disables the feature. 2. Capture `?ref=`, validate it, store it in `referral_v2` for 7 days. 3. Resolve the code with `/code/{code}/address`. A `null` owner means do not attempt a bind. 4. Check eligibility across every attribution chain. Treat anything unresolved as not eligible. 5. Check `/binding/{address}`. Non-null means already bound. 6. Sign with values from `/config`, one write in flight per wallet. 7. On `201` you are done. On `409` or `500`, re-read state before concluding anything. 8. Offer the claim only on a `200` proof with a positive delta, with the wallet on `config.chainId`. # Trading Contracts Source: https://docs.gains.trade/developer/integrators/trading-contracts How to interact with Gains trading contracts. To interact with trading contracts, call the relevant methods on the `GNSMultiCollatDiamond` contract. Each facet method can be accessed through this central contract. Network-specific `GNSMultiCollatDiamond` addresses are listed on the [Active Contracts page](/what-is-gains-network/contract-addresses#active-contracts). ## Addresses For the latest addresses, see [Contract Addresses](/what-is-gains-network/contract-addresses#active-contracts). If you are using testnet, the [Arbitrum Sepolia address](https://louper.dev/diamond/0xd659a15812064C79E189fd950A189b15c75d3186?network=arbitrumSepolia) for `GNSMultiCollatDiamond` is `0xd659a15812064C79E189fd950A189b15c75d3186`. ## Interactions Below is a list of available actions, consisting of market & limit orders, as well as updates. Where possible, NatSpec documentation is linked to. For full reference, see the [ITradingInteractionsUtils](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils) natspec. * Place a trade\* * Place a limit order * Update a trade * Update a limit order * Cancel a limit order * Close a trade\* * Update leverage (decrease/increase) * Increase position size * Decrease position size \**Requires order fulfillment. Integrators make requests, and oracles fulfill them.* ### Place a Trade Place a trade using the following functions. Use tradeType = 0. [`openTrade`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#opentrade) [`openTradeNative`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#opentradenative) If an order hasn't been fulfilled in 60 seconds, collateral can be claimed back using the timeout function: [`cancelOrderAfterTimeout`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#cancelorderaftertimeout) ### Place a Limit Order Same as market order, but provided tradeType of 1 or 2. \ **Limit**: To be used when you want to go long at a lower price than present, or to go short if the price reaches a higher price than present. Executes at exact price set if price reaches threshold + spread. **Stop:** To be used when you want to go long if the price reaches a higher price than present, or to go short if the price reaches a lower price than present. You might want to use this to long a breakout, or short a breakdown. The execution price is the current market price + spread. ### Update Active Trade Supports updating take profit (TP) and stop loss (SL). [`updateSl`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#updatesl) [`updateTp`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#updatetp) ### Update Pending Limit Order If a limit order hasn't been fulfilled yet, it can be updated [`updateOpenOrder`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#updateopenorder) ### Cancel Pending Limit Order If a limit order hasn't been fulfilled yet, it can be canceled [`cancelOpenOrder`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#cancelopenorder) ### Close a Trade Market close a trade [`closeTradeMarket`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#closetrademarket) If the trade hasn't been closed in 60 seconds, a timeout may be initiated, allowing for another close attempt: [`cancelOrderAfterTimeout`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#cancelorderaftertimeout) ### Update Leverage Update leverage for a trade [`updateLeverage`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#updateleverage) ### Update Position Size Decrease position size (by decreasing collateral amount or leverage) [`decreasePositionSize`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#decreasepositionsize) Increase position size (by increasing collateral amount or leverage or both) [`increasePositionSize`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#increasepositionsize) ## Events Events are emitted to allow off-chain services to stay updated. You can subscribe to these directly, or review the [Backend](/developer/integrators/backend) page for instructions on receiving events from a WebSocket stream. We recommend using the backend. **Core Events** For opening or closing a trade: `MarketOrderInitiated` -> `MarketExecuted` For placing a limit order: `OpenOrderPlaced` For updating a trade: `TradeSlUpdated` or `TradeTpUpdated` For fulfilling a limit order (SL, TP, Open limit): `LimitExecuted` For updating leverage: `LeverageUpdateInitiated`-> `LeverageUpdateExecuted` For updating position size (increase): `PositionSizeUpdateInitiated`-> `PositionSizeIncreaseExecuted` For updating position size (decrease): `PositionSizeUpdateInitiated`-> `PositionSizeDeccreaseExecuted` **All Lifecycle Events** [`MarketOrderInitiated`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#marketorderinitiated) [`TriggerOrderInitiated`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#triggerorderinitiated) [`OpenLimitUpdated`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#openlimitupdated) [`OpenLimitCanceled`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#openlimitcanceled) [`ChainlinkCallbackTimeout`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#chainlinkcallbacktimeout) [`OpenOrderPlaced`](/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils#openorderplaced) [`TradeSlUpdated`](/developer/technical-reference/contracts/interfaces/libraries/itradingstorageutils#tradeslupdated) [`TradeTpUpdated`](/developer/technical-reference/contracts/interfaces/libraries/itradingstorageutils#tradetpupdated) [`MarketExecuted`](/developer/technical-reference/contracts/interfaces/libraries/itradingcallbacksutils#marketexecuted) [`LimitExecuted`](/developer/technical-reference/contracts/interfaces/libraries/itradingcallbacksutils#limitexecuted) [`LeverageUpdateInitiated`](/developer/technical-reference/contracts/interfaces/libraries/iupdateleverageutils#leverageupdateinitiated) [`PositionSizeUpdateInitiated`](/developer/technical-reference/contracts/interfaces/libraries/iupdatepositionsizeutils#positionsizeupdateinitiated) [`LeverageUpdateExecuted`](/developer/technical-reference/contracts/interfaces/libraries/iupdateleverageutils#leverageupdateexecuted) [`PositionSizeDecreaseExecuted`](/developer/technical-reference/contracts/interfaces/libraries/iupdatepositionsizeutils#positionsizedecreaseexecuted) [`PositionSizeIncreaseExecuted`](/developer/technical-reference/contracts/interfaces/libraries/iupdatepositionsizeutils#positionsizeincreaseexecuted) # Backend Types Source: https://docs.gains.trade/developer/technical-reference/backend/backend-types Gains' backend return types ```typescript theme={null} type TradeContainerBackend { trade: TradeBackend; tradeInfo: TradeInfoBackend; initialAccFees: TradeInitialAccFeesBackend; liquidationParams: LiquidationParamsBackend; } ``` ```typescript theme={null} type TradeBackend { user: string; index: string; pairIndex: string; leverage: string; // 1e3 long: boolean; isOpen: boolean; collateralIndex: string; tradeType: string; collateralAmount: string; // collat decimals openPrice: string; // 1e10 tp: string; // 1e10 sl: string; // 1e10 } ``` ```typescript theme={null} type TradeInfoBackend { createdBlock: string; tpLastUpdatedBlock: string; slLastUpdatedBlock: string; maxSlippageP: string; // 1e3 lastOiUpdateTs: number; collateralPriceUsd: string; // 1e8 contractsVersion: string; lastPosIncreaseBlock: string; } ``` ```typescript theme={null} type TradeInitialAccFeesBackend { accPairFee: string; // 1e10 accGroupFee: string; // 1e10 block: string; } ``` ```typescript theme={null} type LiquidationParamsBackend { maxLiqSpreadP: string; // 1e12 startLiqThresholdP: string; // 1e12 endLiqThresholdP: string; // 1e12 startLeverage: string; // 1e3 endLeverage: string; // 1e3 } ``` ```typescript theme={null} type TradingGroupBackend { name: string; minLeverage: string; maxLeverage: string; } ``` ```typescript theme={null} type FeeBackend { totalPositionSizeFeeP: string; // 1e12 totalLiqCollateralFeeP: string; // 1e12 oraclePositionSizeFeeP: string; // 1e12 minPositionSizeUsd: string; // 1e3, fee floor position size } ``` ```typescript theme={null} type PairDepthBackend { onePercentDepthAboveUsd: string; onePercentDepthBelowUsd: string; } ``` ```typescript theme={null} type PairParamsBorrowingFeesBackend { pairs: PairBorrowingFeesBackendPair[]; groups: PairBorrowingFeesBackendGroup[]; } ``` ```typescript theme={null} type PairBackend { from: string; to: string; spreadP: string; // 1e12 groupIndex: string; feeIndex: string; } ``` ```typescript theme={null} type GlobalTradingVariablesBackend { lastRefreshed: string; refreshId: number; tradingState: number; maxGainP: number; marketOrdersTimeoutBlocks: number; pairs: PairBackend[]; groups: TradingGroupBackend[]; fees: FeeBackend[]; pairInfos: PairInfosBackend; collaterals: CollateralBackend[]; sssTokenBalance: string; sssLegacyTokenBalance: string; sssRewardTokens: string[]; vaultClosingFeeP: string; maxNegativePnlOnOpenP: number; blockConfirmations: number; oiWindowsSettings: OiWindowsSettingsBackend; oiWindows: OiWindowsBackend[]; feeTiers: FeeTiersBackend; allTrades: TradeContainerBackend[]; currentBlock: number; currentL1Block: number; isForexOpen: boolean; isStocksOpen: boolean; isIndicesOpen: boolean; isCommoditiesOpen: boolean; liquidationParams: { groups: LiquidationParamsBackend[]; pairs: LiquidationParamsBackend[]; }; } ``` ```typescript theme={null} type PairInfosBackend { maxLeverages: number[]; pairDepths: PairDepthBackend[]; pairFactors: PairFactorBackend[]; } ``` ```typescript theme={null} type TraderInfoBackend = { lastDayUpdated: number; trailingPoints: string; } ``` ```typescript theme={null} type UserTradingVariablesBackend { pendingMarketOrdersIds: number[]; pendingMarketOrders: number[]; feeTiers: TraderFeeTiersBackend; collaterals: Array<{ balance: string; allowance: string; decimals: number }>; } ``` ```typescript theme={null} type PairOiBackend = { oiLongUsd: string; // 1e18 oiShortUsd: string; // 1e18 } ``` ```typescript theme={null} type OiWindowsBackend = { [key: string]: PairOiBackend; } ``` ```typescript theme={null} type OiWindowsSettingsBackend = { startTs: number; windowsDuration: number; windowsCount: number; } ``` ```typescript theme={null} type CollateralConfigBackend = { precision: string; precisionDelta: string; decimals: number; } ``` ```typescript theme={null} type FeeTiersBackend = { tiers: Array<{ feeMultiplier: string; pointsThreshold: string }>; // 1e3, 1 multipliers: string[]; // 1e3 currentDay: number; } ``` ```typescript theme={null} type TraderFeeTiersBackend = { traderInfo: TraderInfoBackend; lastDayUpdatedPoints: string; inboundPoints: string; // 1e18 outboundPoints: string; // 1e18 expiredPoints: string[]; // 1e18 } ``` ```typescript theme={null} type PairFactorBackend = { cumulativeFactor: string; // 1e10 protectionCloseFactor: string; // 1e10 protectionCloseFactorBlocks: string; } ``` ```typescript theme={null} type OpenInterestBackend { long: string; // 1e10 short: string; // 1e10 max: string; // 1e10 } ``` ```typescript theme={null} type CollateralBackend { collateralIndex: number; collateral: string; symbol: string; isActive: boolean; prices: TokenPrices; collateralConfig: CollateralConfigBackend; gToken: { address: string; currentBalanceCollateral: string; maxBalanceCollateral: string; marketCap: string; }; borrowingFees: PairParamsBorrowingFeesBackend; } ``` ```typescript theme={null} type CollateralConfigBackend = { precision: string; precisionDelta: string; decimals: number; } ``` ```typescript theme={null} type PairBorrowingFeesBackendPair { oi: OpenInterestBackend; feePerBlock: string; // 1e10 accFeeLong: string; // 1e10 accFeeShort: string; // 1e10 accLastUpdatedBlock: string; feeExponent: string; groups: PairBorrowingFeesBackendPairGroup[]; } ``` ```typescript theme={null} type PairBorrowingFeesBackendPairGroup { groupIndex: string; block: string; initialAccFeeLong: string; // 1e10 initialAccFeeShort: string; // 1e10 prevGroupAccFeeLong: string; // 1e10 prevGroupAccFeeShort: string; // 1e10 pairAccFeeLong: string; // 1e10 pairAccFeeShort: string; // 1e10 } ``` ```typescript theme={null} type PairBorrowingFeesBackendGroup { oi: OpenInterestBackend; feePerBlock: string; // 1e10 accFeeLong: string; // 1e10 accFeeShort: string; // 1e10 accLastUpdatedBlock: string; feeExponent: string; } ``` # v10 Update Source: https://docs.gains.trade/developer/technical-reference/contracts/changelogs/v10-update Announcement: [Gains v10 is live — built to scale](https://medium.com/gains-network/gtrade-v10-is-live-built-to-scale-22dbd635de20) ### Changelog * TradingCallbacksUtils and TradingInteractionsUtils are now external * New external libraries: FundingFeesUtils (new holding fees logic), TradeManagementCallbacks (pnl withdrawal, negative pnl/holding fees realization), TradingStorageGetters (previously ArrayGetters) * New GOV\_EMERGENCY\_TIMELOCK role (setRoles, diamondCut) => 10-hour emergency timelock so we can do emergency fixes * Post-v10 OI stored separately from pre-v10 (collateral + token OIs) * Old borrowing fees and new borrowing fees are charged on all OI (pre-v10 and post-v10) * New funding fees are only charged on post-v10 OI * Counter trade skew calculation uses post-v10 OI only * Skew price impact calculation uses post-v10 OI only * Max skew check uses post-v10 OI only * Pair max OI check uses all OI (pre-v10 and post-v10) * Pair OI updates now done from \_updateOi instead of handleTradeBorrowingCallback (calls pre-v10 setter for pre-v10 trades and post-v10 setter for post-v10 trades), group OI still updated from handleTradeBorrowingCallback * New funding fees facet: funding fees and new borrowing fees * All new funding/borrowing fees data and settings are stored per pair and collateral * Everything is backwards compatible: a pair can have old borrowing fees, new funding fees, and new borrowing fees (any combination) * Funding rate per second's velocity per year = skew coefficient per year \* net exposure in tokens, absolute value capped at max velocity setting, only > 0 when net exposure usd > theta threshold usd * Funding rate = last rate + seconds elapsed \* velocity per year / seconds in a year, absolute value capped at max rate setting (hard cap at 10,000% APR) * Acc funding fees delta = avg funding rate per second % since last update \* seconds elapsed \* current pair price (incremented at every trade, whenever OI or a funding parameter changes), trade funding fee = (current acc funding fee - initial acc funding fee) \* position size collateral / entry price / 100 = sum(avg funding rate per second % \* seconds elapsed \* current pair price) since trade opened \* position size collateral / entry price / 100 = sum(funding rate % \* current pair price \* position size token / 100) since trade opened = sum(funding rate % \* position size collateral dynamic / 100) since trade opened * Can enable/disable funding fees and enable/disable APR multiplier logic on each pair/collateral (resumes from last rate when we re-enable) * APR multipliers use the OI in token amounts (not collateral amounts) to calculate the ratio of longs/shorts (capped at 100x to prevent overflows), otherwise it wouldn't be balanced since the total funding fee on one side is acc fee delta / 100 \* total OI token * New borrowing rate (same on each side) can be defined on each pair/collateral (hard cap at 1,000% APR) * Funding fees and borrowing fees are charged on the dynamic position size in collateral tokens (scaled by current price / entry price) to mimic CEXes behavior * New max OI skew in collateral tokens per pair/collateral (uses net skew in tokens \* current pair price => dynamic OI collateral skew) * Pair max OI check now uses dynamic OIs in collateral tokens (= pre-v10 OI collateral + post-v10 OI token \* current pair price) * Old borrowing fees refactor: * Old borrowing fees calculations now require current pair price (rate is calculated using dynamic OIs collateral) * Still charged on initial position size collateral for now, would require factoring acc fee * Borrowing pair params setter was refactored to use callback pattern * Borrowing groups however still use initial OIs for borrowing rate calculation and max OI check * New param updates callback mechanism: * Specific job id (market) * Uses address(1) to store pending order in order to have a global id * Pending param updates are stored in funding fees facet * New parameter value has to fit into uint224 (pending param update = collateral index, pair index, update type, and new value packed into 1 slot) * Before any trading action that impacts size of an open trade (partial add/close, full close), pending holding fees are realized (reset to 0, stored as realized pnl, if positive sent to vault without burn) * Realized pnl of each trade is split between realized pnl (only impacts trade value) and realized trading fees (impacts both trade value and available collateral in diamond) * 3 new other vars impact availble collateral in diamond: * manuallyRealizedNegativePnlCollateral: equal to the negative pnl we sent to the vault to balance potential closed pnl imbalances (eg. huge negative open pnl but all trades closing have positive pnl) * alreadyTransferredNegativePnlCollateral: equal to the total partial close negative pnl sent to the vault (for leverage delta > 0) * virtualAvailableCollateralInDiamond: when withdrawing collateral with positive pnl it's possible there isn't enough collateral in diamond, however available collateral in diamond must be >= 0 after withdrawing collateral (we prioritize capping manuallyRealizedNegativePnlCollateral at new collateral amount and if not enough we compensate through this variable); otherwise if negative then when user deposits collateral it doesn't increase available in diamond and can deposit/withdraw in loop to drain the vault * The function to realize trading fees on an open trade also checks if the trade can be liquidated after charging the fee, and if so liquidates it in order to avoid someone spamming trade actions potentially before we have time to liquidate him with trigger bots resulting in more fees than his trade can afford * Partial close refactor: * The value sent to the trader is now the partial collateral + net pnl - closing fee, exactly equivalent to the full close formula (later we could refactor to remove full close code and only use partial close code and just close trade when partial close size = trade size) * For collateral delta > 0 we just scale the full trade down (realized pnl and available collateral in diamond) so new trade value + sent to trader = prev trade value, the trading fee is taken from what we send to the trader (collateral sent to trader \< 0 not allowed), and the available collateral in diamond used is the proportional available collateral in diamond based on the position size delta * For leverage delta > 0 we realize the partial unrealized raw pnl (since position size is lower if we didn't do this it would lower the trade's pnl) minus what we sent to the trader so new trade value + sent to trader (when positive, otherwise gets sent to vault) = prev trade value, we charge the trading fee on the open trade (transfers fee from vault if available in diamond = 0), the available collateral in diamond is always zero (removed old traderDebt logic which used to realize partial negative pnl by reducing trade collateral), and if net pnl is negative we send the partial negative pnl (pending + realized) minus the manually realized pnl and already transferred negative pnl (already sent to vault in a previous partial close) to the vault, capped at total trade available collateral in diamond, we don't just send the partial net pnl to the vault because for example realized trading fees are not in the diamond so it wouldn't make sense * UI realized pnl data contains a useful data breakdown to display for the website backend/frontend, since the realized pnl value used on-chain to calculate the trade value is not really what the user expects to see as realized pnl (eg. when withdrawing collateral we realize negative pnl even if this action corresponds to realizing positive pnl because we have to impact the trade's value negatively to prevent withdrawing the same pnl, or eg. the trade's realized pnl gets scaled down on partial closes so it doesn't correspond to the total anymore) * New counter trade mechanism: * Can only be below a defined leverage to qualify (check on trade opening, partial adds, leverage increases), set per pair * Has to improve skew (any size that worsens the skew is returned to the user as collateral or leverage delta reduced for partial adds when collateral delta = 0) * Uses dynamic OI collateral skew (skew token \* current pair price) * Benefit from trading fees discount, set per pair * Both trades and limit/stop orders can be counter trades (once executed they turn into counter-trade trades) * New skew price impact: * Calculated using (existing skew token + trade size token / 2) / skew depth token (existing skew and trade size being signed integers) * Trade size token is calculated using position size collateral / price after fixed spread and cumulative volume price impact on partial add and full open, and using position size collateral delta \* trade position size token / trade position size collateral on partial close and full close (the same value is used to update pair token OIs) * Not included in max negative pnl on open check since it's neutral for pnl when opening and closing (otherwise couldn't trade when skew is too high) * Calculated using post-v10 skew only, pre-v10 trades don't pay any skew price impact on close * Specific skew depth stored per pair and collateral (same on both sides) * Price impact refactor: now fixed spread, cumulative vol price impact, and skew price impact percentages are first summed and then applied to the oracle price instead of applying them one on top of another * Pre-v10 trades can no longer partial add otherwise it would be a way to bypass the new funding fees and skew price impact * Traders can now withdraw net pnl from their trades without impacting their position size * We can now realize the pending holding fees of an open trade (eg. to solve imbalance if more trades closed with earned funding fees than paid funding fees temporarily) * We can now realize the negative pnl of an open trade (eg. to solve imbalance if more trades closed with positive pnl than negative pnl temporarily) => includes closing fixed spread and closing skew price impact, not closing cumulative volume price impact to avoid over-estimating negative PnL * Significant gas optimization: getTrade and getTradeInfo turned internal and use the library directly to avoid overhead from calling diamond proxy * GToken vaults receiveAssets function now supports a \_burn argument so we can send funding fees to the vault without burning them (since they are neutral, an equivalent amount of funding fees will be taken out of vault later) * All trading fees (opening, partial add/close etc.) / holding fees / partial negative pnl (leverage delta > 0) no longer impact the trade's collateral / position size when charged, they are stored as realized trading fees and just impact the trade's value / available collateral in diamond, so when a user opens a trade with 100 DAI at 20x it now opens exactly with 2,000 DAI size * Leverage validation refactor: * Partial add / increase leverage: Instead of validating the adjusted initial leverage to be below the max leverage, we now do this check on the new effective leverage (which increases when pnl is negative and decreases when pnl is positive) * Partial add/close and increase/decrease leverage: We only validate the adjusted initial leverage to be below 0.1x and uint24.max (unlikely to be hit) * Partial close / decrease leverage: removed minimum leverage checks apart from the adjusted initial leverage one (none on effective leverage), only one left is on full open (can easily be bypassed by partially closing or decreasing leverage after trade is opened but doesn't matter) * Partial close / Increase leverage: simplified minimum new collateral amount in request validation, now just has to be > min fee * Partial add refactor: * Removed new pos size > old pos size check in request validation since fees no longer impact the position size (still checks in callback because can happen due to rounding down of leverage when collateral delta > 0 but very unlikely) * Re-calculates the new position size after calculating new collateral / leverage (can be different than old pos + pos size delta due to leverage rounding) * Major bugfix: calculates existingPnlCollateral for new open price calculation using price after impact (before used raw oracle price) * New open price now rounded up for longs and down for shorts to avoid generating positive pnl due to rounding * Simplified oldPosSizePlusPnlCollateral calculation using int * Net trade value and liquidation price calculations now take into account the pending new funding/borrowing fees too as well as the realized pnl * Oracle changes: * Now expected to return nothing when the market is closed (because now we need the current pair price to realize trading fees on a trade to check if it can be liquidated and if we don't have it and just allow requests there can be a spam vector) * Requests can no longer be responded to 1 hour after they are initiated to prevent from keeping them pending * Expected to pass the current pair price too for lookback orders now since we need it to calculate pending holding fees * Closing fees are now always charged on full close, before it used to check if collateral was higher than the closing fee but it doesn't make sense anymore since a trade's collateral can't go below the min fee (check in partial close and increase leverage), and if there isn't enough available collateral in diamond it becomes negative so it's sent from vault to diamond and then distributed * Leverage updates and partial closes now both check the existing and new liq price * Leverage updates no longer result in \_updateOi calls even if there's a tiny position size difference due to rounding, doesn't matter * Only amount that gets burned anymore is the negative pnl on full close which is still available in diamond as well as partial close negative pnl (not holding fees, trading fees, or manually realized negative pnl) * Added liquidation check in \_openTradePrep to prevent executing a limit/stop order with lookbacks which would be immediately liquidated due to current pair price having moved too much against trade * Liquidation price calc function now accepts additional fee as input to simulate liq price after charging a fee / realizing pnl * Old price aggregator orderAnswers mapping deprecated in favor of new one that can store the current pair price (prices of OrderAnswer are now uint56 instead of uint64, max price is 7,205,759), any pending order from before v10 that wasn't fulfilled will have to be canceled after timeout and re-initiated * AggregatorAnswer no longer contains spreadP, now fetched from within getTradeOpeningPriceImpact and getTradeClosingPriceImpact * New ContractsVersion value of V10 to differentiate from trades opened before v10 (for trades opened before v10: no funding fee, no skew price impact, separate OI mapping, cannot partial add) * Trade struct now contains two additional properties: isCounterTrade and positionSizeToken (still fits into 3 slots) * Removed isWithinExposureLimit check in partial add and open trade request validation because it now requires the current pair price (for dynamic max skew calculation), check is still in callback * getTradeFeesCollateral / processFees now accept fee as input so calling function has to refresh fee tier and calculate the fee before calling, and the current trade fee tier points are only counted towards the next trade (before, a trade's fee tier points were credited before this same trade was executed, potentially making it reach the next fee tier for this same trade, impacting its fee) * No longer refresh fee tier in triggerOrder when byPassesLinkCost = false because we use a fixed link cost # v10.1 Update Source: https://docs.gains.trade/developer/technical-reference/contracts/changelogs/v10.1-update ### Changelog * All parameter updates (borrowing/funding) which require the current pair price are no longer done using the request/callback pattern but using signed prices from the oracles directly, in a single transaction * Triggering orders (SL/TP/LIQ/LIMIT\_OPEN/STOP\_OPEN) is now also possible using signed pair prices in a single transaction (previous request/callback pattern still exists as backup) * This both saves gas (5 less transactions) and decreases execution time * Signed pair prices are validated, stored temporarily in storage, and cleaned up at the end of the transaction so the storage gas costs are refunded * Refactored aggregator answer validation (OHLC values) and median/outliers filtering into separate helpers, re-used for signed prices validation (exact same logic as in `fulfill`) * Updated `SL_LIQ_BUFFER_P` to `5%`, from `10%` * Refactored `_limitSlDistance` to account for open and close fees, now min is `liqThreshold - 2 * totalPositionSizeP * leverage - SL_LIQ_BUFFER_P`. * Updated `withinExposureLimits` to allow skew improvements even when skew is above max, uses new `withinSkewLimits` helper. # v10.2 Update Source: https://docs.gains.trade/developer/technical-reference/contracts/changelogs/v10.2-update ## Changelog ### Summary The depth bands feature replaces the simple "1% depth" price impact model with a 30-band system that provides granular control over price impact curves. This enhancement allows for more realistic market depth modeling. ### Added #### New Features * 30 configurable bands (0-29) representing different liquidity depths * Piecewise calculation using trapezoidal rule for smooth price impact curves * Linear extrapolation beyond 100% depth for very large trades * Separate depth configurations for longs (above) and shorts (below) * Efficient storage packing: all band data in 2 slots per direction * Non-decreasing validation for band liquidity/offset values #### New Data Structures * `IPriceImpact.PairDepthBands` - Stores depth band liquidity configuration for each pair (4 slots: above/below × slot1/slot2) * `IPriceImpact.DepthBandsMapping` - Global mapping of band indices to band percentage offsets from mid price (2 slots) * `IPriceImpact.DepthBandParameters` - Working struct for depth band calculations #### New Functions * `initializeDepthBandsMapping(uint256 slot1, uint256 slot2)` - Initialize global bands offset mapping (reinitializer(25)) * `setPairDepthBands(uint256[] indices, PairDepthBands[] depthBands)` - Set depth bands liquidity for multiple pairs * `setDepthBandsMapping(uint256 slot1, uint256 slot2)` - Configure global bands offset values * `getPairDepthBands(uint256 pairIndex)` - Get single pair's encoded depth bands * `getPairDepthBands(uint256[] indices)` - Get multiple pairs' encoded depth bands (array version) * `getPairDepthBandsDecoded(uint256 pairIndex)` - Get single pair's decoded depth bands * `getPairDepthBandsDecoded(uint256[] indices)` - Get multiple pairs' decoded depth bands (array version) * `getDepthBandsMapping()` - Get global bands encoded mapping * `getDepthBandsMappingDecoded()` - Get global bands decoded mapping #### New Internal Functions * `_getDepthBandsPriceImpactP()` - New price impact getter using depth bands * `_getTotalDepthUsd()` - Extract total depth usd from encoded slot * `_getBandValue()` - Extract band value from encoded slots (returns ppm for mappings, bps for depths) * `_calculateDepthBandsPriceImpact()` - Core calculation using trapezoidal rule for average fill price #### New Constants * `DEPTH_BANDS_COUNT = 30` - Total number of depth bands * `DEPTH_BANDS_PER_SLOT1 = 14` - Number of bands stored in slot1 * `HUNDRED_P_BPS = 1e4` - 100% in bps ### Changed #### Libraries * `PriceImpactUtils` is now external and has been adjusted for the new bands feature #### Modified Functions * `getTradeCumulVolPriceImpactP()` - Now forwards to `_getDepthBandsPriceImpactP` implementation using depth bands #### Storage Updates * `IPriceImpact.PriceImpactStorage` struct updated: * Added `mapping(uint256 => PairDepthBands) pairDepthBands` * Added `DepthBandsMapping depthBandsMapping` * Reduced `__gap` array to \[36] to accommodate new storage ### Deprecated #### Storage * `pairDepths` - Replaced by `pairDepthBands` ### Removed #### Functions * `setPairDepths()` - Replaced by `setPairDepthBands()` * `getPairDepth()` - Replaced by `getPairDepthBands()` * `getPairDepths()` - Replaced by array version of `getPairDepthBands()` ### Technical Details #### Band Structure **PairDepthBands** (per-pair liquidity configuration): * Defines the actual liquidity distribution for each trading pair * 30 bands representing cumulative percentages of total depth (0-100%) * Each band liquidity percentage stored as basis points (bps), e.g., 2500 = 25% of total depth * Separate configurations for above/below market price * Storage encoding per direction: * Slot1: totalDepthUsd (32 bits) + bands 0-13 (16 bits each) * Slot2: bands 14-29 (16 bits each) **DepthBandsMapping** (global offset configuration): * Defines the cumulative offset from mid price at each band boundary * Values stored as parts per million (ppm), e.g., 130 = 0.013% offset from mid price * Storage encoding: * Slot1: bands 0-13 offsets (16 bits each, first 32 bits unused) * Slot2: bands 14-29 offsets (16 bits each) #### Calculation Method 1. Iterate through bands until trade size is consumed 2. Use trapezoidal rule for average impact within each band 3. Weight each band's contribution by depth consumed 4. Support linear extrapolation beyond 100% for large trades #### Variable Naming Conventions * Variables ending in `Usd` represent USD-denominated values (1e18) * Variables ending in `Ppm` represent parts per million (1e6) => percentage with 4 decimals * Variables ending in `Bps` represent basis points (1e4) => percentage with 2 decimals * `priceImpactP` represents price impact percentage in 1e10 precision #### Migration Path 1. Initialize global depth bands mapping using `initializeDepthBandsMapping()` 2. Migrate existing pairs from old depth model to depth bands 3. New pairs should use `setPairDepthBands()` directly 4. Between deployment and setting bands, dynamic price impact will be 0 5. Monitor and adjust band configurations as needed ### Key Specifications #### Backwards Compatibility * **Fully backwards compatible**: The new depth bands system produces identical results to the previous linear formula when configured with linear bands and the same depth values #### Validation Requirements * **Pair depth bands**: Must include the value 100% (10,000 bps) as one of the band values and it must be the maximum value * **Pair depth bands**: Must be non-decreasing across bands since they are cumulative (each band value ≥ previous band value) * **Global depth offsets**: Must be non-decreasing across bands since they are cumulative (each offset ≥ previous offset) #### Trade Splitting Protection * **Cumulative volume price impact**: Has 2x weight in the calculation to ensure trade splitting remains unprofitable * This design choice prevents traders from gaming the system by splitting large trades into smaller ones ### Gas Optimization * Efficient storage packing reduces reads to 2 slots per direction + 2 slots for global offsets => 4 slots total * Early exit from loop when trade size has been consumed # v9 Update Source: https://docs.gains.trade/developer/technical-reference/contracts/changelogs/v9-update ## Summary * New features: update trade leverage, update trade position size * Important changes: min position size requirement replaced by minimum fee (trade collateral must be >= 5x min fee when opening), liquidation price now takes into account closing fees, getPnlPercent negative PnL capped at -100% * Important refactors: TradingStorageUtils now handles all OI update calls, constants all moved to ConstantsUtils, common helpers moved to TradingCommonUtils, removed GNSTradingStateCopy facet, tradeInfo.collateralPriceUsd/tradeInfo.lastOiUpdateTs values now set in GNSPriceImpact.addPriceImpactOpenInterest instead of GNSTradingStorage.storeTrade * Bugfixes: liquidation fees now don't take into account fee tiers, getTradeValuePure returns 0 for liquidations (due to precision loss it was possible liquidation price was reached but pnl + borrowing fees didn't reach -90% PnL), and \_openTrade now hardcodes \_trade.\_\_placeholder input to 0 ## Full Changelog ### core/facets/GNSBorrowingFees (update) * New resetTradeBorrowingFees function (pending borrowing fees are charged and reset on partial updates) ### core/facets/GNSPairsStorage (update) * New pairMinFeeUsd getter function (trade fee at minimum position size, replaces minimum position size requirement) ### core/facets/GNSPriceImpact (update) * addPriceImpactOpenInterest and removePriceImpactOpenInterest now accept trader/index/oi delta in collateral tokens oi delta in USD/pairIndex/long, and removePriceImpactOpenInterest no longer accepts \_addTs * Added getTradeLastWindowOiUsd and getTradePriceImpactInfo getters ### core/facets/GNSTradingCallbacks (update) * New callback functions for partials: updateLeverageCallback, increasePositionSizeMarketCallback, decreasePositionSizeMarketCallback ### core/facets/GNSTradingInteractions (update) * New functions to initiate partial updates: updateLeverage, increasePositionSize, decreasePositionSize * openTradeMarketTimeout and closeTradeMarketTimeout turned into cancelOrderAfterTimeout (supports all market order types including partials) ### core/facets/GNSTradingStateCopy.sol (removed) * Not needed anymore now that v8 transition is done ### core/facets/GNSTradingStorage (update) * New updateTradePosition function to update a trade's collateral, leverage, and open price * Array getters (eg. getTraders) now call the new ArrayGetters library * getPnlPercent function removed (moved to TradingCommonUtils) * getPendingOpenOrderType moved to ConstantsUtils ### interfaces/libraries/IBorrowingFeesUtils.sol (update) * BorrowingInitialAccFeesStored event now emits whether trade is long or short ### interfaces/libraries/IPriceImpactUtils.sol (update) * PriceImpactOpenInterestAdded event now emits isPartial ### interfaces/libraries/ITradingCallbacksUtils.sol (update) * Now inherits IUpdateLeverageUtils (leverage updates types and events), IUpdatePositionSizeUtils (position size updates types and events), and ITradingCommonUtils (fee charged events), so that IGNSMultiCollatDiamond also inherits those * Fee charged events moved to ITradingCommonUtils because all functions that charge fees were moved there (since now they're used in many different places other than TradingCallbacksUtils, eg. partials libraries) ### interfaces/libraries/ITradingCommonUtils.sol (new) * Contains fee charged events ### interfaces/libraries/ITradingInteractionsUtils.sol (update) * Now inherits IUpdateLeverageUtils (leverage updates types and events), IUpdatePositionSizeUtils (position size updates types and events) * AbovePairMaxOi and AboveGroupMaxOi errors consolidated into AboveExposureLimits, BelowMinPositionSizeUsd error removed, added ConflictingPendingOrder (eg. when trying to close trade that has a pending partial update) and InsufficientCollateral (trade collateral \< 5 \* min fee when opening trade) errors ### interfaces/libraries/ITradingStateCopyUtils.sol (removed) * Not needed anymore now that v8 transition is done ### interfaces/libraries/ITradingStorageUtils.sol (update) * Removed getPendingOpenOrderType (moved to ConstantsUtils) * Added TradePositionUpdated event ### interfaces/libraries/IUpdateLeverageUtils.sol (new) * Contains update leverage events (LeverageUpdateInitiated, LeverageUpdateExecuted) and inherits IUpdateLeverage for types ### interfaces/libraries/IUpdatePositionSizeUtils.sol (new) * Contains update position size events (PositionSizeUpdateInitiated, PositionSizeIncreaseExecuted, PositionSizeDecreaseExecuted) and inherits IUpdatePositionSize for types ### interfaces/types/IBorrowingFees.sol (update) * Added useBorrowingFees property to LiqPriceInput struct (in increase position size callback we calculate new liq price using new leverage and collateral (- borrowing fees) but borrowing fees haven't been reset yet so we pass useBorrowingFees=false, all other calls pass true) ### interfaces/types/IPriceImpact.sol (update) * New tradePriceImpactInfos mapping * OiWindowUpdate struct (used for events) now also has trader and index properties * New TradePriceImpactInfo struct to store lastWindowOiUsd (and potentially more, has a placeholder) ### interfaces/types/ITradingCallbacks.sol (update) * Added LIQ\_REACHED to CancelReason enum (we cancel all partial updates if existing/updated trade can be liquidated) * Added closingFeeCollateral, triggerFeeCollateral, and collateralLeftInStorage to Values struct ### interfaces/types/ITradingStateCopy.sol (removed) * Not needed anymore now that v8 transition is done ### interfaces/types/ITradingStorage.sol (update) * Added UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE values to PendingOrderType enum ### interfaces/types/IUpdateLeverage.sol (new) * Contains useful structs for leverage updates (UpdateLeverageInput for request, UpdateLeverageValues for callback) ### interfaces/types/IUpdatePositionSize.sol (new) * Contains useful structs for position size updates (DecreasePositionSizeInput and IncreasePositionSizeInput for request, DecreasePositionSizeValues and IncreasePositionSizeValues for callback) ### libraries/ArrayGetters.sol (new) * New external library to reduce TradingStorageUtils size * Array getters are what take the most amount of bytecode in a contract generally, so if needed we can move them in this new library * For now only contains array getters of TradingStorageUtils but it could contain getters of other facets if needed too ### libraries/BorrowingFeesUtils.sol (update) * LIQ\_THRESHOLD\_P AND P\_1 removed, replaced by ConstantsUtils.LIQ\_THRESHOLD\_P and ConstantsUtils.P\_10 respectively (same values) * handleTradeBorrowingCallback: initial acc fees initalization when \_open = true replaced by resetTradeBorrowingFees call * New resetTradeBorrowingFees function to reset a trade's borrowing fees to 0 by setting its initial acc fees to current acc pair/group borrowing fees, useful after partial updates since we charge pending borrowing fees and after we need to reset them to 0 to not charge them again later * getTradeLiquidationPrice now calculates and passes closing fees to \_getTradeLiquidationPrice, and logic adjusted for \_input.useBorrowingFees (if false, passes 0 borrowing fees to \_getTradeLiquidationPrice) * \_getTradeLiquidationPrice's \_borrowingFeeCollateral input renamed to \_feesCollateral, now expects closing fees + borrowing fees instead of just borrowing fees, but calculations stay the same ### libraries/ConstantsUtils.sol (new) * New internal library for useful constants (P\_10, MAX\_SL\_P, MAX\_PNL\_P, LIQ\_THRESHOLD\_P, MAX\_OPEN\_NEGATIVE\_PNL\_P) * Values for these constants didn't change, they were just moved to this library ### libraries/PairsStorageUtils.sol (update) * Added pairMinFeeUsd getter, uses gov fee \* 2 + trigger fee on min position size usd (eg. 0.08% on crypto) ### libraries/PriceAggregatorUtils.sol (update) * PRECISION constant replaced by ConstantsUtils.P\_10 * getPrice: isLookback is now equal to !ConstantsUtils.isOrderTypeMarket * fulfill: added new callbacks for UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE order types (explicit check) * getLinkFee: when \_positionSizeCollateral > 0 (doesn't bypass trigger link fee) uses TradingCommonUtils.getPositionSizeCollateralBasis to charge pairOracleFeeP on max(pos size, min pos size) ### libraries/PriceImpactUtils.sol (update) * Replaced PRECISION by ConstantsUtils.P\_10 * addPriceImpactOpenInterest: arguments changed from \_openInterestUsd/\_pairIndex/\_long to \_trader/\_index/\_oiDeltaCollateral, now responsible for converting the collateral OI passed to USD value using current collateral/usd price, added logic for partials: if last window where OI was added for trade hasn't expired then remove OI from that window and add move it to the current window scaling to the new collateral/usd price, now responsible (instead of GNSTradingStorage) for setting tradeInfo.lastOiUpdateTs and tradeInfo.collateralPriceUsd, and finally stores the new tradePriceImpactInfo.lastWindowOiUsd value * removePriceImpactOpenInterest: arguments changed from \_openInterestUsd/\_pairIndex/\_long/\_addTs to \_trader/\_index/\_oiDeltaCollateral, now fetches timestamp when OI was last added from within the function using tradeInfo.lastOiUpdateTs, responsible for converting the OI collateral value input to USD using tradeInfo.collateralPriceUsd, now caps the removal of OI to the new lastWindowOiUsd value (since any trade OI that's not part of lastWindowOiUsd has necessarily expired and is in another older window), and reduces lastWindowOiUsd by the oi delta so it stays accurate * New getTradeLastWindowOiUsd getter that simply returns lastWindowOiUsd when it's set to a value > 0, otherwise returns the USD position size of the trade at the time of opening (useful for trades opened before v9) * New getTradePriceImpactInfo getter to return values of the new mapping ### libraries/ReferralsUtils.sol (update) * Replaced PRECISION by ConstantsUtils.P\_10 ### libraries/TradingCallbacksUtils.sol (update) * PRECISION replaced by ConstantsUtils.P\_10, LIQ\_THRESHOLD\_P by ConstantsUtils.LIQ\_THRESHOLD\_P, and MAX\_OPEN\_NEGATIVE\_PNL\_P by ConstantsUtils.MAX\_OPEN\_NEGATIVE\_PNL\_P * \_transferCollateralToAddress replaced by TradingCommonUtils.transferCollateralTo, \_updateTraderPoints replaced by TradingCommonUtils.updateFeeTierPoints, \_handleGovFees replaced by radingCommonUtils.distributeGovFeeCollateral, \_getPositionSizeCollateral replaced by TradingCommonUtils.getPositionSizeCollateral, diamond.getPnlPercent replaced by TradingCommonUtils.getPnlPercent, \_getTradeValue replaced by TradingCommonUtils.getTradeValueCollateral, \_marketExecutionPrice replaced by TradingCommonUtils.getMarketExecutionPrice, \_withinExposureLimits replaced by TradingCommonUtils.isWithinExposureLimits * When a trade is canceled (openTradeMarketCallback, closeTradeMarketCallback) we charge gov fee on min pos size / 2 instead of gov fee on full position size * closeTradeMarketCallback: v.positionSizeCollateral removed (was used to calculate closing fees), closing fees calculation moved to inside \_unregisterTrade, removed OI removal when canceled (now handled inside GNSTradingStorage.updateTradeCollateralAmount) * executeTriggerCloseOrderCallback: v.positionSizeCollateral removed (was used to calculate closing fees), v.liqPrice uses TradingCommonUtils wrapper, v.reward1 calculation removed (now done inside \_unregisterTrade) and same conditions used to determine cancelReason directly instead, removed v.gnsPriceCollateral (unused), just pass order type to \_unregisterTrade instead of closing fees, no longer call \_handleTriggerRewards (done from within \_unregisterTrade depending on orderType) * Added: updateLeverageCallback (tradingActivated modifier), increasePositionSizeMarketCallback (tradingActivated modifier), decreasePositionSizeMarketCallback (tradingActivatedOrCloseOnly modifier) for partials, they just return early if order is not open like for other callbacks and call the corresponding UpdateLeverageLifecycles/UpdatePositionSizeLifecycles execute callback function * Removed: \_transferCollateralToAddress, \_distributeStakingReward, \_sendToVault, \_handleTriggerRewards, \_handleGovFees, \_updateTraderPoints, \_distributeReferralReward, \_handleInternalOnRegisterUpdates, \_convertCollateralToUsd, \_convertCollateralToGns, \_getTradeValuePure, \_marketExecutionPrice, \_getTradeValue, \_withinExposureLimits, \_getGToken, \_getPositionSizeCollateral (all moved/refactored to TradingCommonUtils) * \_registerTrade: simplified a lot, all opening fees calculations / distributions moved to TradingCommonUtils.processOpeningFees, \_handleInternalOnRegisterUpdates call removed as GNSTradingStorage manages OI deltas now (directly in storeTrade) * \_unregisterTrade: \_marketOrder input replaced by \_orderType, no longer accepts closing fees as input, moved fee tier closing fees calculations/gToken fee distribution/GNS staking fee distribution/collateralLeftInStorage calculation to TradingCommonUtils.processClosingFees, removed handleTradeBorrowingCallback/removePriceImpactOpenInterest calls as GNSTradingStorage.closeTrade now handles OI deltas, now calls TradingCommonUtils.handleTradePnl for PnL/collateral transfers logic * \_openTradePrep: pass positionSizeCollateral to isWithinExposureLimits instead of collateral and leverage ### libraries/TradingCommonUtils.sol (new) * New external library that contains helpers called by multiple libraries * Contains useful getters (pnl, position size, etc.), collateral/pnl transfer functions, fee distributions, OI delta handling * Mostly renames of previous private functions in TradingCallbacksUtils and TradingInteractionsUtils * getPnlPercent: now caps negative PnL at -100% * getMinPositionSizeCollateral: new function that converts min pos usd to min pos collateral and returns it * getPositionSizeCollateralBasis: returns max(position size input, min position size collateral) for fees calculations * getTradeValuePure: accepts \_orderType and returns 0 if liquidation, now takes into account closing fees for liquidation threshold * isWithinExposureLimits: now accepts \_positionSizeCollateralDelta instead of trade collateral and leverage (so it works for partials too) * getTradeBorrowingFeeCollateral: useful wrapper that takes trade struct as input * getTradeLiquidationPrice: same just a wrapper that takes trade struct as input * getGovFeeCollateral: new getter that returns gov fee after fee tier based on position size * getClosingFeesCollateral: new getter that returns vault and gns staking fees based on closing fee/trigger fee/order type * revertIfTradeHasPendingMarketOrder: new helper to prevent two pending market orders on the same trade * transferCollateralFrom: new helper to transfer collateral from trader to diamond if amount > 0 * handleTradePnl: new helper to handle collateral/pnl transfers between vault/diamond and trader (used for full closes and partial closes) * distributeVaultFeeCollateral: new helper to distribute vault reward * distributeExactGovFeeCollateral: new helper to distribute an exact amount of gov fee * processOpeningFees: new helper that contains the previous fee calculation / distribution logic of \_registerTrade used for both full and partial trade open and returns the total opening fee charged (difference is it charges fees on max(position size input, min position size) and it uses !ConstantsUtils.isOrderTypeMarket to know if it should distribute the trigger fee) * processClosingFees: new helper that contains the previous fee calculation / distribution logic of \_unregisterTrade used for full trade closes only and returns the value struct with the fee values and collateralLeftInStorage (difference is it charges fees on max(position size input, min position size), it calculates the closing and trigger fees based on the order type (and only applies fee tier if order type is not liquidation), it calculates the vault and gns staking fees by calling getClosingFeesCollateral, it only distributes the gns staking and vault fees if trade collateral is big enough to pay (otherwise it's still charged but as negative PnL only), and it distributes the trigger gns fee depending on the order type using !ConstantsUtils.isOrderTypeMarket) * addOiCollateral: new helper to add borrowing/price impact windows OI in one call (flexible amount) * addTradeOiCollateral: new helper to add borrowing/price impact windows OI in one call (trade position size) * removeOiCollateral: new helper to remove borrowing/price impact windows OI in one call (flexible amount) * removeTradeOiCollateral: new helper to remove borrowing/price impact windows OI in one call (trade position size) * handleOiDelta: new helper that either calls addOiCollateral or removeOiCollateral based on a trade's new position size and its existing position size ### libraries/TradingInteractionsUtils.sol (update) * PRECISION replaced by ConstantsUtils.P\_10, MAX\_SL\_P replaced by ConstantsUtils.MAX\_SL\_P, and MAX\_OPEN\_NEGATIVE\_PNL\_P replaced by ConstantsUtils.MAX\_OPEN\_NEGATIVE\_PNL\_P * getPendingOrderType calls now use ConstantsUtils * Replaced \_getPositionSizeCollateral by TradingCommonUtils.getPositionSizeCollateral, \_transferCollateralToTrader by TradingCommonUtils.transferCollateralTo, and \_receiveCollateralFromTrader by TradingCommonUtils.transferCollateralFrom (those 3 private functions were removed) * closeTradeMarket: Replace AlreadyBeingMarketClosed() check by TradingCommonUtils.revertIfTradeHasPendingMarketOrder call * Added: updateLeverage, increasePositionSize, decreasePositionSize that call the create request function in their lifecycles library * triggerOrder: use TradingCommonUtils.getTradeLiquidationPrice wrapper * openTradeMarketTimeout/closeTradeMarketTimeout: removed in favor of cancelOrderAfterTimeout which only accepts an order index now instead of the full order id (impossible to input another address than yours, removes need for this check) * triggerOrder: use ConstantsUtils.isOrderTypeMarket for WrongOrderType check * cancelOrderAfterTimeout: Supports all market orders (ConstantsUtils.isOrderTypeMarket), transfers back trade collateral for MARKET\_OPEN, transfers back partial collateral for UPDATE\_LEVERAGE (leverage decrease), and transfers back partial collateral for MARKET\_PARTIAL\_OPEN (no longer calls closeTradeMarket() again for MARKET\_CLOSE orders) * \_openTrade: overwrite \_trade.\_\_placeholder to 0, consolidated AbovePairMaxOi and AboveGroupMaxOi checks into AboveExposureLimits using TradingCommonUtils.isWithinExposureLimits, replaced BelowMinPositionSizeUsd check by InsufficientCollateral (trade collateral must be >= min fee) ### libraries/TradingStateCopyUtils.sol (removed) * Not needed anymore now that v8 transition is done ### libraries/TradingStorageUtils.sol (update) * Turned into external library (otherwise GNSTradingStorage facet contract would be above max limit) * PRICE\_PRECISION replaced by ConstantsUtils.P\_10, MAX\_SL\_P replaced by ConstantsUtils.MAX\_SL\_P, MAX\_PNL\_P not used anymore * storeTrade: removed TradeInfoCollateralPriceUsdZero check (now tradeInfo.collateralPriceUsd is set by GNSPriceImpact.addPriceImpactOpenInterest), enforces \_tradeInfo.lastOiUpdateTs to 0 to make sure isPartial = false when calling addPriceImpactOpenInterest, added TradingCommonUtils.addTradeOiCollateral call when tradeType is TRADE * updateTradeCollateralAmount: added TradingCommonUtils.handleOiDelta call, added i.createdBlock update (because reducing a trade's collateral now potentially changes the trade's liquidation price with the liq price taking into account closing fees and closing fees having a minimum value) * updateTradePosition: new helper to update a trade's collateralAmount/leverage/openPrice, same checks as updateTradeCollateralAmount (trade must be open, trade type must be TRADE, and additionally new collateral \* new leverage > 0 and new openPrice > 0) calls \_limitTpDistance and \_limitSlDistance again based on updated values, updates i.createdBlock/tpLastUpdatedBlock/slLastUpdatedBlock so lookbacks work properly (tp/sl potentially updated, liquidation price updated) * closeTrade: added TradingCommonUtils.removeTradeOiCollateral call when tradeType is TRADE * Array getters (getTraders, getTrades, getAllTrades, getTradeInfos, getAllTradeInfos, getPendingOrders, getAllPendingOrders) moved to new ArrayGetters external library * getPnlPercent moved to TradingCommonUtils * \_validateTrade: use TradingCommonUtils.getPositionSizeCollateral * Removed getPendingOpenOrderType (moved to ConstantsUtils) ### libraries/updateLeverage/UpdateLeverageLifecycles.sol (new) * New external library to handle leverage updates lifecycles * requestUpdateLeverage: create request (used by TradingInteractionsUtils) * executeUpdateLeverage: callback (used by TradingCallbacksUtils) ### libraries/updatePositionSize/DecreasePositionSizeUtils.sol (new) * New internal library to handle position size decreases, used by the new UpdatePositionSizeLifecycles library * validateRequest: request validation, prepareCallbackValues: all the calculations, validateCallback: callback validation, updateTradeSuccess: success callback, handleCanceled: canceled callback ### libraries/updatePositionSize/IncreasePositionSizeUtils.sol (new) * New internal library to handle position size increases, used by the new UpdatePositionSizeLifecycles library * validateRequest: request validation, prepareCallbackValues: all the calculations, validateCallback: callback validation, updateTradeSuccess: success callback, handleCanceled: canceled callback ### libraries/updatePositionSize/UpdatePositionSizeLifecycles.sol (new) * New external library to handle position size updates lifecycles * requestIncreasePositionSize: create position size increase request (used by TradingInteractionsUtils) * requestDecreasePositionSize: create position size decrease request (used by TradingInteractionsUtils) * executeIncreasePositionSizeMarket: increase position size callback (used by TradingCallbacksUtils) * executeDecreasePositionSizeMarket: decrease position size callback (used by TradingCallbacksUtils) # v9.1 Update Source: https://docs.gains.trade/developer/technical-reference/contracts/changelogs/v9.1-update ## Summary * New features: GNS staking fees are all used to buy GNS, sends an adjustable % to treasury, burn, and GNS staking rewards and uses an adjustable price premium; new compound function in GNS staking * Other changes: There is a 100 seconds cooldown to wait before one can unstake after staking GNS to prevent flashloans (vests must be 100 seconds long at least too now) ## Full Changelog ### core/GNSStaking.sol (update) * New `UNSTAKING_COOLDOWN_SECONDS` constant (= 100 seconds) * New `stakerInfos` mapping to store each user's lastDepositTs * New `notInCooldown` modifier, used by `unstakeGns`, reverts if user deposited less than `UNSTAKING_COOLDOWN_SECONDS` ago * `_harvestToken`, `_harvestFromUnlock`, `_harvestTokenFromUnlock`, `harvestToken`, `harvestTokenFromUnlock`, `harvestTokenAll` now all return the pending token rewards (needed for compound function) * New `compoundGnsRewards` function: harvests pending regular rewards and vest rewards (accepts vests `_ids` as input) and stakes them in the same transaction * `stakeGns`: now public (called by `compoundGnsRewards`) and stores current timestamp in `stakerInfos` mapping for caller * `unstakeGns`: now uses `notInCooldown` modifier * `createUnlockSchedule`: now checks vest duration >= `UNSTAKING_COOLDOWN_SECONDS` instead of accepting any non-zero value ### core/abstract/GNSDiamondStorage.sol (update) * Added `otcStorage` private state var for new `GNSOtc` facet ### core/facets/GNSOtc.sol (new) * New facet which handles the collateral -> GNS OTC buying process and transfer to treasury, burn, and GNS staking rewards (adjustable percentages) * `initializeOtc`: infinite approval of GNS staking contract for GNS token and config initialization * `updateOtcConfig`: update treasury address and percentages * `addOtcCollateralBalance`: increases available collateral balance for OTC buying (used by `GNSTradingCallbacks` when distributing GNS staking fee) * `sellGnsForCollateral`: executes OTC transaction; diamond receives GNS and sender receives collateral tokens, available collateral balance for OTC decreases accordingly * `getOtcConfig`, `getOtcBalance`, `getOtcRate` getters ### interfaces/IGNSMultiCollatDiamond.sol (update) * Now inherits `IOtcUtils` ### interfaces/IGNSStaking.sol (update) * New `StakerInfo` struct (`lastDepositTs` and placeholder) ### interfaces/IGeneralErrors.sol (update) * New `InsufficientBalance()` error ### interfaces/libraries/IOtcUtils.sol (new) * Interface for new `GNSOtc` facet: contains all types, functions, events, and custom errors ### interfaces/types/IOtc.sol (new) * Interface for new `GNSOtc` facet: contains all types * `OtcStorage` struct: `collateralBalances` mapping, `otcConfig` struct * `OtcConfig` struct: treasury address, percentages (treasury, GNS staking, burn), price premium ### interfaces/types/IPriceAggregator.sol (update) * Fixed `__gap` array length, reduced from 41 to 39 ### interfaces/types/ITypes.sol (update) * Now inherits new facet types `IOtc` ### libraries/OtcUtils.sol (new) * Internal library for new `GNSOtc` facet ### libraries/StorageUtils.sol (update) * Added `GLOBAL_OTC_SLOT` constant for new `GNSOtc` facet ### libraries/TradingCommonUtils.sol (update) * `convertCollateralToGns`, `transferCollateralTo`, and `_getMultiCollatDiamond` are now internal: allows not linking TradingCommonUtils to `GNSOtc` as internal functions are imported directly into the bytecode, should only make functions external when it becomes an issue for size * New `transferGnsTo` and `transferGnsFrom` helpers to handle simple GNS transfers between users and the diamond * `distributeGnsStakingFeeCollateral` now calls `_getMultiCollatDiamond().addOtcCollateralBalance` instead of `gnsStaking.distributeReward` # v9.1.1 Update Source: https://docs.gains.trade/developer/technical-reference/contracts/changelogs/v9.1.1-update ## Summary * Apply fee tiers to oracle rewards ## Full Changelog ### core/facets/GNSPriceAggregator.sol (update) * `getPrice` and `getLinkFee` now accept `_trader` argument ### interfaces/libraries/IPriceAggregatorUtils.sol (update) * Adjusted `getPrice` and `getLinkFee` functions definitions * Updated `PriceRequested` event: now emits trader address, and `collateralIndex`/`trader`/`pairIndex` are now the indexed properties (`orderType` and `job` no longer indexed) ### libraries/updateLeverage/UpdateLeverageLifecycles.sol (update) * `_initiateRequest`: small adjustment to avoid stack too deep, now passes `_trade.user` to `getPrice` ### libraries/updatePositionSize/UpdatePositionSizeLifecycles.sol (update) * `_initiateRequest`: passes `_trade.user` to `getPrice` ### libraries/PriceAggregatorUtils.sol (update) * Library is now external * `getPrice` now accepts `_trader` argument, refreshes fee tier for `_trader` right before calculating link fee, passes `_trader` to `getLinkFee` to apply his fee tier to the oracle link fees, and `PriceRequested` now emits `_trader` * `getLinkFee` now accepts `_trader` and applies his fee tier to the link fee result ### libraries/TradingInteractionsUtils.sol (update) * `closeTradeMarket`: passes `t.user` to `getPrice` * `triggerOrder`: refreshes `t.user`'s fee tier before receiving the link fee from the caller, passes `t.user` to `getLinkFee` * `_openTrade`: passes `_trade.user` to `getPrice` * `_getPriceTriggerOrder`: passes `_trade.user` to `getPrice` # v9.2.1 Update Source: https://docs.gains.trade/developer/technical-reference/contracts/changelogs/v9.2.1-update ## Summary * 50% of the spread and price impact is now charged on trade opening and closing instead of 100% on trade opening * Existing trades don't pay any spread or impact on close (since they already paid in full on open), and they keep paying 100% spread when partial adding * Spread and price impact on close use the reverse direction as opening spread (makes price lower for longs and higher for shorts) * Price impact on close uses the opposite side depth and opposite side price impact OI (= cumulative vol now) * Price impact OI windows now use new cumulative volume logic (much shorter windows duration possible because more accurate, opening a long / closing a short uses/adds to long windows, opening a short / closing a long uses/adds to short windows, new cumulative factor which will be set to 1 to start with but can be used to adjust weight of price impact OI in price impact formula), we never remove any OI from windows anymore (logic much simpler, no longer need to move trade OI to current window for partials) * Closing price impact higher for short-term trades (depending on protection factor blocks duration and protection factor multiplier per pair), only when net PnL is positive * Liquidation price now takes into account the closing spread (not the price impact) for trades opened after v9.2 and uses new logic for the liquidation pnl % threshold (closer pnl % threshold as leverage increases, more aggressive for higher leverages similarly to MMR) * Existing trades aren't affected by the new liquidation threshold logic, liquidation parameters for trades are stored on opening so they can't change for an open trade even when a group's liquidation parameters are updated, however a trade's liquidation params are refreshed to current value when position size is increased using partials * New stop loss max distance is `liqPnlThresholdP - 10%` (eg. -70% PnL when trade liq pnl % threshold is -80%) * Added max slippage on close (market close, partial close, tp/sl) mechanism: by default 1% for all opened trades, can be adjusted after trade is open * Extracted cancel reason logic for limit/stop/tp/sl/liq callbacks into getters, will be used by EA-lookbacks to check ability to execute at past chain state * LIQ triggers no longer turned into SL triggers when SL is closer otherwise user could set very low max closing slippage and would never be able to be liquidated if price went past his SL and LIQ price, trigger bots will prioritize SL over LIQ when possible ## Full Changelog ### core/facets/GNSPairsStorage.sol (update) * Added `initializeGroupLiquidationParams`, `setGroupLiquidationParams`, `getGroupLiquidationParams`, and `getPairLiquidationParams` ### core/facets/GNSPriceAggregator.sol (update) * `getPrice` now accepts `_tradeId` instead of `_trader` ### core/facets/GNSPriceImpact.sol (update) * Added `initializePairFactors`, `setProtectionCloseFactors`, `setProtectionCloseFactorBlocks`, `setCumulativeFactors`, `getPairFactors` * Removed `removePriceImpactOpenInterest`, `getTradeLastWindowOiUsd`, `getTradePriceImpactInfo` * `addPriceImpactOpenInterest` now accepts `_open` argument * `getTradePriceImpact` now accepts `_isPnlPositive`, `_open`, `_lastPosIncreaseBlock`, and `_contractsVersion` arguments ### core/facets/GNSTradingCallbacks.sol (update) * Added `validateTriggerOpenOrderCallback` and `validateTriggerCloseOrderCallback` getters ### core/facets/GNSTradingInteractions.sol (update) * New `updateMaxClosingSlippageP` function * `closeTradeMarket` and `decreasePositionSize` now accept `_expectedPrice` argument (used for max slippage check in callbacks) ### core/facets/GNSTradingStorage.sol (update) * New `updateTradeMaxClosingSlippageP` function * `updateTradePosition` now accepts `_isPartialIncrease` argument * Added `getTradeLiquidationParams`, `getTradesLiquidationParams`, `getAllTradesLiquidationParams`, and `getCurrentContractsVersion` ### interfaces/IGeneralErrors.sol (update) * Added `WrongOrderType()` error ### interfaces/libraries/IPairsStorageUtils.sol (update) * Added new function definitions * Added `GroupLiquidationParamsUpdated` event * Added `MaxLiqSpreadPTooHigh`, `WrongLiqParamsThresholds`, `WrongLiqParamsLeverages`, `StartLiqThresholdTooHigh`, `EndLiqThresholdTooLow`, `StartLeverageTooLow`, `EndLeverageTooHigh` ### interfaces/libraries/IPriceAggregatorUtils.sol (update) * Adjusted `getPrice` function definition * Updated `PriceRequested` event: now emits `tradeId` instead of `trader` ### interfaces/libraries/IPriceImpactUtils.sol (update) * Added new function definitions * Removed deprecated function definitions * Adjusted `addPriceImpactOpenInterest` and `getTradePriceImpact` functions definitions * Added `ProtectionCloseFactorUpdated`, `ProtectionCloseFactorBlocksUpdated`, and `CumulativeFactorUpdated` events * Removed `isPartial` from `PriceImpactOpenInterestAdded` event * Removed `PriceImpactOpenInterestRemoved` event ### interfaces/libraries/ITradingCallbacksUtils.sol (update) * Added `validateTriggerOpenOrderCallback` and `validateTriggerCloseOrderCallback` functions definitions ### interfaces/libraries/ITradingCommonUtils.sol (update) * Added `TradePriceImpactInput` struct to avoid stack too deep in `getTradeClosingPriceImpact` ### interfaces/libraries/ITradingInteractionsUtils.sol (update) * Added `updateMaxClosingSlippageP` function definition * Adjusted `closeTradeMarket` and `decreasePositionSize` functions definitions * Removed `WrongOrderType()` error ### interfaces/libraries/ITradingStorageUtils.sol (update) * Added new function definitions * Adjusted `updateTradePosition` function definition * `TradeStored` event now also emits the trade liquidation params * `TradePositionUpdated` now emits `isPartialIncrease` * New `TradeMaxClosingSlippagePUpdated` event ### interfaces/libraries/IUpdatePositionSizeUtils.sol (update) * Added `long` and `collateralPriceUsd` properties to `PositionSizeIncreaseExecuted` and `PositionSizeDecreaseExecuted` events ### interfaces/types/IBorrowingFees.sol (update) * `LiqPriceInput` struct has new `liquidationParams` property ### interfaces/types/IPairsStorage.sol (update) * Added `groupLiquidationParams` mapping and corresponding `GroupLiquidationParams` struct * `__gap` length decreased from 41 to 40 ### interfaces/types/IPriceImpact.sol (update) * Added `pairFactors` mapping * `__gap` length decreased from 46 to 45 * Added `_open` property to `OiWindowUpdate` struct * New `PairFactors` struct ### interfaces/types/ITradingStorage.sol (update) * Added `tradeLiquidationParams` mapping * `__gap` length decreased from 39 to 38 * New `ContractsVersion` enum * `TradeInfo` struct now has `contractsVersion` and `lastPosIncreaseBlock` properties, and `__placeholder` was reduced from `uint48` to `uint8` ### interfaces/types/IUpdatePositionSize.sol (update) * Added `expectedPrice` property to `DecreasePositionSizeInput` struct * Added `priceAfterImpact` property to `DecreasePositionSizeValues` struct ### libraries/ArrayGetters.sol (update) * Added `getTradesLiquidationParams` and `getAllTradesLiquidationParams` getters ### libraries/BorrowingFeesUtils.sol (update) * `getTradeLiquidationPrice`: calculate `closingFeesCollateral` using new `TradingCommonUtils.getTotalClosingFeesCollateral` helper, pass input liquidation params, trade contracts version, and pair spread % to `_getTradeLiquidationPrice` * `_getTradeLiquidationPrice`: new `_liquidationParams`, `_contractsVersion`, and `_pairSpreadP` arguments, `_collateralPrecisionDelta` is now uint256 (saves one var to avoid stack too deep), calculate `liqPnlThresholdP` using new `TradingCommonUtils.getLiqPnlThresholdP` helper, in `collateralLiqNegativePnlInt` calculation divide by `1e10` because of new liq threshold precision, if trade opened after v9.2 make liquidation price distance lower by closing spread (= 1/2 pair spread %, capped at `maxLiqSpreadP`) ### libraries/ConstantsUtils.sol (update) * Replaced `MAX_SL_P` by `SL_LIQ_BUFFER_P=10%`, renamed `LIQ_THRESHOLD_P` to `LEGACY_LIQ_THRESHOLD_P`, added `MIN_LIQ_THRESHOLD_P=50%`/`MAX_LIQ_SPREAD_P=0.05%`/`DEFAULT_MAX_CLOSING_SLIPPAGE_P=1%` ### libraries/PairsStorageUtils.sol (update) * New `initializeGroupLiquidationParams` function: initializes group liquidation params for all existing groups * New `setGroupLiquidationParams` function: used to update a group's liquidation params (only affects trades opened after the change) * New `getGroupLiquidationParams` and `getPairLiquidationParams` getters ### libraries/PriceAggregatorUtils.sol (update) * `getPrice`: now accepts `_tradeId` argument instead of `_trader`, passes `trader`/`index`/`orderType` data to `linkRequest` ### libraries/PriceImpactUtils.sol (update) * `MAX_WINDOWS_DURATION` lowered from 30 days to 10 minutes, `MIN_WINDOWS_DURATION` lowered from 10 minutes to 1 minute * New `initializePairFactors` function that initializes pairs factors * New `setProtectionCloseFactors` to set the protection close factors for a set of pairs * New `setProtectionCloseFactorBlocks` to set the protection close factor duration in blocks for a set of pairs * New `setCumulativeFactors` to set the cumulative factors for a set of pairs * `addPriceImpactOpenInterest`: Removed partials logic that moved previous trade OI to current window if not expired, changed logic to decide if adds to long or short part of window (opening a long / closing a short adds to long window, opening a short / closing a long adds to short window), removed `lastWindowOiUsd` update (deprecated) * Removed `removePriceImpactOpenInterest` and `getTradeLastWindowOiUsd` * `getTradePriceImpact`: new `_isPnlPositive`/`_open`/`_lastPosIncreaseBlock`/`_contractsVersion` arguments, now loads `pairFactors` for pair, uses opposite side depth when `_open = false`, uses opposite side price impact OI when `_open = false`, passes `_open`, `protectionCloseFactor` (only when `_isPnlPositive` is true, `_open` is false, `protectionCloseFactor` isn't zero, and protection close factor didn't expire, otherwise passes `1e10`), `cumulativeFactor` (when not zero, otherwise passes `1e10`), and `_contractsVersion` to `_getTradePriceImpact` * Removed `getTradePriceImpactInfo` (deprecated) * New `getPairFactors` getter * `_getTradePriceImpact`: new `_open`, `_protectionCloseFactor`, `_cumulativeFactor`, `_contractsVersion` arguments, returns early 0 price impact if trade opened before v9.2 and `_open = false` (no closing price impact for trades opened before v9.2 since they paid it fully on open), multiplies `_startOpenInterestUsd` by `_cumulativeFactor`, multiplies by `_protectionCloseFactor` instead of `1e10` in `priceImpactP` calculation and divides result by 2 if trade opened after v9.2 (charge half price impact if trade opened after v9.2 since they paid half on open already, for trades opened before v9.2 charges full opening price impact), sets `_long` to `!_long` if `_open` is false to invert the price impact direction on close ### libraries/TradingCallbacksUtils.sol (update) * `closeTradeMarketCallback`: use new `_getTradeInfo` getter, Add `TradingCommonUtils.getTradeClosingPriceImpact` call, added max slippage cancel reason check (uses default max slippage % if `tradeInfo.maxSlippageP` not set), use `priceAfterImpact` (= market price + closing spread and price impact) instead of `_a.price` to calculate `v.profitP`, emit `priceAfterImpact` and `priceImpactP` in event * `executeTriggerOpenOrderCallback`: moved all cancel reason and spread/price impact logic to `validateTriggerOpenOrderCallback` * `executeTriggerCloseOrderCallback`: moved all cancel reason and spread/price impact logic to `validateTriggerCloseOrderCallback`, emit `priceImpactP` in `LimitExecuted` event * `validateTriggerOpenOrderCallback`: new getter that contains the extracted cancel reason logic of `executeTriggerOpenOrderCallback` * `validateTriggerCloseOrderCallback`: new getter that contains the extracted cancel reason logic of `executeTriggerCloseOrderCallback`, for SLs and TPs (not liquidations) set `v.executionPrice` to `TradingCommonUtils.getTradeClosingPriceImpact` result to take into account closing spread and impact, added max slippage cancel reason check for everything but liquidations (uses default max slippage % if `tradeInfo.maxSlippageP` not set) * `_openTradePrep`: no logic change, just use new `TradingCommonUtils.getTradeOpeningPriceImpact` helper to calculate opening price impact * New `_getTradeInfo` getter ### libraries/TradingCommonUtils.sol (update) * `getMarketExecutionPrice`: new `_open`/`_contractsVersion` arguments, returns early with 0 spread if `_open = false` and `_contractsVersion = before v9.2`, divides spread by 2 if `_contractsVersion >= v9.2`, inverts spread direction when `_open` = false * `getTradeValuePure`: combined `_borrowingFeeCollateral` and `_closingFeeCollateral` into `_feesCollateral` to avoid stack too deep, added `_liqPnlThresholdP` argument, `collateralLiqThreshold` is now `uint256` and uses `_liqPnlThresholdP` instead of `ConstantsUtils.LIQ_THRESHOLD_P` and is adjusted for `1e10` precision, added `int256` conversion for `collateralLiqThreshold` in return statement * `getLiqPnlThresholdP`: new pure function that returns the corresponding liquidation PnL threshold percentage to use depending on a trade's liquidation params and leverage; uses new logic (linearly decreasing liq pnl threshold as leverage increases, capped between two values) * `getTradeLiquidationPrice`: pass the stored trade's liquidation params * `getTradeValueCollateral`: pass `borrowingFeesCollateral + _closingFeesCollateral` to `getTradeValuePure` instead of passing them separately, and also pass `getTradeLiqPnlThresholdP(_trade)` * `getTradeOpeningPriceImpact`: New view helper to calculate the price impact % and price after spread + price impact for trade openings / partial adds * `getTradeClosingPriceImpact`: New view helper that returns the closing price impact %, price after closing spread and impact, and net trade value used to determine whether net pnl is positive or not; returns early 0% price impact for trades opened before v9.2, otherwise calculates net trade value (taking into account pnl, spread, price impact, closing fees, and borrowing fees) without protection factor and compares it to the initial trade collateral to determine the `_isPnlPositive` value passed to `getTradePriceImpact` which determines the final returned `priceImpactP` and `priceAfterImpact` values * `getTradeLiqPnlThresholdP`: new getter that returns the value of `getLiqPnlThresholdP` by passing the trade's stored liquidation params and its leverage * `getTotalClosingFeesCollateral`: new getter that returns a trade's closing fee based on its `_collateralIndex`/`_pairIndex`/`_positionSizeCollateral`, used in `BorrowingFeesUtils.getTradeLiquidationPrice`/`TradingCommonUtils.getTradeClosingPriceImpact`/`DecreasePositionSizeUtils.validateRequest` * Renamed `addOiCollateral` to `updateOi`, now accepts `_open` argument and passes it to `handleTradeBorrowingCallback` and `addPriceImpactOpenInterest` * Renamed `addTradeOiCollateral` to `updateOiTrade`, now accepts `_open` argument and passes it to `updateOi` * Removed `removeOiCollateral` and `removeTradeOiCollateral` * `handleOiDelta` now uses `updateOi`, passes `_open = true` when `_newPositionSizeCollateral > existingPositionSizeCollateral` and `_open = false` when `_newPositionSizeCollateral < existingPositionSizeCollateral` ### libraries/TradingInteractionsUtils.sol (update) * New `updateMaxClosingSlippageP` function that simply calls `GNSTradingStorage.updateTradeMaxClosingSlippageP` * `closeTradeMarket`: now accepts `_expectedPrice`, reverts if `_expectedPrice` is 0, sets `pendingOrder.trade.openPrice` to `_expectedPrice`, passes trade id to `getPrice` * `decreasePositionSize`: now accepts `_expectedPrice`, passes it to `requestDecreasePositionSize` * `triggerOrder`: no longer turn LIQ orders into SL orders when SL is closer, uses `TradingCommonUtils.getTradeOpeningPriceImpact` to calculate `priceImpactP` * `_openTrade`: uses `TradingCommonUtils.getTradeOpeningPriceImpact` to calculate `priceImpactP`, passes trade id to `getPrice` * `_getPriceTriggerOrder`: passes trade id to `getPrice` ### libraries/TradingStorageUtils.sol (update) * `storeTrade`: Fetches the corresponding pair's liquidation params and stores them into the new `tradeLiquidationParams` mapping, limits the trade SL distance using the new `_limitTradeSlDistance` helper, sets `_tradeInfo.contractsVersion` to the current version using `getCurrentContractsVersion()`, sets `_tradeInfo.lastPosIncreaseBlock` to current block, no longer sets `_tradeInfo.lastOiUpdateTs = 0` because corresponding logic was deprecated, calls `updateOiTrade` with `_open = true` instead of `addTradeOiCollateral`, emits the trade's liquidation params * New `updateTradeMaxClosingSlippageP` setter * `updateTradePosition`/`updateOpenOrderDetails`/`updateTradeSl`: limit the trade's SL distance using the new `_limitTradeSlDistance` helper instead of `_limitSlDistance` * `updateTradePosition`: new `_isPartialIncrease` argument, sets the trade's stored liquidation params to the current pair liquidation params when `_isPartialIncrease = true` and sets `i.lastPosIncreaseBlock` to current block, emits `_isPartialIncrease` in `TradePositionUpdated` event * `closeTrade`: calls `updateOiTrade` with `_open = false` instead of `removeTradeOiCollateral` * `getTradeLiquidationParams`: new getter to return the new `tradeLiquidationParams` mapping values * `getCurrentContractsVersion`: new getter to return the current contracts version (will need to be updated at each significant update) * `_limitSlDistance`: accepts new `_liqPnlThresholdP` argument, calculates `minSlP` as `_liqPnlThresholdP - ConstantsUtils.SL_LIQ_BUFFER_P`, uses calculated `minSlP` instead of `ConstantsUtils.MAX_SL_P`, adjustments done for `1e10` precision of `minSlP` * `_limitTradeSlDistance`: new view wrapper accepting `_trade` and `_newSl` arguments; returns a trade's capped SL distance based on its open price, leverage, new stop loss value, whether it's a long or a short, and based on its liquidation pnl % threshold fetched using `TradingCommonUtils.getTradeLiqPnlThresholdP(_trade)` ### libraries/updateLeverage/UpdateLeverageLifecycles.sol (update) * `_initiateRequest`: small adjustment to avoid stack too deep, now passes trade id to `getPrice` * `_prepareCallbackValues`: pass stored trade liquidation params in `values.liqPrice` calculation * `_handleCallback`: pass `_isPartialIncrease = false` to `updateTradePosition` ### libraries/updatePositionSize/DecreasePositionSizeUtils.sol (update) * `validateRequest`: calculate `closingFeesCollateral` using new `TradingCommonUtils.getTotalClosingFeesCollateral` helper, revert if `input.expectedPrice` is 0 * `prepareCallbackValues`: added `values.priceAfterImpact` calculation using new `TradingCommonUtils.getTradeClosingPriceImpact` helper, `values.existingPnlCollateral` now uses `uint64(values.priceAfterImpact)` instead of `_answer.price` * `validateCallback`: now accepts `_pendingOrder` (to fetch expected price), added max slippage calculations and corresponding cancel reason check (uses default max slippage % if `tradeInfo.maxSlippageP` not set) * `updateTradeSuccess`: pass `_isPartialIncrease = false` to `updateTradePosition` ### libraries/updatePositionSize/IncreasePositionSizeUtils.sol (update) * `prepareCallbackValues`: Uses `TradingCommonUtils.getTradeOpeningPriceImpact` to calculate `values.priceAfterImpact`, passes current pair liquidation params to `getTradeLiquidationPrice` for `values.newLiqPrice` calculation (already checks using new liquidation params since trade liquidation params will be refreshed on success callback) * `updateTradeSuccess`: pass `_isPartialIncrease = true` to `updateTradePosition` ### libraries/updatePositionSize/UpdatePositionSizeLifecycles.sol (update) * `requestDecreasePositionSize`: passes `_input.expectedPrice` to `_initiateRequest` * `_initiateRequest`: passes trade id to `getPrice` * `executeIncreasePositionSizeMarket`/`executeDecreasePositionSizeMarket`: pass trade long and current collateral/usd price to event * `executeDecreasePositionSizeMarket`: pass `_order` to `DecreasePositionSizeUtils.validateCallback` # GNSAddressStore Source: https://docs.gains.trade/developer/technical-reference/contracts/core/abstract/gnsaddressstore *Proxy base for the diamond and its facet contracts to store addresses and manage access control* ## initialize ```solidity theme={null} function initialize(address _rolesManager) external ``` *Initializes address store facet* ### Parameters | Name | Type | Description | | -------------- | ------- | --------------------- | | \_rolesManager | address | roles manager address | ## getAddresses ```solidity theme={null} function getAddresses() external view returns (struct IAddressStore.Addresses) ``` *Returns addresses current values* ## hasRole ```solidity theme={null} function hasRole(address _account, enum IAddressStore.Role _role) public view returns (bool) ``` *Returns whether an account has been granted a particular role* ### Parameters | Name | Type | Description | | --------- | ----------------------- | ------------------------ | | \_account | address | account address to check | | \_role | enum IAddressStore.Role | role to check | ## \_setRole ```solidity theme={null} function _setRole(address _account, enum IAddressStore.Role _role, bool _value) internal ``` *Update role for account* ### Parameters | Name | Type | Description | | --------- | ----------------------- | ----------------------------- | | \_account | address | account to update | | \_role | enum IAddressStore.Role | role to set | | \_value | bool | true if allowed, false if not | ## setRoles ```solidity theme={null} function setRoles(address[] _accounts, enum IAddressStore.Role[] _roles, bool[] _values) external ``` *Updates access control for a list of accounts* ### Parameters | Name | Type | Description | | ---------- | -------------------------- | ------------------------------- | | \_accounts | address\[] | accounts addresses to update | | \_roles | enum IAddressStore.Role\[] | corresponding roles to update | | \_values | bool\[] | corresponding new values to set | ## \_enforceRole ```solidity theme={null} function _enforceRole(enum IAddressStore.Role _role) internal view ``` *Reverts if caller does not have role* ### Parameters | Name | Type | Description | | ------ | ----------------------- | --------------- | | \_role | enum IAddressStore.Role | role to enforce | ## onlyRole ```solidity theme={null} modifier onlyRole(enum IAddressStore.Role _role) ``` *Reverts if caller does not have role* ## onlySelf ```solidity theme={null} modifier onlySelf() ``` *Reverts if caller isn't this same contract (facets calling other facets)* # GNSDiamondCut Source: https://docs.gains.trade/developer/technical-reference/contracts/core/abstract/gnsdiamondcut *Based on EIP-2535: Diamonds (*[*https://eips.ethereum.org/EIPS/eip-2535*](https://eips.ethereum.org/EIPS/eip-2535)*) Follows diamond-3 implementation (*[*https://github.com/mudgen/diamond-3-hardhat/*](https://github.com/mudgen/diamond-3-hardhat/)*) Manages all actions (calls, updates and initializations) related to the diamond and its facets.* ## fallback ```solidity theme={null} fallback() external payable ``` *Forwards call to the right facet using msg.sig using delegatecall. Reverts if signature is not known.* ## receive ```solidity theme={null} receive() external payable ``` *Allows the contract to receive ether* ## diamondCut ```solidity theme={null} function diamondCut(struct IDiamondStorage.FacetCut[] _faceCut, address _init, bytes _calldata) external ``` Add/replace/remove any number of functions and optionally execute a function with delegatecall ### Parameters | Name | Type | Description | | ---------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | | \_faceCut | [IDiamondStorage.FacetCut\[\]](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#facetcut) | | | \_init | address | The address of the contract or facet to execute \_calldata | | \_calldata | bytes | A function call, including function selector and arguments \_calldata is executed with delegatecall on \_init | ## \_diamondCut ```solidity theme={null} function _diamondCut(struct IDiamondStorage.FacetCut[] _facetCut, address _init, bytes _calldata) internal ``` *Internal function for diamondCut()* ## \_addFunctions ```solidity theme={null} function _addFunctions(address _facetAddress, bytes4[] _functionSelectors) internal ``` *Adds the facet if it wasn't added yet, and adds its functions to the diamond* ### Parameters | Name | Type | Description | | ------------------- | --------- | ----------------------------- | | \_facetAddress | address | address of the facet contract | | \_functionSelectors | bytes4\[] | array of function selectors | ## \_replaceFunctions ```solidity theme={null} function _replaceFunctions(address _facetAddress, bytes4[] _functionSelectors) internal ``` *Updates facet contract address for given function selectors* ### Parameters | Name | Type | Description | | ------------------- | --------- | ----------------------------- | | \_facetAddress | address | address of the facet contract | | \_functionSelectors | bytes4\[] | array of function selectors | ## \_removeFunctions ```solidity theme={null} function _removeFunctions(address _facetAddress, bytes4[] _functionSelectors) internal ``` *Removes some function selectors of a facet from diamond* ### Parameters | Name | Type | Description | | ------------------- | --------- | ----------------------------- | | \_facetAddress | address | address of the facet contract | | \_functionSelectors | bytes4\[] | array of function selectors | ## \_addFacet ```solidity theme={null} function _addFacet(struct IDiamondStorage.DiamondStorage s, address _facetAddress) internal ``` *Adds a new facet contract address to the diamond* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | | s | [IDiamondStorage.DiamondStorage](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#diamondstorage) | diamond storage pointer | | \_facetAddress | address | address of the new facet contract | ## \_addFunction ```solidity theme={null} function _addFunction(struct IDiamondStorage.DiamondStorage s, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal ``` *Adds a new function to the diamond for a given facet contract* ### Parameters | Name | Type | Description | | ------------------ | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | s | [IDiamondStorage.DiamondStorage](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#diamondstorage) | diamond storage pointer | | \_selector | bytes4 | function selector | | \_selectorPosition | uint96 | position of the function selector in the facet selectors array | | \_facetAddress | address | address of the facet contract | ## \_removeFunction ```solidity theme={null} function _removeFunction(struct IDiamondStorage.DiamondStorage s, address _facetAddress, bytes4 _selector) internal ``` *Removes a function from a facet of the diamond* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | s | [IDiamondStorage.DiamondStorage](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#diamondstorage) | diamond storage pointer | | \_facetAddress | address | address of the facet contract | | \_selector | bytes4 | function selector | ## \_initializeDiamondCut ```solidity theme={null} function _initializeDiamondCut(address _init, bytes _calldata) internal ``` *Initializes a facet after updating the diamond using delegatecall* ### Parameters | Name | Type | Description | | ---------- | ------- | --------------------------------------------- | | \_init | address | address of the contract to execute \_calldata | | \_calldata | bytes | function call (selector and arguments) | ## \_enforceHasContractCode ```solidity theme={null} function _enforceHasContractCode(address _contract) internal view ``` *Reverts if the given address is not a contract* ### Parameters | Name | Type | Description | | ---------- | ------- | ---------------- | | \_contract | address | address to check | # GNSDiamondLoupe Source: https://docs.gains.trade/developer/technical-reference/contracts/core/abstract/gnsdiamondloupe *Based on EIP-2535: Diamonds ([https://eips.ethereum.org/EIPS/eip-2535](https://eips.ethereum.org/EIPS/eip-2535)) Follows diamond-3 implementation ([https://github.com/mudgen/diamond-3-hardhat/](https://github.com/mudgen/diamond-3-hardhat/)) Returns useful information about the diamond and its facets.* ## facets ```solidity theme={null} function facets() external view returns (struct IGNSDiamondLoupe.Facet[] facets_) ``` Gets all facets and their selectors. ### Return Values | Name | Type | Description | | -------- | -------------------------------------------------------------------------------------------------------- | ----------- | | facets\_ | [IGNSDiamondLoupe.Facet\[\]](/developer/technical-reference/contracts/interfaces/ignsdiamondloupe#facet) | Facet | ## facetFunctionSelectors ```solidity theme={null} function facetFunctionSelectors(address _facet) external view returns (bytes4[] facetFunctionSelectors_) ``` Gets all the function selectors provided by a facet. ### Parameters | Name | Type | Description | | ------- | ------- | ------------------ | | \_facet | address | The facet address. | ### Return Values | Name | Type | Description | | ------------------------ | --------- | ----------------------- | | facetFunctionSelectors\_ | bytes4\[] | the function selectors. | ## facetAddresses ```solidity theme={null} function facetAddresses() external view returns (address[] facetAddresses_) ``` Get all the facet addresses used by a diamond. ### Return Values | Name | Type | Description | | ---------------- | ---------- | ------------------- | | facetAddresses\_ | address\[] | the facet addresses | ## facetAddress ```solidity theme={null} function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_) ``` Gets the facet that supports the given selector. *If facet is not found return address(0).* ### Parameters | Name | Type | Description | | ------------------ | ------ | ---------------------- | | \_functionSelector | bytes4 | The function selector. | ### Return Values | Name | Type | Description | | -------------- | ------- | ------------------ | | facetAddress\_ | address | The facet address. | # GNSDiamondStorage Source: https://docs.gains.trade/developer/technical-reference/contracts/core/abstract/gnsdiamondstorage *Sets storage slot layout for diamond facets.* # GNSBorrowingFees Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnsborrowingfees *Facet #9: Borrowing Fees and open interests* ## constructor ```solidity theme={null} constructor() public ``` ## setBorrowingPairParams ```solidity theme={null} function setBorrowingPairParams(uint8 _collateralIndex, uint16 _pairIndex, struct IBorrowingFees.BorrowingPairParams _value) external ``` *Updates borrowing pair params of a pair* ### Parameters | Name | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_value | [IBorrowingFees.BorrowingPairParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new value | ## setBorrowingPairParamsArray ```solidity theme={null} function setBorrowingPairParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingPairParams[] _values) external ``` *Updates borrowing pair params of multiple pairs* ### Parameters | Name | Type | Description | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_indices | uint16\[] | indices of the pairs | | \_values | [IBorrowingFees.BorrowingPairParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new values | ## setBorrowingGroupParams ```solidity theme={null} function setBorrowingGroupParams(uint8 _collateralIndex, uint16 _groupIndex, struct IBorrowingFees.BorrowingGroupParams _value) external ``` *Updates borrowing group params of a group* ### Parameters | Name | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_value | [IBorrowingFees.BorrowingGroupParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new value | ## setBorrowingGroupParamsArray ```solidity theme={null} function setBorrowingGroupParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingGroupParams[] _values) external ``` *Updates borrowing group params of multiple groups* ### Parameters | Name | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_indices | uint16\[] | indices of the groups | | \_values | [IBorrowingFees.BorrowingGroupParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new values | ## handleTradeBorrowingCallback ```solidity theme={null} function handleTradeBorrowingCallback(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, uint256 _positionSizeCollateral, bool _open, bool _long) external virtual ``` *Callback after a trade is opened/closed to store pending borrowing fees and adjust open interests* ### Parameters | Name | Type | Description | | ------------------------ | ------- | ------------------------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_trader | address | address of the trader | | \_pairIndex | uint16 | index of the pair | | \_index | uint32 | index of the trade | | \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens | | \_open | bool | true if trade has been opened, false if trade has been closed | | \_long | bool | true if trade is long, false if trade is short | ## resetTradeBorrowingFees ```solidity theme={null} function resetTradeBorrowingFees(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, bool _long) external virtual ``` *Resets a trade borrowing fee to 0 (useful when new trade opened or when partial trade executed)* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_trader | address | address of the trader | | \_pairIndex | uint16 | index of the pair | | \_index | uint32 | index of the trade | | \_long | bool | true if trade is long, false if trade is short | ## getBorrowingPairPendingAccFees ```solidity theme={null} function getBorrowingPairPendingAccFees(uint8 _collateralIndex, uint16 _pairIndex, uint256 _currentBlock) public view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 pairAccFeeDelta) ``` *Returns the pending acc borrowing fees for a pair on both sides* ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_currentBlock | uint256 | current block number | ### Return Values | Name | Type | Description | | --------------- | ------ | ---------------------------------------------------- | | accFeeLong | uint64 | new pair acc borrowing fee on long side | | accFeeShort | uint64 | new pair acc borrowing fee on short side | | pairAccFeeDelta | uint64 | pair acc borrowing fee delta (for side that changed) | ## getBorrowingGroupPendingAccFees ```solidity theme={null} function getBorrowingGroupPendingAccFees(uint8 _collateralIndex, uint16 _groupIndex, uint256 _currentBlock) public view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 groupAccFeeDelta) ``` *Returns the pending acc borrowing fees for a borrowing group on both sides* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_currentBlock | uint256 | current block number | ### Return Values | Name | Type | Description | | ---------------- | ------ | ----------------------------------------------------- | | accFeeLong | uint64 | new group acc borrowing fee on long side | | accFeeShort | uint64 | new group acc borrowing fee on short side | | groupAccFeeDelta | uint64 | group acc borrowing fee delta (for side that changed) | ## getTradeBorrowingFee ```solidity theme={null} function getTradeBorrowingFee(struct IBorrowingFees.BorrowingFeeInput _input) public view returns (uint256 feeAmountCollateral) ``` *Returns the borrowing fee for a trade* ### Parameters | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | \_input | [IBorrowingFees.BorrowingFeeInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingfeeinput) | input data (collateralIndex, trader, pairIndex, index, long, collateral, leverage) | ### Return Values | Name | Type | Description | | ------------------- | ------- | ------------------------------------ | | feeAmountCollateral | uint256 | borrowing fee (collateral precision) | ## getTradeLiquidationPrice ```solidity theme={null} function getTradeLiquidationPrice(struct IBorrowingFees.LiqPriceInput _input) external view returns (uint256) ``` *Returns the liquidation price for a trade* ### Parameters | Name | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | \_input | [IBorrowingFees.LiqPriceInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#liqpriceinput) | input data (collateralIndex, trader, pairIndex, index, openPrice, long, collateral, leverage) | ## getPairOisCollateral ```solidity theme={null} function getPairOisCollateral(uint8 _collateralIndex, uint16 _pairIndex) public view returns (uint256 longOi, uint256 shortOi) ``` *Returns the open interests for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ### Return Values | Name | Type | Description | | ------- | ------- | --------------------------- | | longOi | uint256 | open interest on long side | | shortOi | uint256 | open interest on short side | ## getBorrowingPairGroupIndex ```solidity theme={null} function getBorrowingPairGroupIndex(uint8 _collateralIndex, uint16 _pairIndex) public view returns (uint16 groupIndex) ``` *Returns the borrowing group index for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ### Return Values | Name | Type | Description | | ---------- | ------ | --------------------- | | groupIndex | uint16 | borrowing group index | ## getPairOiCollateral ```solidity theme={null} function getPairOiCollateral(uint8 _collateralIndex, uint16 _pairIndex, bool _long) external view returns (uint256) ``` *Returns the open interest in collateral tokens for a pair on one side* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_long | bool | true if long side | ## withinMaxBorrowingGroupOi ```solidity theme={null} function withinMaxBorrowingGroupOi(uint8 _collateralIndex, uint16 _pairIndex, bool _long, uint256 _positionSizeCollateral) external view returns (bool) ``` *Returns whether a trade is within the max group borrowing open interest* ### Parameters | Name | Type | Description | | ------------------------ | ------- | ----------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_long | bool | true if long side | | \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens | ## getBorrowingGroup ```solidity theme={null} function getBorrowingGroup(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.BorrowingData) ``` *Returns a borrowing group's data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | ## getBorrowingGroupOi ```solidity theme={null} function getBorrowingGroupOi(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.OpenInterest) ``` *Returns a borrowing group's oi data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | ## getBorrowingPair ```solidity theme={null} function getBorrowingPair(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingData) ``` *Returns a borrowing pair's data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getBorrowingPairOi ```solidity theme={null} function getBorrowingPairOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.OpenInterest) ``` *Returns a borrowing pair's oi data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getBorrowingPairGroups ```solidity theme={null} function getBorrowingPairGroups(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingPairGroup[]) ``` *Returns a borrowing pair's oi data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getAllBorrowingPairs ```solidity theme={null} function getAllBorrowingPairs(uint8 _collateralIndex) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[], struct IBorrowingFees.BorrowingPairGroup[][]) ``` *Returns all borrowing pairs' borrowing data, oi data, and pair groups data* ### Parameters | Name | Type | Description | | ----------------- | ----- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | ## getBorrowingGroups ```solidity theme={null} function getBorrowingGroups(uint8 _collateralIndex, uint16[] _indices) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[]) ``` *Returns borrowing groups' data and oi data* ### Parameters | Name | Type | Description | | ----------------- | --------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_indices | uint16\[] | indices of the groups | ## getBorrowingInitialAccFees ```solidity theme={null} function getBorrowingInitialAccFees(uint8 _collateralIndex, address _trader, uint32 _index) external view returns (struct IBorrowingFees.BorrowingInitialAccFees) ``` *Returns borrowing groups' data* ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_trader | address | address of trader | | \_index | uint32 | index of trade | ## getPairMaxOi ```solidity theme={null} function getPairMaxOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256) ``` *Returns the max open interest for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getPairMaxOiCollateral ```solidity theme={null} function getPairMaxOiCollateral(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256) ``` *Returns the max open interest in collateral tokens for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | # GNSFeeTiers Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnsfeetiers *Facet #3: Fee tiers* ## constructor ```solidity theme={null} constructor() public ``` ## initializeFeeTiers ```solidity theme={null} function initializeFeeTiers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers, uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) external ``` ### Parameters | Name | Type | Description | | ------------------------ | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | \_groupIndices | uint256\[] | group indices (pairs storage fee index) to initialize | | \_groupVolumeMultipliers | uint256\[] | corresponding group volume multipliers (1e3) | | \_feeTiersIndices | uint256\[] | fee tiers indices to initialize | | \_feeTiers | [IFeeTiers.FeeTier\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | fee tiers values to initialize (feeMultiplier, pointsThreshold) | ## setGroupVolumeMultipliers ```solidity theme={null} function setGroupVolumeMultipliers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers) external ``` *Updates groups volume multipliers* ### Parameters | Name | Type | Description | | ------------------------ | ---------- | ------------------------------------------ | | \_groupIndices | uint256\[] | indices of groups to update | | \_groupVolumeMultipliers | uint256\[] | corresponding new volume multipliers (1e3) | ## setFeeTiers ```solidity theme={null} function setFeeTiers(uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) external ``` *Updates fee tiers* ### Parameters | Name | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | \_feeTiersIndices | uint256\[] | indices of fee tiers to update | | \_feeTiers | [IFeeTiers.FeeTier\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | new fee tiers values (feeMultiplier, pointsThreshold) | ## setTradersFeeTiersEnrollment ```solidity theme={null} function setTradersFeeTiersEnrollment(address[] _traders, struct IFeeTiers.TraderEnrollment[] _values) external ``` *Updates traders enrollment status in fee tiers* ### Parameters | Name | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------- | | \_traders | address\[] | group of traders | | \_values | [IFeeTiers.TraderEnrollment\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#traderenrollment) | corresponding enrollment values | ## addTradersUnclaimedPoints ```solidity theme={null} function addTradersUnclaimedPoints(address[] _traders, enum IFeeTiers.CreditType[] _creditTypes, uint224[] _points) external ``` *Credits points to traders* ### Parameters | Name | Type | Description | | ------------- | ---------------------------- | -------------------------------------- | | \_traders | address\[] | traders addresses | | \_creditTypes | enum IFeeTiers.CreditType\[] | types of credit (IMMEDIATE, CLAIMABLE) | | \_points | uint224\[] | points to credit (1e18) | ## updateTraderPoints ```solidity theme={null} function updateTraderPoints(address _trader, uint256 _volumeUsd, uint256 _pairIndex) external virtual ``` *Increases daily points from a new trade, re-calculate trailing points, and cache daily fee tier for a trader.* ### Parameters | Name | Type | Description | | ----------- | ------- | ---------------------------- | | \_trader | address | trader address | | \_volumeUsd | uint256 | trading volume in USD (1e18) | | \_pairIndex | uint256 | pair index | ## calculateFeeAmount ```solidity theme={null} function calculateFeeAmount(address _trader, uint256 _normalFeeAmountCollateral) external view returns (uint256) ``` *Returns fee amount after applying the trader's active fee tier multiplier* ### Parameters | Name | Type | Description | | --------------------------- | ------- | -------------------------------------- | | \_trader | address | address of trader | | \_normalFeeAmountCollateral | uint256 | base fee amount (collateral precision) | ## getFeeTiersCount ```solidity theme={null} function getFeeTiersCount() external view returns (uint256) ``` Returns the current number of active fee tiers ## getFeeTier ```solidity theme={null} function getFeeTier(uint256 _feeTierIndex) external view returns (struct IFeeTiers.FeeTier) ``` *Returns a fee tier's details (feeMultiplier, pointsThreshold)* ### Parameters | Name | Type | Description | | -------------- | ------- | -------------- | | \_feeTierIndex | uint256 | fee tier index | ## getGroupVolumeMultiplier ```solidity theme={null} function getGroupVolumeMultiplier(uint256 _groupIndex) external view returns (uint256) ``` *Returns a group's volume multiplier* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------------------- | | \_groupIndex | uint256 | group index (pairs storage fee index) | ## getFeeTiersTraderInfo ```solidity theme={null} function getFeeTiersTraderInfo(address _trader) external view returns (struct IFeeTiers.TraderInfo) ``` *Returns a trader's info (lastDayUpdated, trailingPoints)* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | ## getFeeTiersTraderDailyInfo ```solidity theme={null} function getFeeTiersTraderDailyInfo(address _trader, uint32 _day) external view returns (struct IFeeTiers.TraderDailyInfo) ``` *Returns a trader's daily fee tier info (feeMultiplierCache, points)* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | | \_day | uint32 | day | ## getTraderFeeTiersEnrollment ```solidity theme={null} function getTraderFeeTiersEnrollment(address _trader) external view returns (struct IFeeTiers.TraderEnrollment) ``` *Returns a trader's fee tiers enrollment status* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | ## getTraderUnclaimedPoints ```solidity theme={null} function getTraderUnclaimedPoints(address _trader) external view returns (uint224) ``` *Returns a trader's unclaimed points, credited by Governance* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | # GNSOtc Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnsotc *Facet #11: OTC (Handles buy backs and distribution)* ## constructor ```solidity theme={null} constructor() public ``` ## initializeOtc ```solidity theme={null} function initializeOtc(struct IOtc.OtcConfig _config) external ``` *Initializer for OTC facet* ### Parameters | Name | Type | Description | | -------- | ------------------------------------------------------------------------------------------ | -------------- | | \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config | ## updateOtcConfig ```solidity theme={null} function updateOtcConfig(struct IOtc.OtcConfig _config) external ``` *Updates OTC config* ### Parameters | Name | Type | Description | | -------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | | \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config. Sum of `treasuryShareP`, `stakingShareP`, `burnShareP` must equal 100 and `premiumP` must be less than or equal to MAX\_PREMIUM\_P | ## addOtcCollateralBalance ```solidity theme={null} function addOtcCollateralBalance(uint8 _collateralIndex, uint256 _collateralAmount) external virtual ``` *Increases OTC balance for a collateral* ### Parameters | Name | Type | Description | | ------------------ | ------- | ------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_collateralAmount | uint256 | amount of collateral to increase (collateral precision) | ## sellGnsForCollateral ```solidity theme={null} function sellGnsForCollateral(uint8 _collateralIndex, uint256 _collateralAmount) external ``` *OTC Buys GNS from caller for `_amountCollateral` of `_collateralIndex`* ### Parameters | Name | Type | Description | | ------------------ | ------- | ---------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_collateralAmount | uint256 | amount of collateral to trade (collateral precision) | ## getOtcConfig ```solidity theme={null} function getOtcConfig() external view returns (struct IOtc.OtcConfig) ``` *Returns OTC Config* ## getOtcBalance ```solidity theme={null} function getOtcBalance(uint8 _collateralIndex) external view returns (uint256) ``` *Returns OTC balance for a collateral (collateral precision)* ### Parameters | Name | Type | Description | | ----------------- | ----- | ---------------- | | \_collateralIndex | uint8 | collateral index | ## getOtcRate ```solidity theme={null} function getOtcRate(uint8 _collateralIndex) external view returns (uint256) ``` *Returns OTC rate (price + premium) of GNS in collateral (1e10)* ### Parameters | Name | Type | Description | | ----------------- | ----- | ---------------- | | \_collateralIndex | uint8 | collateral index | # GNSPairsStorage Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnspairsstorage *Facet #1: Pairs storage* ## constructor ```solidity theme={null} constructor() public ``` ## initializeGroupLiquidationParams ```solidity theme={null} function initializeGroupLiquidationParams(struct IPairsStorage.GroupLiquidationParams[] _groupLiquidationParams) external ``` *Initializes liquidation params for all existing groups* ### Parameters | Name | Type | Description | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | \_groupLiquidationParams | [IPairsStorage.GroupLiquidationParams\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | liquidation params for each group (index corresponds to group index) | ## initializeNewFees ```solidity theme={null} function initializeNewFees(struct IPairsStorage.GlobalTradeFeeParams _tradeFeeParams) external ``` *Copies all existing fee groups to new mapping, multiplies existing groups min/max lev by 1e3, initializes new global trade fee params* ### Parameters | Name | Type | Description | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_tradeFeeParams | [IPairsStorage.GlobalTradeFeeParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#globaltradefeeparams) | global trade fee params | ## addPairs ```solidity theme={null} function addPairs(struct IPairsStorage.Pair[] _pairs) external ``` *Adds new trading pairs* ### Parameters | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------ | ------------ | | \_pairs | [IPairsStorage.Pair\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | pairs to add | ## updatePairs ```solidity theme={null} function updatePairs(uint256[] _pairIndices, struct IPairsStorage.Pair[] _pairs) external ``` *Updates trading pairs* ### Parameters | Name | Type | Description | | ------------- | ------------------------------------------------------------------------------------------------------ | ---------------- | | \_pairIndices | uint256\[] | indices of pairs | | \_pairs | [IPairsStorage.Pair\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | new pairs values | ## addGroups ```solidity theme={null} function addGroups(struct IPairsStorage.Group[] _groups) external ``` *Adds new pair groups* ### Parameters | Name | Type | Description | | -------- | -------------------------------------------------------------------------------------------------------- | ------------- | | \_groups | [IPairsStorage.Group\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | groups to add | ## updateGroups ```solidity theme={null} function updateGroups(uint256[] _ids, struct IPairsStorage.Group[] _groups) external ``` *Updates pair groups* ### Parameters | Name | Type | Description | | -------- | -------------------------------------------------------------------------------------------------------- | ----------------- | | \_ids | uint256\[] | indices of groups | | \_groups | [IPairsStorage.Group\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | new groups values | ## addFees ```solidity theme={null} function addFees(struct IPairsStorage.FeeGroup[] _fees) external ``` *Adds new pair fees groups* ### Parameters | Name | Type | Description | | ------ | -------------------------------------------------------------------------------------------------------------- | ----------- | | \_fees | [IPairsStorage.FeeGroup\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | fees to add | ## updateFees ```solidity theme={null} function updateFees(uint256[] _ids, struct IPairsStorage.FeeGroup[] _fees) external ``` *Updates pair fees groups* ### Parameters | Name | Type | Description | | ------ | -------------------------------------------------------------------------------------------------------------- | --------------- | | \_ids | uint256\[] | indices of fees | | \_fees | [IPairsStorage.FeeGroup\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | new fees values | ## setGroupLiquidationParams ```solidity theme={null} function setGroupLiquidationParams(uint256 _groupIndex, struct IPairsStorage.GroupLiquidationParams _params) external ``` *Updates group liquidation params (will only apply for trades opened after the change)* ### Parameters | Name | Type | Description | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | | \_groupIndex | uint256 | index of group | | \_params | [IPairsStorage.GroupLiquidationParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | new liquidation params | ## setGlobalTradeFeeParams ```solidity theme={null} function setGlobalTradeFeeParams(struct IPairsStorage.GlobalTradeFeeParams _feeParams) external ``` *Updates global trade fee params* ### Parameters | Name | Type | Description | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------- | -------------- | | \_feeParams | [IPairsStorage.GlobalTradeFeeParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#globaltradefeeparams) | new fee params | ## setPairCustomMaxLeverages ```solidity theme={null} function setPairCustomMaxLeverages(uint256[] _indices, uint256[] _values) external ``` *Updates pair custom max leverages (if unset group default is used); useful to delist a pair if new value is below the pair's group minLeverage* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------------------------------- | | \_indices | uint256\[] | indices of pairs | | \_values | uint256\[] | new custom max leverages (1e3 precision) | ## pairJob ```solidity theme={null} function pairJob(uint256 _pairIndex) external view returns (string, string) ``` *Returns data needed by price aggregator when doing a new price request* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ### Return Values | Name | Type | Description | | ---- | ------ | ----------- | | \[0] | string | | | \[1] | string | | ## isPairListed ```solidity theme={null} function isPairListed(string _from, string _to) external view returns (bool) ``` *Returns whether a pair is listed* ### Parameters | Name | Type | Description | | ------ | ------ | ------------------- | | \_from | string | pair from (eg. BTC) | | \_to | string | pair to (eg. USD) | ## isPairIndexListed ```solidity theme={null} function isPairIndexListed(uint256 _pairIndex) external view returns (bool) ``` *Returns whether a pair index is listed* ### Parameters | Name | Type | Description | | ----------- | ------- | ---------------------- | | \_pairIndex | uint256 | index of pair to check | ## pairs ```solidity theme={null} function pairs(uint256 _index) external view returns (struct IPairsStorage.Pair) ``` *Returns a pair's details* ### Parameters | Name | Type | Description | | ------- | ------- | ------------- | | \_index | uint256 | index of pair | ## pairsCount ```solidity theme={null} function pairsCount() external view returns (uint256) ``` *Returns number of listed pairs* ## pairSpreadP ```solidity theme={null} function pairSpreadP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's spread % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairMinLeverage ```solidity theme={null} function pairMinLeverage(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's min leverage (1e3 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairTotalPositionSizeFeeP ```solidity theme={null} function pairTotalPositionSizeFeeP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's total position size fee % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairTotalLiqCollateralFeeP ```solidity theme={null} function pairTotalLiqCollateralFeeP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's total liquidation collateral fee % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairOraclePositionSizeFeeP ```solidity theme={null} function pairOraclePositionSizeFeeP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's oracle position size fee % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairMinPositionSizeUsd ```solidity theme={null} function pairMinPositionSizeUsd(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's min position size in USD (1e18 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## getGlobalTradeFeeParams ```solidity theme={null} function getGlobalTradeFeeParams() external view returns (struct IPairsStorage.GlobalTradeFeeParams) ``` *Returns global trade fee params* ## pairMinFeeUsd ```solidity theme={null} function pairMinFeeUsd(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's minimum trading fee in USD (1e18 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## groups ```solidity theme={null} function groups(uint256 _index) external view returns (struct IPairsStorage.Group) ``` *Returns a group details* ### Parameters | Name | Type | Description | | ------- | ------- | -------------- | | \_index | uint256 | index of group | ## groupsCount ```solidity theme={null} function groupsCount() external view returns (uint256) ``` *Returns number of listed groups* ## fees ```solidity theme={null} function fees(uint256 _index) external view returns (struct IPairsStorage.FeeGroup) ``` *Returns a fee group details* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------ | | \_index | uint256 | index of fee group | ## feesCount ```solidity theme={null} function feesCount() external view returns (uint256) ``` *Returns number of listed fee groups* ## pairMaxLeverage ```solidity theme={null} function pairMaxLeverage(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's active max leverage; custom if set, otherwise group default (1e3 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairCustomMaxLeverage ```solidity theme={null} function pairCustomMaxLeverage(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's custom max leverage; 0 if not set (1e3 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## getAllPairsRestrictedMaxLeverage ```solidity theme={null} function getAllPairsRestrictedMaxLeverage() external view returns (uint256[]) ``` *Returns all listed pairs custom max leverages (1e3 precision)* ## getGroupLiquidationParams ```solidity theme={null} function getGroupLiquidationParams(uint256 _groupIndex) external view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Returns a group's liquidation params* ## getPairLiquidationParams ```solidity theme={null} function getPairLiquidationParams(uint256 _pairIndex) external view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Returns a pair's group liquidation params* # GNSPriceAggregator Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnspriceaggregator *Facet #10: Price aggregator (does the requests to the Chainlink DON, takes the median, and executes callbacks)* ## constructor ```solidity theme={null} constructor() public ``` ## initializePriceAggregator ```solidity theme={null} function initializePriceAggregator(address _linkToken, contract IChainlinkFeed _linkUsdPriceFeed, uint24 _twapInterval, uint8 _minAnswers, address[] _nodes, bytes32[2] _jobIds, uint8[] _collateralIndices, struct IPriceAggregator.LiquidityPoolInput[] _gnsCollateralLiquidityPools, contract IChainlinkFeed[] _collateralUsdPriceFeeds) external ``` *Initializes price aggregator facet* ### Parameters | Name | Type | Description | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | \_linkToken | address | LINK token address | | \_linkUsdPriceFeed | contract IChainlinkFeed | LINK/USD price feed address | | \_twapInterval | uint24 | TWAP interval (seconds) | | \_minAnswers | uint8 | answers count at which a trade is executed with median | | \_nodes | address\[] | | | \_jobIds | bytes32\[2] | chainlink job ids (market/lookback) | | \_collateralIndices | uint8\[] | collateral indices | | \_gnsCollateralLiquidityPools | [IPriceAggregator.LiquidityPoolInput\[\]](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | corresponding GNS/collateral liquidity pool values | | \_collateralUsdPriceFeeds | contract IChainlinkFeed\[] | corresponding collateral/USD chainlink price feeds | ## updateLinkUsdPriceFeed ```solidity theme={null} function updateLinkUsdPriceFeed(contract IChainlinkFeed _value) external ``` *Updates LINK/USD chainlink price feed* ### Parameters | Name | Type | Description | | ------- | ----------------------- | ----------- | | \_value | contract IChainlinkFeed | new value | ## updateCollateralUsdPriceFeed ```solidity theme={null} function updateCollateralUsdPriceFeed(uint8 _collateralIndex, contract IChainlinkFeed _value) external ``` *Updates collateral/USD chainlink price feed* ### Parameters | Name | Type | Description | | ----------------- | ----------------------- | ---------------- | | \_collateralIndex | uint8 | collateral index | | \_value | contract IChainlinkFeed | new value | ## updateCollateralGnsLiquidityPool ```solidity theme={null} function updateCollateralGnsLiquidityPool(uint8 _collateralIndex, struct IPriceAggregator.LiquidityPoolInput _liquidityPoolInput) external ``` *Updates collateral/GNS liquidity pool* ### Parameters | Name | Type | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------- | | \_collateralIndex | uint8 | collateral index | | \_liquidityPoolInput | [IPriceAggregator.LiquidityPoolInput](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | new values | ## updateTwapInterval ```solidity theme={null} function updateTwapInterval(uint24 _twapInterval) external ``` *Updates TWAP interval* ### Parameters | Name | Type | Description | | -------------- | ------ | ------------------- | | \_twapInterval | uint24 | new value (seconds) | ## updateMinAnswers ```solidity theme={null} function updateMinAnswers(uint8 _value) external ``` *Updates minimum answers count* ### Parameters | Name | Type | Description | | ------- | ----- | ----------- | | \_value | uint8 | new value | ## addOracle ```solidity theme={null} function addOracle(address _a) external ``` *Adds an oracle* ### Parameters | Name | Type | Description | | ---- | ------- | ----------- | | \_a | address | new value | ## replaceOracle ```solidity theme={null} function replaceOracle(uint256 _index, address _a) external ``` *Replaces an oracle* ### Parameters | Name | Type | Description | | ------- | ------- | ------------ | | \_index | uint256 | oracle index | | \_a | address | new value | ## removeOracle ```solidity theme={null} function removeOracle(uint256 _index) external ``` *Removes an oracle* ### Parameters | Name | Type | Description | | ------- | ------- | ------------ | | \_index | uint256 | oracle index | ## setMarketJobId ```solidity theme={null} function setMarketJobId(bytes32 _jobId) external ``` *Updates market job id* ### Parameters | Name | Type | Description | | ------- | ------- | ----------- | | \_jobId | bytes32 | new value | ## setLimitJobId ```solidity theme={null} function setLimitJobId(bytes32 _jobId) external ``` *Updates lookback job id* ### Parameters | Name | Type | Description | | ------- | ------- | ----------- | | \_jobId | bytes32 | new value | ## getPrice ```solidity theme={null} function getPrice(uint8 _collateralIndex, uint16 _pairIndex, struct ITradingStorage.Id _tradeId, struct ITradingStorage.Id _orderId, enum ITradingStorage.PendingOrderType _orderType, uint256 _positionSizeCollateral, uint256 _fromBlock) external virtual ``` *Requests price from oracles* ### Parameters | Name | Type | Description | | ------------------------ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_pairIndex | uint16 | pair index | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | trade id | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | order id | | \_orderType | enum ITradingStorage.PendingOrderType | order type | | \_positionSizeCollateral | uint256 | position size (collateral precision) | | \_fromBlock | uint256 | block number from which to start fetching prices (for lookbacks) | ## fulfill ```solidity theme={null} function fulfill(bytes32 _requestId, uint256 _priceData) external ``` *Fulfills price request, called by chainlink oracles* ### Parameters | Name | Type | Description | | ----------- | ------- | ----------- | | \_requestId | bytes32 | request id | | \_priceData | uint256 | price data | ## claimBackLink ```solidity theme={null} function claimBackLink() external ``` *Claims back LINK tokens, called by gov fund* ## getLinkFee ```solidity theme={null} function getLinkFee(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _positionSizeCollateral) external view returns (uint256) ``` *Returns LINK fee for price request* ### Parameters | Name | Type | Description | | ------------------------ | ------- | --------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_trader | address | trader address | | \_pairIndex | uint16 | pair index | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | ## getCollateralPriceUsd ```solidity theme={null} function getCollateralPriceUsd(uint8 _collateralIndex) external view returns (uint256) ``` *Returns collateral/USD price* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getUsdNormalizedValue ```solidity theme={null} function getUsdNormalizedValue(uint8 _collateralIndex, uint256 _collateralValue) external view returns (uint256) ``` *Returns USD normalized value from collateral value* ### Parameters | Name | Type | Description | | ----------------- | ------- | --------------------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_collateralValue | uint256 | collateral value (collateral precision) | ## getCollateralFromUsdNormalizedValue ```solidity theme={null} function getCollateralFromUsdNormalizedValue(uint8 _collateralIndex, uint256 _normalizedValue) external view returns (uint256) ``` *Returns collateral value (collateral precision) from USD normalized value* ### Parameters | Name | Type | Description | | ----------------- | ------- | --------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_normalizedValue | uint256 | normalized value (1e18 USD) | ## getGnsPriceUsd ```solidity theme={null} function getGnsPriceUsd(uint8 _collateralIndex) external view virtual returns (uint256) ``` *Returns GNS/USD price based on GNS/collateral price* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getGnsPriceUsd ```solidity theme={null} function getGnsPriceUsd(uint8 _collateralIndex, uint256 _gnsPriceCollateral) external view returns (uint256) ``` *Returns GNS/USD price based on GNS/collateral price* ### Parameters | Name | Type | Description | | -------------------- | ------- | --------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_gnsPriceCollateral | uint256 | GNS/collateral price (1e10) | ## getGnsPriceCollateralIndex ```solidity theme={null} function getGnsPriceCollateralIndex(uint8 _collateralIndex) external view virtual returns (uint256) ``` *Returns GNS/collateral price* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getGnsPriceCollateralAddress ```solidity theme={null} function getGnsPriceCollateralAddress(address _collateral) external view virtual returns (uint256) ``` *Returns GNS/collateral price* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------- | | \_collateral | address | address of the collateral | ## getLinkUsdPriceFeed ```solidity theme={null} function getLinkUsdPriceFeed() external view returns (contract IChainlinkFeed) ``` *Returns the link/usd price feed address* ## getTwapInterval ```solidity theme={null} function getTwapInterval() external view returns (uint24) ``` *Returns the twap interval in seconds* ## getMinAnswers ```solidity theme={null} function getMinAnswers() external view returns (uint8) ``` *Returns the minimum answers to execute an order and take the median* ## getMarketJobId ```solidity theme={null} function getMarketJobId() external view returns (bytes32) ``` *Returns the market job id* ## getLimitJobId ```solidity theme={null} function getLimitJobId() external view returns (bytes32) ``` *Returns the limit job id* ## getOracle ```solidity theme={null} function getOracle(uint256 _index) external view returns (address) ``` *Returns a specific oracle* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------- | | \_index | uint256 | index of the oracle | ## getOracles ```solidity theme={null} function getOracles() external view returns (address[]) ``` *Returns all oracles* ## getCollateralGnsLiquidityPool ```solidity theme={null} function getCollateralGnsLiquidityPool(uint8 _collateralIndex) external view returns (struct IPriceAggregator.LiquidityPoolInfo) ``` *Returns collateral/gns liquidity pool info* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getCollateralUsdPriceFeed ```solidity theme={null} function getCollateralUsdPriceFeed(uint8 _collateralIndex) external view returns (contract IChainlinkFeed) ``` *Returns collateral/usd chainlink price feed* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getPriceAggregatorOrder ```solidity theme={null} function getPriceAggregatorOrder(bytes32 _requestId) external view returns (struct IPriceAggregator.Order) ``` *Returns order data* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------- | | \_requestId | bytes32 | index of collateral | ## getPriceAggregatorOrderAnswers ```solidity theme={null} function getPriceAggregatorOrderAnswers(struct ITradingStorage.Id _orderId) external view returns (struct IPriceAggregator.OrderAnswer[]) ``` *Returns order data* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ----------- | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | order id | ## getChainlinkToken ```solidity theme={null} function getChainlinkToken() external view returns (address) ``` *Returns chainlink token address* ## getRequestCount ```solidity theme={null} function getRequestCount() external view returns (uint256) ``` *Returns requestCount (used by ChainlinkClientUtils)* ## getPendingRequest ```solidity theme={null} function getPendingRequest(bytes32 _id) external view returns (address) ``` *Returns pendingRequests mapping entry (used by ChainlinkClientUtils)* # GNSPriceImpact Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnspriceimpact *Facet #4: Price impact OI windows* ## constructor ```solidity theme={null} constructor() public ``` ## initializePriceImpact ```solidity theme={null} function initializePriceImpact(uint48 _windowsDuration, uint48 _windowsCount) external ``` *Initializes price impact facet* ### Parameters | Name | Type | Description | | ----------------- | ------ | -------------------------- | | \_windowsDuration | uint48 | windows duration (seconds) | | \_windowsCount | uint48 | windows count | ## initializeNegPnlCumulVolMultiplier ```solidity theme={null} function initializeNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) external ``` *Initializes negative pnl cumulative volume multiplier* ### Parameters | Name | Type | Description | | -------------------------- | ------ | ---------------- | | \_negPnlCumulVolMultiplier | uint40 | new value (1e10) | ## initializePairFactors ```solidity theme={null} function initializePairFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors, uint32[] _protectionCloseFactorBlocks, uint40[] _cumulativeFactors) external ``` *Initializes pair factors* ### Parameters | Name | Type | Description | | ----------------------------- | --------- | ------------------------------- | | \_pairIndices | uint16\[] | pair indices to initialize | | \_protectionCloseFactors | uint40\[] | protection close factors (1e10) | | \_protectionCloseFactorBlocks | uint32\[] | protection close factor blocks | | \_cumulativeFactors | uint40\[] | cumulative factors (1e10) | ## setPriceImpactWindowsCount ```solidity theme={null} function setPriceImpactWindowsCount(uint48 _newWindowsCount) external ``` *Updates price impact windows count* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------- | | \_newWindowsCount | uint48 | new windows count | ## setPriceImpactWindowsDuration ```solidity theme={null} function setPriceImpactWindowsDuration(uint48 _newWindowsDuration) external ``` *Updates price impact windows duration* ### Parameters | Name | Type | Description | | -------------------- | ------ | ------------------------------ | | \_newWindowsDuration | uint48 | new windows duration (seconds) | ## setNegPnlCumulVolMultiplier ```solidity theme={null} function setNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) external ``` *Updates negative pnl cumulative volume multiplier* ### Parameters | Name | Type | Description | | -------------------------- | ------ | ---------------- | | \_negPnlCumulVolMultiplier | uint40 | new value (1e10) | ## setProtectionCloseFactorWhitelist ```solidity theme={null} function setProtectionCloseFactorWhitelist(address[] _traders, bool[] _whitelisted) external ``` *Whitelists/unwhitelists traders from protection close factor* ### Parameters | Name | Type | Description | | ------------- | ---------- | ----------------- | | \_traders | address\[] | traders addresses | | \_whitelisted | bool\[] | values | ## setPairDepths ```solidity theme={null} function setPairDepths(uint256[] _indices, uint128[] _depthsAboveUsd, uint128[] _depthsBelowUsd) external ``` *Updates pairs 1% depths above and below* ### Parameters | Name | Type | Description | | ---------------- | ---------- | ----------------------------- | | \_indices | uint256\[] | indices of pairs | | \_depthsAboveUsd | uint128\[] | depths above the price in USD | | \_depthsBelowUsd | uint128\[] | depths below the price in USD | ## setProtectionCloseFactors ```solidity theme={null} function setProtectionCloseFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors) external ``` *Sets protection close factors for pairs* ### Parameters | Name | Type | Description | | ------------------------ | --------- | ----------------------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_protectionCloseFactors | uint40\[] | new protection close factors (1e10) | ## setProtectionCloseFactorBlocks ```solidity theme={null} function setProtectionCloseFactorBlocks(uint16[] _pairIndices, uint32[] _protectionCloseFactorBlocks) external ``` *Sets protection close factor blocks duration for pairs* ### Parameters | Name | Type | Description | | ----------------------------- | --------- | ---------------------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_protectionCloseFactorBlocks | uint32\[] | new protection close factor blocks | ## setCumulativeFactors ```solidity theme={null} function setCumulativeFactors(uint16[] _pairIndices, uint40[] _cumulativeFactors) external ``` *Sets cumulative factors for pairs* ### Parameters | Name | Type | Description | | ------------------- | --------- | ----------------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_cumulativeFactors | uint40\[] | new cumulative factors (1e10) | ## setExemptOnOpen ```solidity theme={null} function setExemptOnOpen(uint16[] _pairIndices, bool[] _exemptOnOpen) external ``` *Sets whether pairs are exempt from price impact on open* ### Parameters | Name | Type | Description | | -------------- | --------- | ---------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_exemptOnOpen | bool\[] | new values | ## setExemptAfterProtectionCloseFactor ```solidity theme={null} function setExemptAfterProtectionCloseFactor(uint16[] _pairIndices, bool[] _exemptAfterProtectionCloseFactor) external ``` *Sets whether pairs are exempt from price impact on close once protection close factor has expired* ### Parameters | Name | Type | Description | | ---------------------------------- | --------- | ---------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_exemptAfterProtectionCloseFactor | bool\[] | new values | ## addPriceImpactOpenInterest ```solidity theme={null} function addPriceImpactOpenInterest(address _trader, uint32 _index, uint256 _oiDeltaCollateral, bool _open, bool _isPnlPositive) external virtual ``` *Adds open interest to current window* ### Parameters | Name | Type | Description | | ------------------- | ------- | ---------------------------------------------------------------------------------- | | \_trader | address | trader address | | \_index | uint32 | trade index | | \_oiDeltaCollateral | uint256 | open interest to add (collateral precision) | | \_open | bool | whether it corresponds to opening or closing a trade | | \_isPnlPositive | bool | whether it corresponds to a positive pnl trade (only relevant when \_open = false) | ## getPriceImpactOi ```solidity theme={null} function getPriceImpactOi(uint256 _pairIndex, bool _long) external view returns (uint256 activeOi) ``` *Returns active open interest used in price impact calculation for a pair and side (long/short)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------------------ | | \_pairIndex | uint256 | index of pair | | \_long | bool | true for long, false for short | ## getTradePriceImpact ```solidity theme={null} function getTradePriceImpact(address _trader, uint256 _marketPrice, uint256 _pairIndex, bool _long, uint256 _tradeOpenInterestUsd, bool _isPnlPositive, bool _open, uint256 _lastPosIncreaseBlock, enum ITradingStorage.ContractsVersion _contractsVersion) external view returns (uint256 priceImpactP, uint256 priceAfterImpact) ``` *Returns price impact % (1e10 precision) and price after impact (1e10 precision) for a trade* ### Parameters | Name | Type | Description | | ---------------------- | ------------------------------------- | ------------------------------------------------------------------------------------- | | \_trader | address | trader address (to check if whitelisted from protection close factor) | | \_marketPrice | uint256 | market price (1e10 precision) | | \_pairIndex | uint256 | index of pair | | \_long | bool | true for long, false for short | | \_tradeOpenInterestUsd | uint256 | open interest of trade in USD (1e18 precision) | | \_isPnlPositive | bool | true if positive pnl, false if negative pnl (only relevant when \_open = false) | | \_open | bool | true on open, false on close | | \_lastPosIncreaseBlock | uint256 | block when trade position size was last increased (only relevant when \_open = false) | | \_contractsVersion | enum ITradingStorage.ContractsVersion | trade contracts version | ## getPairDepth ```solidity theme={null} function getPairDepth(uint256 _pairIndex) external view returns (struct IPriceImpact.PairDepth) ``` *Returns a pair's depths above and below the price* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## getOiWindowsSettings ```solidity theme={null} function getOiWindowsSettings() external view returns (struct IPriceImpact.OiWindowsSettings) ``` *Returns current price impact windows settings* ## getOiWindow ```solidity theme={null} function getOiWindow(uint48 _windowsDuration, uint256 _pairIndex, uint256 _windowId) external view returns (struct IPriceImpact.PairOi) ``` *Returns OI window details (long/short OI)* ### Parameters | Name | Type | Description | | ----------------- | ------- | -------------------------- | | \_windowsDuration | uint48 | windows duration (seconds) | | \_pairIndex | uint256 | index of pair | | \_windowId | uint256 | id of window | ## getOiWindows ```solidity theme={null} function getOiWindows(uint48 _windowsDuration, uint256 _pairIndex, uint256[] _windowIds) external view returns (struct IPriceImpact.PairOi[]) ``` *Returns multiple OI windows details (long/short OI)* ### Parameters | Name | Type | Description | | ----------------- | ---------- | -------------------------- | | \_windowsDuration | uint48 | windows duration (seconds) | | \_pairIndex | uint256 | index of pair | | \_windowIds | uint256\[] | ids of windows | ## getPairDepths ```solidity theme={null} function getPairDepths(uint256[] _indices) external view returns (struct IPriceImpact.PairDepth[]) ``` *Returns depths above and below the price for multiple pairs* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------- | | \_indices | uint256\[] | indices of pairs | ## getPairFactors ```solidity theme={null} function getPairFactors(uint256[] _indices) external view returns (struct IPriceImpact.PairFactors[]) ``` *Returns factors for a set of pairs (1e10)* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------- | | \_indices | uint256\[] | indices of pairs | ## getNegPnlCumulVolMultiplier ```solidity theme={null} function getNegPnlCumulVolMultiplier() external view returns (uint48) ``` *Returns negative pnl cumulative volume multiplier* ## getProtectionCloseFactorWhitelist ```solidity theme={null} function getProtectionCloseFactorWhitelist(address _trader) external view returns (bool) ``` *Returns whether a trader is whitelisted from protection close factor* # GNSReferrals Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnsreferrals *Facet #2: Referral system* ## constructor ```solidity theme={null} constructor() public ``` ## initializeReferrals ```solidity theme={null} function initializeReferrals(uint256 _allyFeeP, uint256 _startReferrerFeeP, uint256 _targetVolumeUsd) external ``` ### Parameters | Name | Type | Description | | ------------------- | ------- | ---------------------------------------------------------------- | | \_allyFeeP | uint256 | % of total referral fee going to ally | | \_startReferrerFeeP | uint256 | initial % of total referral fee earned when zero volume referred | | \_targetVolumeUsd | uint256 | usd opening volume to refer to reach 100% of referral fee | ## updateAllyFeeP ```solidity theme={null} function updateAllyFeeP(uint256 _value) external ``` *Updates allyFeeP* ### Parameters | Name | Type | Description | | ------- | ------- | -------------- | | \_value | uint256 | new ally fee % | ## updateStartReferrerFeeP ```solidity theme={null} function updateStartReferrerFeeP(uint256 _value) external ``` *Updates startReferrerFeeP* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------------ | | \_value | uint256 | new start referrer fee % | ## updateReferralsTargetVolumeUsd ```solidity theme={null} function updateReferralsTargetVolumeUsd(uint256 _value) external ``` *Updates targetVolumeUsd* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------------ | | \_value | uint256 | new target volume in usd | ## whitelistAllies ```solidity theme={null} function whitelistAllies(address[] _allies) external ``` *Whitelists ally addresses* ### Parameters | Name | Type | Description | | -------- | ---------- | ----------------------- | | \_allies | address\[] | array of ally addresses | ## unwhitelistAllies ```solidity theme={null} function unwhitelistAllies(address[] _allies) external ``` *Unwhitelists ally addresses* ### Parameters | Name | Type | Description | | -------- | ---------- | ----------------------- | | \_allies | address\[] | array of ally addresses | ## whitelistReferrers ```solidity theme={null} function whitelistReferrers(address[] _referrers, address[] _allies) external ``` *Whitelists referrer addresses* ### Parameters | Name | Type | Description | | ----------- | ---------- | ------------------------------------- | | \_referrers | address\[] | array of referrer addresses | | \_allies | address\[] | array of corresponding ally addresses | ## unwhitelistReferrers ```solidity theme={null} function unwhitelistReferrers(address[] _referrers) external ``` *Unwhitelists referrer addresses* ### Parameters | Name | Type | Description | | ----------- | ---------- | --------------------------- | | \_referrers | address\[] | array of referrer addresses | ## registerPotentialReferrer ```solidity theme={null} function registerPotentialReferrer(address _trader, address _referrer) external virtual ``` *Registers potential referrer for trader (only works if trader wasn't referred yet by someone else)* ### Parameters | Name | Type | Description | | ---------- | ------- | -------------- | | \_trader | address | trader address | | \_referrer | address | | ## distributeReferralReward ```solidity theme={null} function distributeReferralReward(address _trader, uint256 _volumeUsd, uint256 _referrerFeeUsd, uint256 _gnsPriceUsd) external virtual ``` *Distributes ally and referrer rewards* ### Parameters | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | \_trader | address | trader address | | \_volumeUsd | uint256 | trading volume in usd (1e18 precision) | | \_referrerFeeUsd | uint256 | referrer fee in USD (1e18 precision) | | \_gnsPriceUsd | uint256 | token price in usd (1e10 precision) | ## claimAllyRewards ```solidity theme={null} function claimAllyRewards() external ``` *Claims pending GNS ally rewards of caller* ## claimReferrerRewards ```solidity theme={null} function claimReferrerRewards() external ``` *Claims pending GNS referrer rewards of caller* ## getReferrerFeeProgressP ```solidity theme={null} function getReferrerFeeProgressP(address _referrer) external view returns (uint256) ``` *Returns referrer fee % progress towards earning 100% based on his volume referred (1e10)* ### Parameters | Name | Type | Description | | ---------- | ------- | ---------------- | | \_referrer | address | referrer address | ## getTraderLastReferrer ```solidity theme={null} function getTraderLastReferrer(address _trader) external view returns (address) ``` *Returns last referrer of trader (whether referrer active or not)* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------- | | \_trader | address | address of trader | ## getTraderActiveReferrer ```solidity theme={null} function getTraderActiveReferrer(address _trader) external view returns (address) ``` *Returns active referrer of trader* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------- | | \_trader | address | address of trader | ## getReferrersReferred ```solidity theme={null} function getReferrersReferred(address _ally) external view returns (address[]) ``` *Returns referrers referred by ally* ### Parameters | Name | Type | Description | | ------ | ------- | --------------- | | \_ally | address | address of ally | ## getTradersReferred ```solidity theme={null} function getTradersReferred(address _referrer) external view returns (address[]) ``` *Returns traders referred by referrer* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------- | | \_referrer | address | address of referrer | ## getReferralsAllyFeeP ```solidity theme={null} function getReferralsAllyFeeP() external view returns (uint256) ``` *Returns ally fee % of total referral fee* ## getReferralsStartReferrerFeeP ```solidity theme={null} function getReferralsStartReferrerFeeP() external view returns (uint256) ``` *Returns start referrer fee % of total referral fee when zero volume was referred* ## getReferralsTargetVolumeUsd ```solidity theme={null} function getReferralsTargetVolumeUsd() external view returns (uint256) ``` *Returns target volume in usd to reach 100% of referral fee* ## getAllyDetails ```solidity theme={null} function getAllyDetails(address _ally) external view returns (struct IReferrals.AllyDetails) ``` *Returns ally details* ### Parameters | Name | Type | Description | | ------ | ------- | --------------- | | \_ally | address | address of ally | ## getReferrerDetails ```solidity theme={null} function getReferrerDetails(address _referrer) external view returns (struct IReferrals.ReferrerDetails) ``` *Returns referrer details* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------- | | \_referrer | address | address of referrer | # GNSTradingCallbacks Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnstradingcallbacks *Facet #8: Callbacks (to execute actions after receiving median price from price aggregator)* ## constructor ```solidity theme={null} constructor() public ``` ## initializeCallbacks ```solidity theme={null} function initializeCallbacks(uint8 _vaultClosingFeeP) external ``` ### Parameters | Name | Type | Description | | ------------------ | ----- | ----------------------------------- | | \_vaultClosingFeeP | uint8 | the % of closing fee going to vault | ## initializeTreasuryAddress ```solidity theme={null} function initializeTreasuryAddress(address _treasury) external ``` *Initialize the treasury address* ### Parameters | Name | Type | Description | | ---------- | ------- | -------------------- | | \_treasury | address | the treasury address | ## updateVaultClosingFeeP ```solidity theme={null} function updateVaultClosingFeeP(uint8 _valueP) external ``` *Update the % of closing fee going to vault* ### Parameters | Name | Type | Description | | -------- | ----- | ----------------------------------- | | \_valueP | uint8 | the % of closing fee going to vault | ## updateTreasuryAddress ```solidity theme={null} function updateTreasuryAddress(address _treasury) external ``` *Updates the treasury address* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------ | | \_treasury | address | the new treasury address | ## claimPendingGovFees ```solidity theme={null} function claimPendingGovFees() external ``` *Claim the pending gov fees for all collaterals* ## openTradeMarketCallback ```solidity theme={null} function openTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual ``` *Executes a pending open trade market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## closeTradeMarketCallback ```solidity theme={null} function closeTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual ``` *Executes a pending close trade market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## executeTriggerOpenOrderCallback ```solidity theme={null} function executeTriggerOpenOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual ``` *Executes a pending open trigger order (for limit/stop orders)* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## executeTriggerCloseOrderCallback ```solidity theme={null} function executeTriggerCloseOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual ``` *Executes a pending close trigger order (for tp/sl/liq orders)* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## getVaultClosingFeeP ```solidity theme={null} function getVaultClosingFeeP() external view returns (uint8) ``` *Returns the current vaultClosingFeeP value (%)* ## getPendingGovFeesCollateral ```solidity theme={null} function getPendingGovFeesCollateral(uint8 _collateralIndex) external view returns (uint256) ``` *Returns the current pending gov fees for a collateral index (collateral precision)* ## updateLeverageCallback ```solidity theme={null} function updateLeverageCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual ``` *Executes a pending update leverage order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## increasePositionSizeMarketCallback ```solidity theme={null} function increasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual ``` *Executes a pending increase position size market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## decreasePositionSizeMarketCallback ```solidity theme={null} function decreasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual ``` *Executes a pending decrease position size market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## validateTriggerOpenOrderCallback ```solidity theme={null} function validateTriggerOpenOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) external view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v) ``` *Makes open trigger (STOP/LIMIT) checks like slippage, price impact, missed targets and returns cancellation reason if any* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the trade | | \_orderType | enum ITradingStorage.PendingOrderType | the pending order type | | \_open | uint64 | the `open` value from an aggregator answer | | \_high | uint64 | the `high` value from an aggregator answer | | \_low | uint64 | the `low` value from an aggregator answer | ## validateTriggerCloseOrderCallback ```solidity theme={null} function validateTriggerCloseOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) external view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v) ``` *Makes close trigger (SL/TP/LIQ) checks like slippage and price impact and returns cancellation reason if any* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the trade | | \_orderType | enum ITradingStorage.PendingOrderType | the pending order type | | \_open | uint64 | the `open` value from an aggregator answer | | \_high | uint64 | the `high` value from an aggregator answer | | \_low | uint64 | the `low` value from an aggregator answer | # GNSTradingInteractions Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnstradinginteractions *Facet #7: Trading (user interactions)* ## constructor ```solidity theme={null} constructor() public ``` ## initializeTrading ```solidity theme={null} function initializeTrading(uint16 _marketOrdersTimeoutBlocks, address[] _usersByPassTriggerLink) external ``` *Initializes the trading facet* ### Parameters | Name | Type | Description | | --------------------------- | ---------- | ----------------------------------------------------------------------- | | \_marketOrdersTimeoutBlocks | uint16 | The number of blocks after which a market order is considered timed out | | \_usersByPassTriggerLink | address\[] | | ## updateMarketOrdersTimeoutBlocks ```solidity theme={null} function updateMarketOrdersTimeoutBlocks(uint16 _valueBlocks) external ``` *Updates marketOrdersTimeoutBlocks* ### Parameters | Name | Type | Description | | ------------- | ------ | ------------------------------------------- | | \_valueBlocks | uint16 | blocks after which a market order times out | ## updateByPassTriggerLink ```solidity theme={null} function updateByPassTriggerLink(address[] _users, bool[] _shouldByPass) external ``` *Updates the users that can bypass the link cost of triggerOrder* ### Parameters | Name | Type | Description | | -------------- | ---------- | ---------------------------------------------------------------- | | \_users | address\[] | array of addresses that can bypass the link cost of triggerOrder | | \_shouldByPass | bool\[] | whether each user should bypass the link cost | ## setTradingDelegate ```solidity theme={null} function setTradingDelegate(address _delegate) external ``` \_Sets *delegate as the new delegate of caller (can call delegatedAction)* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------ | | \_delegate | address | the new delegate address | ## removeTradingDelegate ```solidity theme={null} function removeTradingDelegate() external ``` *Removes the delegate of caller (can't call delegatedAction)* ## delegatedTradingAction ```solidity theme={null} function delegatedTradingAction(address _trader, bytes _callData) external returns (bytes) ``` \_Caller executes a trading action on behalf of *trader using delegatecall* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------------------------------------ | | \_trader | address | the trader address to execute the trading action for | | \_callData | bytes | the data to be executed (open trade/close trade, etc.) | ## openTrade ```solidity theme={null} function openTrade(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external ``` *Opens a new trade/limit order/stop order* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | the trade to be opened | | \_maxSlippageP | uint16 | the maximum allowed slippage % when open the trade (1e3 precision) | | \_referrer | address | the address of the referrer (can only be set once for a trader) | ## openTradeNative ```solidity theme={null} function openTradeNative(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external payable ``` *Wraps native token and opens a new trade/limit order/stop order* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | the trade to be opened | | \_maxSlippageP | uint16 | the maximum allowed slippage % when open the trade (1e3 precision) | | \_referrer | address | the address of the referrer (can only be set once for a trader) | ## updateMaxClosingSlippageP ```solidity theme={null} function updateMaxClosingSlippageP(uint32 _index, uint16 _maxSlippageP) external ``` *Updates existing trade's max closing slippage % for caller* ### Parameters | Name | Type | Description | | -------------- | ------ | ------------------------------------------ | | \_index | uint32 | index of trade | | \_maxSlippageP | uint16 | new max closing slippage % (1e3 precision) | ## closeTradeMarket ```solidity theme={null} function closeTradeMarket(uint32 _index, uint64 _expectedPrice) external ``` *Closes an open trade (market order) for caller* ### Parameters | Name | Type | Description | | --------------- | ------ | ------------------------------------------------------------------- | | \_index | uint32 | the index of the trade of caller | | \_expectedPrice | uint64 | expected closing price, used to check max slippage (1e10 precision) | ## updateOpenOrder ```solidity theme={null} function updateOpenOrder(uint32 _index, uint64 _triggerPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external ``` *Updates an existing limit/stop order for caller* ### Parameters | Name | Type | Description | | -------------- | ------ | ------------------------------------------------------ | | \_index | uint32 | index of limit/stop order of caller | | \_triggerPrice | uint64 | new trigger price of limit/stop order (1e10 precision) | | \_tp | uint64 | new tp of limit/stop order (1e10 precision) | | \_sl | uint64 | new sl of limit/stop order (1e10 precision) | | \_maxSlippageP | uint16 | new max slippage % of limit/stop order (1e3 precision) | ## cancelOpenOrder ```solidity theme={null} function cancelOpenOrder(uint32 _index) external ``` *Cancels an open limit/stop order for caller* ### Parameters | Name | Type | Description | | ------- | ------ | ----------------------------------- | | \_index | uint32 | index of limit/stop order of caller | ## updateTp ```solidity theme={null} function updateTp(uint32 _index, uint64 _newTp) external ``` *Updates the tp of an open trade for caller* ### Parameters | Name | Type | Description | | ------- | ------ | ------------------------------------- | | \_index | uint32 | index of open trade of caller | | \_newTp | uint64 | new tp of open trade (1e10 precision) | ## updateSl ```solidity theme={null} function updateSl(uint32 _index, uint64 _newSl) external ``` *Updates the sl of an open trade for caller* ### Parameters | Name | Type | Description | | ------- | ------ | ------------------------------------- | | \_index | uint32 | index of open trade of caller | | \_newSl | uint64 | new sl of open trade (1e10 precision) | ## updateLeverage ```solidity theme={null} function updateLeverage(uint32 _index, uint24 _newLeverage) external ``` *Update trade leverage* ### Parameters | Name | Type | Description | | ------------- | ------ | ------------------ | | \_index | uint32 | index of trade | | \_newLeverage | uint24 | new leverage (1e3) | ## increasePositionSize ```solidity theme={null} function increasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice, uint16 _maxSlippageP) external ``` *Increase trade position size* ### Parameters | Name | Type | Description | | ----------------- | ------- | -------------------------------------------- | | \_index | uint32 | index of trade | | \_collateralDelta | uint120 | collateral to add (collateral precision) | | \_leverageDelta | uint24 | partial trade leverage (1e3) | | \_expectedPrice | uint64 | expected price of execution (1e10 precision) | | \_maxSlippageP | uint16 | max slippage % (1e3) | ## decreasePositionSize ```solidity theme={null} function decreasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice) external ``` *Decrease trade position size* ### Parameters | Name | Type | Description | | ----------------- | ------- | ------------------------------------------------------------------- | | \_index | uint32 | index of trade | | \_collateralDelta | uint120 | collateral to remove (collateral precision) | | \_leverageDelta | uint24 | leverage to reduce by (1e3) | | \_expectedPrice | uint64 | expected closing price, used to check max slippage (1e10 precision) | ## triggerOrder ```solidity theme={null} function triggerOrder(uint256 _packed) external ``` *Initiates a new trigger order (for tp/sl/liq/limit/stop orders)* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------------------------------------------------- | | \_packed | uint256 | the packed data of the trigger order (orderType, trader, index) | ## cancelOrderAfterTimeout ```solidity theme={null} function cancelOrderAfterTimeout(uint32 _orderIndex) external ``` *Safety function in case oracles don't answer in time, allows caller to cancel a pending order and if relevant claim back any stuck collateral Only allowed for MARKET\_OPEN, MARKET\_CLOSE, UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE orders* ### Parameters | Name | Type | Description | | ------------ | ------ | ------------------------------------- | | \_orderIndex | uint32 | the id of the pending order to cancel | ## getWrappedNativeToken ```solidity theme={null} function getWrappedNativeToken() external view returns (address) ``` *Returns the wrapped native token or address(0) if the current chain, or the wrapped token, is not supported.* ## isWrappedNativeToken ```solidity theme={null} function isWrappedNativeToken(address _token) external view returns (bool) ``` *Returns true if the token is the wrapped native token for the current chain, where supported.* ### Parameters | Name | Type | Description | | ------- | ------- | ------------- | | \_token | address | token address | ## getTradingDelegate ```solidity theme={null} function getTradingDelegate(address _trader) external view returns (address) ``` *Returns the address a trader delegates his trading actions to* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getMarketOrdersTimeoutBlocks ```solidity theme={null} function getMarketOrdersTimeoutBlocks() external view returns (uint16) ``` *Returns the current marketOrdersTimeoutBlocks value* ## getByPassTriggerLink ```solidity theme={null} function getByPassTriggerLink(address _user) external view returns (bool) ``` *Returns whether a user bypasses trigger link costs* ### Parameters | Name | Type | Description | | ------ | ------- | ------------------- | | \_user | address | address of the user | # GNSTradingStorage Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnstradingstorage *Facet #5: Trading storage* ## constructor ```solidity theme={null} constructor() public ``` ## initializeTradingStorage ```solidity theme={null} function initializeTradingStorage(address _gns, address _gnsStaking, address[] _collaterals, address[] _gTokens) external ``` *Initializes the trading storage facet* ### Parameters | Name | Type | Description | | ------------- | ---------- | ----------------------------------- | | \_gns | address | address of the gns token | | \_gnsStaking | address | address of the gns staking contract | | \_collaterals | address\[] | | | \_gTokens | address\[] | | ## updateTradingActivated ```solidity theme={null} function updateTradingActivated(enum ITradingStorage.TradingActivated _activated) external ``` *Updates the trading activated state* ### Parameters | Name | Type | Description | | ----------- | ------------------------------------- | ------------------------------- | | \_activated | enum ITradingStorage.TradingActivated | the new trading activated state | ## addCollateral ```solidity theme={null} function addCollateral(address _collateral, address _gToken) external ``` *Adds a new supported collateral* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------------------- | | \_collateral | address | the address of the collateral | | \_gToken | address | the gToken contract of the collateral | ## toggleCollateralActiveState ```solidity theme={null} function toggleCollateralActiveState(uint8 _collateralIndex) external ``` *Toggles the active state of a supported collateral* ### Parameters | Name | Type | Description | | ----------------- | ----- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | ## updateGToken ```solidity theme={null} function updateGToken(address _collateral, address _gToken) external ``` *Updates the contracts of a supported collateral trading stack* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------------------- | | \_collateral | address | address of the collateral | | \_gToken | address | the gToken contract of the collateral | ## storeTrade ```solidity theme={null} function storeTrade(struct ITradingStorage.Trade _trade, struct ITradingStorage.TradeInfo _tradeInfo) external virtual returns (struct ITradingStorage.Trade) ``` *Stores a new trade (trade/limit/stop)* ### Parameters | Name | Type | Description | | ----------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade to be stored | | \_tradeInfo | [ITradingStorage.TradeInfo](/developer/technical-reference/contracts/interfaces/types/itradingstorage#tradeinfo) | trade info to be stored | ## updateTradeMaxClosingSlippageP ```solidity theme={null} function updateTradeMaxClosingSlippageP(struct ITradingStorage.Id _tradeId, uint16 _maxSlippageP) external virtual ``` *Updates an existing trade max closing slippage %* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the trade | | \_maxSlippageP | uint16 | new max slippage % (1e3 precision) | ## updateTradeCollateralAmount ```solidity theme={null} function updateTradeCollateralAmount(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount) external virtual ``` *Updates an open trade collateral* ### Parameters | Name | Type | Description | | ------------------ | -------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade | | \_collateralAmount | uint120 | new collateral amount value (collateral precision) | ## updateTradePosition ```solidity theme={null} function updateTradePosition(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount, uint24 _leverage, uint64 _openPrice, bool _isPartialIncrease, bool _isPnlPositive) external virtual ``` *Updates an open trade collateral* ### Parameters | Name | Type | Description | | ------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade | | \_collateralAmount | uint120 | new collateral amount value (collateral precision) | | \_leverage | uint24 | new leverage value | | \_openPrice | uint64 | new open price value | | \_isPartialIncrease | bool | refreshes trade liquidation params if true | | \_isPnlPositive | bool | whether the pnl is positive (only relevant when closing) | ## updateOpenOrderDetails ```solidity theme={null} function updateOpenOrderDetails(struct ITradingStorage.Id _tradeId, uint64 _openPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external virtual ``` *Updates an open order details (limit/stop)* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------- | ------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade | | \_openPrice | uint64 | new open price (1e10) | | \_tp | uint64 | new take profit price (1e10) | | \_sl | uint64 | new stop loss price (1e10) | | \_maxSlippageP | uint16 | new max slippage % value (1e3) | ## updateTradeTp ```solidity theme={null} function updateTradeTp(struct ITradingStorage.Id _tradeId, uint64 _newTp) external virtual ``` *Updates the take profit of an open trade* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ------------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id | | \_newTp | uint64 | the new take profit (1e10 precision) | ## updateTradeSl ```solidity theme={null} function updateTradeSl(struct ITradingStorage.Id _tradeId, uint64 _newSl) external virtual ``` *Updates the stop loss of an open trade* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | --------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id | | \_newSl | uint64 | the new sl (1e10 precision) | ## closeTrade ```solidity theme={null} function closeTrade(struct ITradingStorage.Id _tradeId, bool _isPnlPositive) external virtual ``` *Marks an open trade/limit/stop as closed* ### Parameters | Name | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------- | --------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id | | \_isPnlPositive | bool | whether the pnl is positive | ## storePendingOrder ```solidity theme={null} function storePendingOrder(struct ITradingStorage.PendingOrder _pendingOrder) external virtual returns (struct ITradingStorage.PendingOrder) ``` *Stores a new pending order* ### Parameters | Name | Type | Description | | -------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------ | | \_pendingOrder | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | the pending order to be stored | ## closePendingOrder ```solidity theme={null} function closePendingOrder(struct ITradingStorage.Id _orderId) external virtual ``` *Closes a pending order* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------- | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the pending order to be closed | ## getCollateral ```solidity theme={null} function getCollateral(uint8 _index) external view returns (struct ITradingStorage.Collateral) ``` *Returns collateral data by index* ### Parameters | Name | Type | Description | | ------- | ----- | ------------------------------------- | | \_index | uint8 | the index of the supported collateral | ## isCollateralActive ```solidity theme={null} function isCollateralActive(uint8 _index) external view returns (bool) ``` *Returns whether can open new trades with a collateral* ### Parameters | Name | Type | Description | | ------- | ----- | ------------------------------------ | | \_index | uint8 | the index of the collateral to check | ## isCollateralListed ```solidity theme={null} function isCollateralListed(uint8 _index) external view returns (bool) ``` *Returns whether a collateral has been listed* ### Parameters | Name | Type | Description | | ------- | ----- | ------------------------------------ | | \_index | uint8 | the index of the collateral to check | ## getCollateralsCount ```solidity theme={null} function getCollateralsCount() external view returns (uint8) ``` *Returns the number of supported collaterals* ## getCollaterals ```solidity theme={null} function getCollaterals() external view returns (struct ITradingStorage.Collateral[]) ``` *Returns the supported collaterals* ## getCollateralIndex ```solidity theme={null} function getCollateralIndex(address _collateral) external view returns (uint8) ``` *Returns the index of a supported collateral* ### Parameters | Name | Type | Description | | ------------ | ------- | ----------------------------- | | \_collateral | address | the address of the collateral | ## getTradingActivated ```solidity theme={null} function getTradingActivated() external view returns (enum ITradingStorage.TradingActivated) ``` *Returns the trading activated state* ## getTraderStored ```solidity theme={null} function getTraderStored(address _trader) external view returns (bool) ``` *Returns whether a trader is stored in the traders array* ### Parameters | Name | Type | Description | | -------- | ------- | --------------- | | \_trader | address | trader to check | ## getTradersCount ```solidity theme={null} function getTradersCount() external view returns (uint256) ``` *Returns the length of the traders array* ## getTraders ```solidity theme={null} function getTraders(uint32 _offset, uint32 _limit) external view returns (address[]) ``` *Returns all traders that have open trades using a pagination system* ### Parameters | Name | Type | Description | | -------- | ------ | -------------------------------- | | \_offset | uint32 | start index in the traders array | | \_limit | uint32 | end index in the traders array | ## getTrade ```solidity theme={null} function getTrade(address _trader, uint32 _index) external view returns (struct ITradingStorage.Trade) ``` *Returns open trade/limit/stop order* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------------------- | | \_trader | address | address of the trader | | \_index | uint32 | index of the trade for trader | ## getTrades ```solidity theme={null} function getTrades(address _trader) external view returns (struct ITradingStorage.Trade[]) ``` *Returns all open trades/limit/stop orders for a trader* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getAllTradesForTraders ```solidity theme={null} function getAllTradesForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.Trade[]) ``` *Returns all trade/limit/stop orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | ------------------------------------ | | \_traders | address\[] | list of traders to return trades for | | \_offset | uint256 | index of first trade to return | | \_limit | uint256 | index of last trade to return | ## getAllTrades ```solidity theme={null} function getAllTrades(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.Trade[]) ``` *Returns all trade/limit/stop orders using a pagination system. Calls `getAllTradesForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ------------------------------ | | \_offset | uint256 | index of first trade to return | | \_limit | uint256 | index of last trade to return | ## getTradeInfo ```solidity theme={null} function getTradeInfo(address _trader, uint32 _index) external view returns (struct ITradingStorage.TradeInfo) ``` *Returns trade info of an open trade/limit/stop order* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------------------- | | \_trader | address | address of the trader | | \_index | uint32 | index of the trade for trader | ## getTradeInfos ```solidity theme={null} function getTradeInfos(address _trader) external view returns (struct ITradingStorage.TradeInfo[]) ``` *Returns all trade infos of open trade/limit/stop orders for a trader* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getAllTradeInfosForTraders ```solidity theme={null} function getAllTradeInfosForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.TradeInfo[]) ``` *Returns all trade infos of open trade/limit/stop orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | --------------------------------------- | | \_traders | address\[] | list of traders to return tradeInfo for | | \_offset | uint256 | index of first tradeInfo to return | | \_limit | uint256 | index of last tradeInfo to return | ## getAllTradeInfos ```solidity theme={null} function getAllTradeInfos(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.TradeInfo[]) ``` *Returns all trade infos of open trade/limit/stop orders using a pagination system. Calls `getAllTradeInfosForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ---------------------------------- | | \_offset | uint256 | index of first tradeInfo to return | | \_limit | uint256 | index of last tradeInfo to return | ## getPendingOrder ```solidity theme={null} function getPendingOrder(struct ITradingStorage.Id _orderId) external view returns (struct ITradingStorage.PendingOrder) ``` *Returns a pending ordeer* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ----------------------- | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the pending order | ## getPendingOrders ```solidity theme={null} function getPendingOrders(address _user) external view returns (struct ITradingStorage.PendingOrder[]) ``` *Returns all pending orders for a trader* ### Parameters | Name | Type | Description | | ------ | ------- | --------------------- | | \_user | address | address of the trader | ## getAllPendingOrdersForTraders ```solidity theme={null} function getAllPendingOrdersForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.PendingOrder[]) ``` *Returns all pending orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | ------------------------------------------ | | \_traders | address\[] | list of traders to return pendingOrder for | | \_offset | uint256 | index of first pendingOrder to return | | \_limit | uint256 | index of last pendingOrder to return | ## getAllPendingOrders ```solidity theme={null} function getAllPendingOrders(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.PendingOrder[]) ``` *Returns all pending orders using a pagination system Calls `getAllPendingOrdersForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ------------------------------------- | | \_offset | uint256 | index of first pendingOrder to return | | \_limit | uint256 | index of last pendingOrder to return | ## getTradePendingOrderBlock ```solidity theme={null} function getTradePendingOrderBlock(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType) external view returns (uint256) ``` *Returns the block number of the pending order for a trade (0 = doesn't exist)* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | --------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the trade | | \_orderType | enum ITradingStorage.PendingOrderType | pending order type to check | ## getCounters ```solidity theme={null} function getCounters(address _trader, enum ITradingStorage.CounterType _type) external view returns (struct ITradingStorage.Counter) ``` *Returns the counters of a trader (currentIndex / open count for trades/tradeInfos and pendingOrders mappings)* ### Parameters | Name | Type | Description | | -------- | -------------------------------- | -------------------------------------- | | \_trader | address | address of the trader | | \_type | enum ITradingStorage.CounterType | the counter type (trade/pending order) | ## getCountersForTraders ```solidity theme={null} function getCountersForTraders(address[] _traders, enum ITradingStorage.CounterType _type) external view returns (struct ITradingStorage.Counter[]) ``` *Returns the counters for a list of traders* ### Parameters | Name | Type | Description | | --------- | -------------------------------- | -------------------------------------- | | \_traders | address\[] | the list of traders | | \_type | enum ITradingStorage.CounterType | the counter type (trade/pending order) | ## getGToken ```solidity theme={null} function getGToken(uint8 _collateralIndex) external view returns (address) ``` *Returns the address of the gToken for a collateral stack* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------------------------- | | \_collateralIndex | uint8 | the index of the supported collateral | ## getTradeLiquidationParams ```solidity theme={null} function getTradeLiquidationParams(address _trader, uint32 _index) external view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Returns the liquidation params for a trade* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------------------- | | \_trader | address | address of the trader | | \_index | uint32 | index of the trade for trader | ## getTradesLiquidationParams ```solidity theme={null} function getTradesLiquidationParams(address _trader) external view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Returns all trade liquidation params of open trade/limit/stop orders for a trader* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getAllTradesLiquidationParamsForTraders ```solidity theme={null} function getAllTradesLiquidationParamsForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Returns all trade liquidation params of open trade/limit/stop orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------------------------------- | | \_traders | address\[] | list of traders to return liq params for | | \_offset | uint256 | index of first liq param to return | | \_limit | uint256 | index of last liq param to return | ## getAllTradesLiquidationParams ```solidity theme={null} function getAllTradesLiquidationParams(uint256 _offset, uint256 _limit) external view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Returns all trade liquidation params of open trade/limit/stop orders using a pagination system Calls `getAllTradesLiquidationParamsForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ---------------------------------- | | \_offset | uint256 | index of first liq param to return | | \_limit | uint256 | index of last liq param to return | ## getCurrentContractsVersion ```solidity theme={null} function getCurrentContractsVersion() external pure returns (enum ITradingStorage.ContractsVersion) ``` *Returns the current contracts version* # GNSTriggerRewards Source: https://docs.gains.trade/developer/technical-reference/contracts/core/facets/gnstriggerrewards *Facet #6: Trigger rewards* ## constructor ```solidity theme={null} constructor() public ``` ## initializeTriggerRewards ```solidity theme={null} function initializeTriggerRewards(uint16 _timeoutBlocks) external ``` *Initializes parameters for trigger rewards facet* ### Parameters | Name | Type | Description | | --------------- | ------ | -------------------------------------- | | \_timeoutBlocks | uint16 | blocks after which a trigger times out | ## updateTriggerTimeoutBlocks ```solidity theme={null} function updateTriggerTimeoutBlocks(uint16 _timeoutBlocks) external ``` *Updates the blocks after which a trigger times out* ### Parameters | Name | Type | Description | | --------------- | ------ | -------------------------------------- | | \_timeoutBlocks | uint16 | blocks after which a trigger times out | ## distributeTriggerReward ```solidity theme={null} function distributeTriggerReward(uint256 _rewardGns) external virtual ``` *Distributes GNS rewards to oracles for a specific trigger* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------------------------------------ | | \_rewardGns | uint256 | total GNS reward to be distributed among oracles | ## claimPendingTriggerRewards ```solidity theme={null} function claimPendingTriggerRewards(address _oracle) external ``` *Claims pending GNS trigger rewards for the caller* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_oracle | address | address of the oracle | ## getTriggerTimeoutBlocks ```solidity theme={null} function getTriggerTimeoutBlocks() external view returns (uint16) ``` *Returns current triggerTimeoutBlocks value* ## hasActiveOrder ```solidity theme={null} function hasActiveOrder(uint256 _orderBlock) external view returns (bool) ``` *Checks if an order is active (exists and has not timed out)* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------- | | \_orderBlock | uint256 | block number of the order | ## getTriggerPendingRewardsGns ```solidity theme={null} function getTriggerPendingRewardsGns(address _oracle) external view returns (uint256) ``` *Returns the pending GNS trigger rewards for an oracle* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_oracle | address | address of the oracle | # GNSMultiCollatDiamond Source: https://docs.gains.trade/developer/technical-reference/contracts/core/gnsmulticollatdiamond *Diamond that contains all code for the Gains leverage trading platform* [Download file](/images/hJFnQOm8d3mjVbW14zgc-gnsmulticollatdiamond.json) **Please refer to the Facets section in the sidebar for the list of facets and the functions they support.** \ **Essential Diamond facets like DiamondCut, Loupe and other Access-Control related facets can be found in the Abstract section** # GNSStaking Source: https://docs.gains.trade/developer/technical-reference/contracts/core/gnsstaking *Staking contract for GNS token to earn in multiple reward tokens from fees generated on Gains.* ## gns ```solidity theme={null} contract IERC20 gns ``` ## dai ```solidity theme={null} contract IERC20 dai ``` ## accDaiPerToken ```solidity theme={null} uint128 accDaiPerToken ``` ## gnsBalance ```solidity theme={null} uint128 gnsBalance ``` ## stakers ```solidity theme={null} mapping(address => struct IGNSStaking.Staker) stakers ``` ## unlockManagers ```solidity theme={null} mapping(address => bool) unlockManagers ``` ## rewardTokens ```solidity theme={null} address[] rewardTokens ``` ## rewardTokenState ```solidity theme={null} mapping(address => struct IGNSStaking.RewardState) rewardTokenState ``` ## userTokenRewards ```solidity theme={null} mapping(address => mapping(address => struct IGNSStaking.RewardInfo)) userTokenRewards ``` ## userTokenUnlockRewards ```solidity theme={null} mapping(address => mapping(address => mapping(uint256 => struct IGNSStaking.RewardInfo))) userTokenUnlockRewards ``` ## stakerInfos ```solidity theme={null} mapping(address => struct IGNSStaking.StakerInfo) stakerInfos ``` ## constructor ```solidity theme={null} constructor() public ``` ## initialize ```solidity theme={null} function initialize(address _owner, contract IERC20 _gns, contract IERC20 _dai) external ``` *Sets `owner` and initializes `dai` and `gns` state variables* ## initializeV2 ```solidity theme={null} function initializeV2() external ``` *Add `dai` as a reward token (old stakers.debtDai, unlockSchedules.debtDai and accDaiPerToken are deprecacted now) Necessary to call right after contract is updated because otherwise distributeRewardDai() reverts.* ## onlyAuthorizedUnlockManager ```solidity theme={null} modifier onlyAuthorizedUnlockManager(address _staker, bool _revocable) ``` *Modifier used for vest creation access control. Users can create non-revocable vests for themselves only, `owner` and `unlockManagers` can create both types for anyone.* ## onlyRewardToken ```solidity theme={null} modifier onlyRewardToken(address _token) ``` *Modifier to reject any `_token` not configured as a reward token* ## notInCooldown ```solidity theme={null} modifier notInCooldown() ``` *Modifier to ensure operation is not performed before cooldown period has expired* ## setUnlockManager ```solidity theme={null} function setUnlockManager(address _manager, bool _authorized) external ``` \_Sets whether `_manager` is `_authorized` to create vests for other users. Emits \{UnlockManagerUpdated}\_ ## addRewardToken ```solidity theme={null} function addRewardToken(address _token) external ``` \_Forwards call to \{*addRewardToken}. Only callable by `owner`.* ## setDelegatee ```solidity theme={null} function setDelegatee(address _token, address _delegatee) external ``` *Attempts to set the delegatee of `_token` to `_delegatee`. `_token` must be a valid reward token.* ## unlockedGns ```solidity theme={null} function unlockedGns(struct IGNSStaking.UnlockSchedule _schedule, uint48 _timestamp) public pure returns (uint128) ``` *Returns the unlocked GNS tokens amount of `_schedule` at `_timestamp`. Includes already claimed GNS tokens.* ## releasableGns ```solidity theme={null} function releasableGns(struct IGNSStaking.UnlockSchedule _schedule, uint48 _timestamp) public pure returns (uint128) ``` *Returns the releasable GNS tokens amount (1e18 precision) of `_schedule` at `_timestamp`. Doesn't include already claimed GNS tokens.* ## owner ```solidity theme={null} function owner() public view returns (address) ``` *Returns the owner of the contract.* ## isRewardToken ```solidity theme={null} function isRewardToken(address _token) public view returns (bool) ``` *Returns whether `_token` is a listed reward token.* ## distributeReward ```solidity theme={null} function distributeReward(address _token, uint256 _amountToken) external ``` \_Transfers `_amountToken` of `_token` (valid reward token) from caller to this contract and updates `accRewardPerGns`. Note: `accRewardPerGns` is normalized to 1e18 for all reward tokens (even those with less than 18 decimals) Emits \{RewardDistributed}\_ ## harvestToken ```solidity theme={null} function harvestToken(address _token) public returns (uint128) ``` *Harvests the caller's regular pending `_token` rewards. `_token` must be a valid reward token.* ## harvestTokenFromUnlock ```solidity theme={null} function harvestTokenFromUnlock(address _token, uint256[] _ids) public returns (uint128) ``` *Harvests the caller's pending `_token` rewards for vests `_ids`. `_token` must be a valid reward token.* ## harvestTokenAll ```solidity theme={null} function harvestTokenAll(address _token, uint256[] _ids) public returns (uint128) ``` *Harvests the caller's regular pending `_token` rewards and pending rewards for vests `_ids`.* ## harvestTokens ```solidity theme={null} function harvestTokens() public ``` *Harvests the caller's regular pending rewards for all supported reward tokens.* ## harvestTokensFromUnlock ```solidity theme={null} function harvestTokensFromUnlock(uint256[] _ids) public ``` *Harvests the caller's pending rewards of vests `_ids` for all supported reward tokens.* ## harvestTokensAll ```solidity theme={null} function harvestTokensAll(uint256[] _ids) public ``` *Harvests the caller's regular pending rewards and pending rewards of vests `_ids` for all supported reward tokens.* ## compoundGnsRewards ```solidity theme={null} function compoundGnsRewards(uint256[] _ids) external ``` *Harvests the caller's GNS pending rewards and then stakes them* ## harvestDai ```solidity theme={null} function harvestDai() public ``` *Harvests caller's old regular dai rewards.* ## harvestDaiFromUnlock ```solidity theme={null} function harvestDaiFromUnlock(uint256[] _ids) public ``` *Harvests caller's old dai rewards for vests `_ids`.* ## harvestDaiAll ```solidity theme={null} function harvestDaiAll(uint256[] _ids) public ``` *Harvests caller's old regular dai rewards and old dai rewards of vests `_ids`.* ## harvestAll ```solidity theme={null} function harvestAll(uint256[] _ids) external ``` *Harvests the caller's regular pending rewards and pending rewards for vests `_ids` for all supported reward tokens (+ old DAI rewards).* ## stakeGns ```solidity theme={null} function stakeGns(uint128 _amountGns) public ``` \_Stakes non-vested `_amountGns` from caller. Emits \{GnsStaked}\_ ## unstakeGns ```solidity theme={null} function unstakeGns(uint128 _amountGns) external ``` \_Unstakes non-vested `_amountGns` from caller. Emits \{GnsUnstaked}\_ ## claimUnlockedGns ```solidity theme={null} function claimUnlockedGns(uint256[] _ids) external ``` *Claims caller's unlocked GNS from vests `_ids`.* ## createUnlockSchedule ```solidity theme={null} function createUnlockSchedule(struct IGNSStaking.UnlockScheduleInput _schedule, address _staker) external ``` \_Creates vest for `_staker` given `_schedule` input parameters. Restricted with onlyAuthorizedUnlockManager access control. Emits \{UnlockScheduled}\_ ## revokeUnlockSchedule ```solidity theme={null} function revokeUnlockSchedule(address _staker, uint256 _id) external ``` \_Revokes vest `_id` for `_staker`. Sends the unlocked GNS to `_staker` and sends the remaining locked GNS to `owner`. Only callable by `owner`. Emits \{UnlockScheduleRevoked}\_ ## pendingRewardToken ```solidity theme={null} function pendingRewardToken(address _staker, address _token) public view returns (uint128) ``` *Returns the pending `_token` rewards (precision depends on token) for `_staker`.* ## pendingRewardTokens ```solidity theme={null} function pendingRewardTokens(address _staker) external view returns (uint128[] pendingTokens) ``` *Returns an array of `_staker`'s pending rewards (precision depends on token) for all supported tokens.* ## pendingRewardTokensFromUnlocks ```solidity theme={null} function pendingRewardTokensFromUnlocks(address _staker, uint256[] _ids) external view returns (uint128[] pendingTokens) ``` *Returns an array of `_staker`'s pending rewards (precision depends on token) from vests `_ids` for all supported tokens.* ## pendingRewardDai ```solidity theme={null} function pendingRewardDai(address _staker) external view returns (uint128) ``` *Returns `_staker`'s pending old dai rewards (1e18 precision).* ## pendingRewardDaiFromUnlocks ```solidity theme={null} function pendingRewardDaiFromUnlocks(address _staker, uint256[] _ids) external view returns (uint128 pending) ``` *Returns `_staker`'s pending old dai rewards (1e18 precision) from vests `_ids`.* ## totalGnsStaked ```solidity theme={null} function totalGnsStaked(address _staker) external view returns (uint128) ``` *Returns `_staker's` total non-vested and vested GNS staked (1e18 precision)* ## getUnlockSchedules ```solidity theme={null} function getUnlockSchedules(address _staker) external view returns (struct IGNSStaking.UnlockSchedule[]) ``` *Returns all `_staker's` vests.* ## getUnlockSchedules ```solidity theme={null} function getUnlockSchedules(address _staker, uint256 _index) external view returns (struct IGNSStaking.UnlockSchedule) ``` *Returns `_staker's` vest at `_index'`* ## getRewardTokens ```solidity theme={null} function getRewardTokens() external view returns (address[]) ``` *Returns the address of all supported reward tokens* # GToken Source: https://docs.gains.trade/developer/technical-reference/contracts/core/gtoken *GToken vault contract, direct counterparty to trades happening on Gains* ## gnsToken ```solidity theme={null} address gnsToken ``` ## lockedDepositNft ```solidity theme={null} contract IGTokenLockedDepositNft lockedDepositNft ``` ## manager ```solidity theme={null} address manager ``` ## admin ```solidity theme={null} address admin ``` ## pnlHandler ```solidity theme={null} address pnlHandler ``` ## openTradesPnlFeed ```solidity theme={null} contract IGTokenOpenPnlFeed openTradesPnlFeed ``` ## gnsPriceProvider ```solidity theme={null} struct IGToken.GnsPriceProvider gnsPriceProvider ``` ## PRECISION\_18 ```solidity theme={null} uint256 PRECISION_18 ``` ## PRECISION\_10 ```solidity theme={null} uint256 PRECISION_10 ``` ## MIN\_DAILY\_ACC\_PNL\_DELTA ```solidity theme={null} uint256 MIN_DAILY_ACC_PNL_DELTA ``` ## MAX\_SUPPLY\_INCREASE\_DAILY\_P ```solidity theme={null} uint256 MAX_SUPPLY_INCREASE_DAILY_P ``` ## MAX\_LOSSES\_BURN\_P ```solidity theme={null} uint256 MAX_LOSSES_BURN_P ``` ## MAX\_GNS\_SUPPLY\_MINT\_DAILY\_P ```solidity theme={null} uint256 MAX_GNS_SUPPLY_MINT_DAILY_P ``` ## MAX\_DISCOUNT\_P ```solidity theme={null} uint256 MAX_DISCOUNT_P ``` ## MIN\_LOCK\_DURATION ```solidity theme={null} uint256 MIN_LOCK_DURATION ``` ## MAX\_LOCK\_DURATION ```solidity theme={null} uint256 MAX_LOCK_DURATION ``` ## WITHDRAW\_EPOCHS\_LOCKS ```solidity theme={null} uint256[] WITHDRAW_EPOCHS_LOCKS ``` ## maxAccOpenPnlDelta ```solidity theme={null} uint256 maxAccOpenPnlDelta ``` ## maxDailyAccPnlDelta ```solidity theme={null} uint256 maxDailyAccPnlDelta ``` ## withdrawLockThresholdsP ```solidity theme={null} uint256[2] withdrawLockThresholdsP ``` ## maxSupplyIncreaseDailyP ```solidity theme={null} uint256 maxSupplyIncreaseDailyP ``` ## lossesBurnP ```solidity theme={null} uint256 lossesBurnP ``` ## maxGnsSupplyMintDailyP ```solidity theme={null} uint256 maxGnsSupplyMintDailyP ``` ## maxDiscountP ```solidity theme={null} uint256 maxDiscountP ``` ## maxDiscountThresholdP ```solidity theme={null} uint256 maxDiscountThresholdP ``` ## shareToAssetsPrice ```solidity theme={null} uint256 shareToAssetsPrice ``` ## accPnlPerTokenUsed ```solidity theme={null} int256 accPnlPerTokenUsed ``` ## accPnlPerToken ```solidity theme={null} int256 accPnlPerToken ``` ## accRewardsPerToken ```solidity theme={null} uint256 accRewardsPerToken ``` ## dailyAccPnlDelta ```solidity theme={null} int256 dailyAccPnlDelta ``` ## lastDailyAccPnlDeltaReset ```solidity theme={null} uint256 lastDailyAccPnlDeltaReset ``` ## currentEpoch ```solidity theme={null} uint256 currentEpoch ``` ## currentEpochStart ```solidity theme={null} uint256 currentEpochStart ``` ## currentEpochPositiveOpenPnl ```solidity theme={null} uint256 currentEpochPositiveOpenPnl ``` ## currentMaxSupply ```solidity theme={null} uint256 currentMaxSupply ``` ## lastMaxSupplyUpdate ```solidity theme={null} uint256 lastMaxSupplyUpdate ``` ## withdrawRequests ```solidity theme={null} mapping(address => mapping(uint256 => uint256)) withdrawRequests ``` ## lockedDepositsCount ```solidity theme={null} uint256 lockedDepositsCount ``` ## lockedDeposits ```solidity theme={null} mapping(uint256 => struct IGToken.LockedDeposit) lockedDeposits ``` ## assetsToDeplete ```solidity theme={null} uint256 assetsToDeplete ``` ## dailyMintedGns ```solidity theme={null} uint256 dailyMintedGns ``` ## lastDailyMintedGnsReset ```solidity theme={null} uint256 lastDailyMintedGnsReset ``` ## totalDeposited ```solidity theme={null} uint256 totalDeposited ``` ## totalClosedPnl ```solidity theme={null} int256 totalClosedPnl ``` ## totalRewards ```solidity theme={null} uint256 totalRewards ``` ## totalLiability ```solidity theme={null} int256 totalLiability ``` ## totalLockedDiscounts ```solidity theme={null} uint256 totalLockedDiscounts ``` ## totalDiscounts ```solidity theme={null} uint256 totalDiscounts ``` ## totalDepleted ```solidity theme={null} uint256 totalDepleted ``` ## totalDepletedGns ```solidity theme={null} uint256 totalDepletedGns ``` ## totalRefilled ```solidity theme={null} uint256 totalRefilled ``` ## totalRefilledGns ```solidity theme={null} uint256 totalRefilledGns ``` ## accBlockWeightedMarketCap ```solidity theme={null} uint256 accBlockWeightedMarketCap ``` ## accBlockWeightedMarketCapLastStored ```solidity theme={null} uint256 accBlockWeightedMarketCapLastStored ``` ## collateralConfig ```solidity theme={null} struct CollateralUtils.CollateralConfig collateralConfig ``` ## initialize ```solidity theme={null} function initialize(struct IGToken.Meta _meta, struct IGToken.ContractAddresses _contractAddresses, uint256 _MIN_LOCK_DURATION, uint256 _maxAccOpenPnlDelta, uint256 _maxDailyAccPnlDelta, uint256[2] _withdrawLockThresholdsP, uint256 _maxSupplyIncreaseDailyP, uint256 _lossesBurnP, uint256 _maxGnsSupplyMintDailyP, uint256 _maxDiscountP, uint256 _maxDiscountThresholdP) external ``` ## initializeV3 ```solidity theme={null} function initializeV3() external ``` ## onlyManager ```solidity theme={null} modifier onlyManager() ``` ## checks ```solidity theme={null} modifier checks(uint256 assetsOrShares) ``` ## validDiscount ```solidity theme={null} modifier validDiscount(uint256 lockDuration) ``` ## transferOwnership ```solidity theme={null} function transferOwnership(address newOwner) public ``` *Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.* ## updateManager ```solidity theme={null} function updateManager(address newValue) external ``` ## updateAdmin ```solidity theme={null} function updateAdmin(address newValue) external ``` ## updatePnlHandler ```solidity theme={null} function updatePnlHandler(address newValue) external ``` ## updateGnsPriceProvider ```solidity theme={null} function updateGnsPriceProvider(struct IGToken.GnsPriceProvider newValue) external ``` ## updateOpenTradesPnlFeed ```solidity theme={null} function updateOpenTradesPnlFeed(address newValue) external ``` ## updateDelegatee ```solidity theme={null} function updateDelegatee(address _delegatee) external ``` ## updateMaxAccOpenPnlDelta ```solidity theme={null} function updateMaxAccOpenPnlDelta(uint256 newValue) external ``` ## updateMaxDailyAccPnlDelta ```solidity theme={null} function updateMaxDailyAccPnlDelta(uint256 newValue) external ``` ## updateWithdrawLockThresholdsP ```solidity theme={null} function updateWithdrawLockThresholdsP(uint256[2] newValue) external ``` ## updateMaxSupplyIncreaseDailyP ```solidity theme={null} function updateMaxSupplyIncreaseDailyP(uint256 newValue) external ``` ## updateLossesBurnP ```solidity theme={null} function updateLossesBurnP(uint256 newValue) external ``` ## updateMaxGnsSupplyMintDailyP ```solidity theme={null} function updateMaxGnsSupplyMintDailyP(uint256 newValue) external ``` ## updateMaxDiscountP ```solidity theme={null} function updateMaxDiscountP(uint256 newValue) external ``` ## updateMaxDiscountThresholdP ```solidity theme={null} function updateMaxDiscountThresholdP(uint256 newValue) external ``` ## maxAccPnlPerToken ```solidity theme={null} function maxAccPnlPerToken() public view returns (uint256) ``` ## collateralizationP ```solidity theme={null} function collateralizationP() public view returns (uint256) ``` ## gnsTokenToAssetsPrice ```solidity theme={null} function gnsTokenToAssetsPrice() public view returns (uint256 price) ``` ## withdrawEpochsTimelock ```solidity theme={null} function withdrawEpochsTimelock() public view returns (uint256) ``` ## lockDiscountP ```solidity theme={null} function lockDiscountP(uint256 collatP, uint256 lockDuration) public view returns (uint256) ``` ## totalSharesBeingWithdrawn ```solidity theme={null} function totalSharesBeingWithdrawn(address owner) public view returns (uint256 shares) ``` ## tryUpdateCurrentMaxSupply ```solidity theme={null} function tryUpdateCurrentMaxSupply() public ``` ## tryResetDailyAccPnlDelta ```solidity theme={null} function tryResetDailyAccPnlDelta() public ``` ## tryNewOpenPnlRequestOrEpoch ```solidity theme={null} function tryNewOpenPnlRequestOrEpoch() public ``` ## transfer ```solidity theme={null} function transfer(address to, uint256 amount) public returns (bool) ``` ## transferFrom ```solidity theme={null} function transferFrom(address from, address to, uint256 amount) public returns (bool) ``` ## decimals ```solidity theme={null} function decimals() public view returns (uint8) ``` ## \_convertToShares ```solidity theme={null} function _convertToShares(uint256 assets, enum MathUpgradeable.Rounding rounding) internal view returns (uint256 shares) ``` *Internal conversion function (from assets to shares) with support for rounding direction.* ## \_convertToAssets ```solidity theme={null} function _convertToAssets(uint256 shares, enum MathUpgradeable.Rounding rounding) internal view returns (uint256 assets) ``` *Internal conversion function (from shares to assets) with support for rounding direction.* ## maxMint ```solidity theme={null} function maxMint(address) public view returns (uint256) ``` *See \{IERC4626-maxMint}.* ## maxDeposit ```solidity theme={null} function maxDeposit(address owner) public view returns (uint256) ``` ## maxRedeem ```solidity theme={null} function maxRedeem(address owner) public view returns (uint256) ``` *See \{IERC4626-maxRedeem}.* ## maxWithdraw ```solidity theme={null} function maxWithdraw(address owner) public view returns (uint256) ``` *See \{IERC4626-maxWithdraw}.* ## deposit ```solidity theme={null} function deposit(uint256 assets, address receiver) public returns (uint256) ``` *See \{IERC4626-deposit}.* ## mint ```solidity theme={null} function mint(uint256 shares, address receiver) public returns (uint256) ``` \_See \{IERC4626-mint}. As opposed to \{deposit}, minting is allowed even if the vault is in a state where the price of a share is zero. In this case, the shares will be minted without requiring any assets to be deposited.\_ ## withdraw ```solidity theme={null} function withdraw(uint256 assets, address receiver, address owner) public returns (uint256) ``` *See \{IERC4626-withdraw}.* ## redeem ```solidity theme={null} function redeem(uint256 shares, address receiver, address owner) public returns (uint256) ``` *See \{IERC4626-redeem}.* ## makeWithdrawRequest ```solidity theme={null} function makeWithdrawRequest(uint256 shares, address owner) external ``` ## cancelWithdrawRequest ```solidity theme={null} function cancelWithdrawRequest(uint256 shares, address owner, uint256 unlockEpoch) external ``` ## depositWithDiscountAndLock ```solidity theme={null} function depositWithDiscountAndLock(uint256 assets, uint256 lockDuration, address receiver) external returns (uint256) ``` ## mintWithDiscountAndLock ```solidity theme={null} function mintWithDiscountAndLock(uint256 shares, uint256 lockDuration, address receiver) external returns (uint256) ``` ## unlockDeposit ```solidity theme={null} function unlockDeposit(uint256 depositId, address receiver) external ``` ## distributeReward ```solidity theme={null} function distributeReward(uint256 assets) external ``` ## sendAssets ```solidity theme={null} function sendAssets(uint256 assets, address receiver) external ``` ## receiveAssets ```solidity theme={null} function receiveAssets(uint256 assets, address user) external ``` ## deplete ```solidity theme={null} function deplete(uint256 assets) external ``` ## refill ```solidity theme={null} function refill(uint256 assets) external ``` ## updateAccPnlPerTokenUsed ```solidity theme={null} function updateAccPnlPerTokenUsed(uint256 prevPositiveOpenPnl, uint256 newPositiveOpenPnl) external returns (uint256) ``` ## getLockedDeposit ```solidity theme={null} function getLockedDeposit(uint256 depositId) external view returns (struct IGToken.LockedDeposit) ``` ## tvl ```solidity theme={null} function tvl() public view returns (uint256) ``` ## availableAssets ```solidity theme={null} function availableAssets() public view returns (uint256) ``` ## marketCap ```solidity theme={null} function marketCap() public view returns (uint256) ``` # GTokenOpenPnlFeed Source: https://docs.gains.trade/developer/technical-reference/contracts/core/gtokenopenpnlfeed *Manages open pnl oracle requests for a gToken vault* ## LINK\_FEE\_BALANCE\_DIVIDER ```solidity theme={null} uint256 LINK_FEE_BALANCE_DIVIDER ``` ## MIN\_ANSWERS ```solidity theme={null} uint256 MIN_ANSWERS ``` ## MIN\_REQUESTS\_START ```solidity theme={null} uint256 MIN_REQUESTS_START ``` ## MAX\_REQUESTS\_START ```solidity theme={null} uint256 MAX_REQUESTS_START ``` ## MIN\_REQUESTS\_EVERY ```solidity theme={null} uint256 MIN_REQUESTS_EVERY ``` ## MAX\_REQUESTS\_EVERY ```solidity theme={null} uint256 MAX_REQUESTS_EVERY ``` ## MIN\_REQUESTS\_COUNT ```solidity theme={null} uint256 MIN_REQUESTS_COUNT ``` ## MAX\_REQUESTS\_COUNT ```solidity theme={null} uint256 MAX_REQUESTS_COUNT ``` ## gToken ```solidity theme={null} contract IGToken gToken ``` ## requestsStart ```solidity theme={null} uint256 requestsStart ``` ## requestsEvery ```solidity theme={null} uint256 requestsEvery ``` ## requestsCount ```solidity theme={null} uint256 requestsCount ``` ## oracles ```solidity theme={null} address[] oracles ``` ## job ```solidity theme={null} bytes32 job ``` ## minAnswers ```solidity theme={null} uint256 minAnswers ``` ## nextEpochValues ```solidity theme={null} int256[] nextEpochValues ``` ## nextEpochValuesRequestCount ```solidity theme={null} uint256 nextEpochValuesRequestCount ``` ## nextEpochValuesLastRequest ```solidity theme={null} uint256 nextEpochValuesLastRequest ``` ## lastRequestId ```solidity theme={null} uint256 lastRequestId ``` ## requestIds ```solidity theme={null} mapping(bytes32 => uint256) requestIds ``` ## requests ```solidity theme={null} mapping(uint256 => struct IGTokenOpenPnlFeed.Request) requests ``` ## requestAnswers ```solidity theme={null} mapping(uint256 => int256[]) requestAnswers ``` ## constructor ```solidity theme={null} constructor(uint256 _LINK_FEE_BALANCE_DIVIDER, address _linkToken, contract IGToken _gToken, address[] _oracles, bytes32 _job, uint256 _minAnswers) public ``` ## onlyGTokenOwner ```solidity theme={null} modifier onlyGTokenOwner() ``` ## onlyGTokenManager ```solidity theme={null} modifier onlyGTokenManager() ``` ## onlyGTokenAdmin ```solidity theme={null} modifier onlyGTokenAdmin() ``` ## updateRequestsStart ```solidity theme={null} function updateRequestsStart(uint256 newValue) public ``` ## updateRequestsEvery ```solidity theme={null} function updateRequestsEvery(uint256 newValue) public ``` ## updateRequestsCount ```solidity theme={null} function updateRequestsCount(uint256 newValue) public ``` ## updateRequestsInfoBatch ```solidity theme={null} function updateRequestsInfoBatch(uint256 newRequestsStart, uint256 newRequestsEvery, uint256 newRequestsCount) external ``` ## updateMinAnswers ```solidity theme={null} function updateMinAnswers(uint256 newValue) external ``` ## updateOracle ```solidity theme={null} function updateOracle(uint256 _index, address newValue) external ``` ## updateOracles ```solidity theme={null} function updateOracles(address[] newValues) external ``` ## updateJob ```solidity theme={null} function updateJob(bytes32 newValue) external ``` ## resetNextEpochValueRequests ```solidity theme={null} function resetNextEpochValueRequests() external ``` ## forceNewEpoch ```solidity theme={null} function forceNewEpoch() external ``` ## newOpenPnlRequestOrEpoch ```solidity theme={null} function newOpenPnlRequestOrEpoch() external ``` ## fulfill ```solidity theme={null} function fulfill(bytes32 requestId, int256 value) external ``` # IArbSys Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/iarbsys *Interface for Arbitrum special l2 functions* ## arbBlockNumber ```solidity theme={null} function arbBlockNumber() external view returns (uint256) ``` # IChainlinkFeed Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ichainlinkfeed *Interface for Chainlink feeds* ## latestRoundData ```solidity theme={null} function latestRoundData() external view returns (uint80, int256, uint256, uint256, uint80) ``` ## decimals ```solidity theme={null} function decimals() external view returns (uint8) ``` # IChainlinkOracle Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ichainlinkoracle *Interface for chainlink oracles* ## getAuthorizationStatus ```solidity theme={null} function getAuthorizationStatus(address) external view returns (bool) ``` ## owner ```solidity theme={null} function owner() external view returns (address) ``` # IERC20 Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ierc20 *Interface for ERC20 tokens* ## burn ```solidity theme={null} function burn(address, uint256) external ``` ## mint ```solidity theme={null} function mint(address, uint256) external ``` ## hasRole ```solidity theme={null} function hasRole(bytes32, address) external view returns (bool) ``` ## deposit ```solidity theme={null} function deposit() external payable ``` # IERC721 Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ierc721 *Interface for ERC721 tokens* ## balanceOf ```solidity theme={null} function balanceOf(address) external view returns (uint256) ``` ## ownerOf ```solidity theme={null} function ownerOf(uint256) external view returns (address) ``` ## transferFrom ```solidity theme={null} function transferFrom(address, address, uint256) external ``` ## tokenOfOwnerByIndex ```solidity theme={null} function tokenOfOwnerByIndex(address, uint256) external view returns (uint256) ``` # IERC721Design Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ierc721design *Interface for ERC721 token designs* ## buildTokenURI ```solidity theme={null} function buildTokenURI(uint256 nftType, uint256 tokenId) external pure returns (string) ``` # IGeneralErrors Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/igeneralerrors *Interface for errors potentially used in all libraries (general names)* ## InitError ```solidity theme={null} error InitError() ``` ## InvalidAddresses ```solidity theme={null} error InvalidAddresses() ``` ## InvalidInputLength ```solidity theme={null} error InvalidInputLength() ``` ## InvalidCollateralIndex ```solidity theme={null} error InvalidCollateralIndex() ``` ## WrongParams ```solidity theme={null} error WrongParams() ``` ## WrongLength ```solidity theme={null} error WrongLength() ``` ## WrongOrder ```solidity theme={null} error WrongOrder() ``` ## WrongIndex ```solidity theme={null} error WrongIndex() ``` ## BlockOrder ```solidity theme={null} error BlockOrder() ``` ## Overflow ```solidity theme={null} error Overflow() ``` ## ZeroAddress ```solidity theme={null} error ZeroAddress() ``` ## ZeroValue ```solidity theme={null} error ZeroValue() ``` ## AlreadyExists ```solidity theme={null} error AlreadyExists() ``` ## DoesntExist ```solidity theme={null} error DoesntExist() ``` ## Paused ```solidity theme={null} error Paused() ``` ## BelowMin ```solidity theme={null} error BelowMin() ``` ## AboveMax ```solidity theme={null} error AboveMax() ``` ## NotAuthorized ```solidity theme={null} error NotAuthorized() ``` ## WrongTradeType ```solidity theme={null} error WrongTradeType() ``` ## WrongOrderType ```solidity theme={null} error WrongOrderType() ``` ## InsufficientBalance ```solidity theme={null} error InsufficientBalance() ``` # IGNSAddressStore Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ignsaddressstore *Interface for AddressStoreUtils library* ## initialize ```solidity theme={null} function initialize(address _rolesManager) external ``` *Initializes address store facet* ### Parameters | Name | Type | Description | | -------------- | ------- | --------------------- | | \_rolesManager | address | roles manager address | ## getAddresses ```solidity theme={null} function getAddresses() external view returns (struct IAddressStore.Addresses) ``` *Returns addresses current values* ## hasRole ```solidity theme={null} function hasRole(address _account, enum IAddressStore.Role _role) external view returns (bool) ``` *Returns whether an account has been granted a particular role* ### Parameters | Name | Type | Description | | --------- | ----------------------- | ------------------------ | | \_account | address | account address to check | | \_role | enum IAddressStore.Role | role to check | ## setRoles ```solidity theme={null} function setRoles(address[] _accounts, enum IAddressStore.Role[] _roles, bool[] _values) external ``` *Updates access control for a list of accounts* ### Parameters | Name | Type | Description | | ---------- | -------------------------- | ------------------------------- | | \_accounts | address\[] | accounts addresses to update | | \_roles | enum IAddressStore.Role\[] | corresponding roles to update | | \_values | bool\[] | corresponding new values to set | ## AddressesUpdated ```solidity theme={null} event AddressesUpdated(struct IAddressStore.Addresses addresses) ``` *Emitted when addresses are updated* ### Parameters | Name | Type | Description | | --------- | ------------------------------ | -------------------- | | addresses | struct IAddressStore.Addresses | new addresses values | ## AccessControlUpdated ```solidity theme={null} event AccessControlUpdated(address target, enum IAddressStore.Role role, bool access) ``` *Emitted when access control is updated for an account* ### Parameters | Name | Type | Description | | ------ | ----------------------- | ---------------------------------- | | target | address | account address to update | | role | enum IAddressStore.Role | role to update | | access | bool | whether role is granted or revoked | ## NotAllowed ```solidity theme={null} error NotAllowed() ``` ## WrongAccess ```solidity theme={null} error WrongAccess() ``` # IGNSDiamond Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ignsdiamond *the non-expanded interface for multi-collat diamond, only contains types/structs/enums* # IGNSDiamondCut Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ignsdiamondcut *Based on EIP-2535: Diamonds ([https://eips.ethereum.org/EIPS/eip-2535](https://eips.ethereum.org/EIPS/eip-2535)) Follows diamond-3 implementation ([https://github.com/mudgen/diamond-3-hardhat/](https://github.com/mudgen/diamond-3-hardhat/)) One of the diamond standard interfaces, used for diamond management.* ## diamondCut ```solidity theme={null} function diamondCut(struct IDiamondStorage.FacetCut[] _diamondCut, address _init, bytes _calldata) external ``` Add/replace/remove any number of functions and optionally execute a function with delegatecall ### Parameters | Name | Type | Description | | ------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | | \_diamondCut | [IDiamondStorage.FacetCut\[\]](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#facetcut) | Contains the facet addresses and function selectors | | \_init | address | The address of the contract or facet to execute \_calldata | | \_calldata | bytes | A function call, including function selector and arguments \_calldata is executed with delegatecall on \_init | ## DiamondCut ```solidity theme={null} event DiamondCut(struct IDiamondStorage.FacetCut[] _diamondCut, address _init, bytes _calldata) ``` *Emitted when function selectors of a facet of the diamond is added, replaced, or removed* ### Parameters | Name | Type | Description | | ------------ | ---------------------------------- | ---------------------------------------------------------------------- | | \_diamondCut | struct IDiamondStorage.FacetCut\[] | Contains the update data (facet addresses, action, function selectors) | | \_init | address | The address of the contract or facet to execute \_calldata | | \_calldata | bytes | Function call to execute after the diamond cut | ## InitializationFunctionReverted ```solidity theme={null} error InitializationFunctionReverted(address _initializationContractAddress, bytes _calldata) ``` ## InvalidFacetCutAction ```solidity theme={null} error InvalidFacetCutAction() ``` ## NotContract ```solidity theme={null} error NotContract() ``` ## NotFound ```solidity theme={null} error NotFound() ``` # IGNSDiamondLoupe Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ignsdiamondloupe *Based on EIP-2535: Diamonds ([https://eips.ethereum.org/EIPS/eip-2535](https://eips.ethereum.org/EIPS/eip-2535)) Follows diamond-3 implementation ([https://github.com/mudgen/diamond-3-hardhat/](https://github.com/mudgen/diamond-3-hardhat/)) One of the diamond standard interfaces, used to inspect the diamond like a magnifying glass.* ## Facet These functions are expected to be called frequently by tools. ```solidity theme={null} struct Facet { address facetAddress; bytes4[] functionSelectors; } ``` ## facets ```solidity theme={null} function facets() external view returns (struct IGNSDiamondLoupe.Facet[] facets_) ``` Gets all facet addresses and their four byte function selectors. ### Return Values | Name | Type | Description | | -------- | -------------------------------------------------------------------------------------------------------- | ----------- | | facets\_ | [IGNSDiamondLoupe.Facet\[\]](/developer/technical-reference/contracts/interfaces/ignsdiamondloupe#facet) | Facet | ## facetFunctionSelectors ```solidity theme={null} function facetFunctionSelectors(address _facet) external view returns (bytes4[] facetFunctionSelectors_) ``` Gets all the function selectors supported by a specific facet. ### Parameters | Name | Type | Description | | ------- | ------- | ------------------ | | \_facet | address | The facet address. | ### Return Values | Name | Type | Description | | ------------------------ | --------- | ----------- | | facetFunctionSelectors\_ | bytes4\[] | | ## facetAddresses ```solidity theme={null} function facetAddresses() external view returns (address[] facetAddresses_) ``` Get all the facet addresses used by a diamond. ### Return Values | Name | Type | Description | | ---------------- | ---------- | ----------- | | facetAddresses\_ | address\[] | | ## facetAddress ```solidity theme={null} function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_) ``` Gets the facet that supports the given selector. *If facet is not found return address(0).* ### Parameters | Name | Type | Description | | ------------------ | ------ | ---------------------- | | \_functionSelector | bytes4 | The function selector. | ### Return Values | Name | Type | Description | | -------------- | ------- | ------------------ | | facetAddress\_ | address | The facet address. | # IGNSMultiCollatDiamond Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ignsmulticollatdiamond *Expanded version of multi-collat diamond that includes events and function signatures Technically this interface is virtual since the diamond doesn't directly implement these functions. It only forwards the calls to the facet contracts using delegatecall.* # IGNSStaking Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/ignsstaking *Interface for GNSStaking contract* ## Staker ```solidity theme={null} struct Staker { uint128 stakedGns; uint128 debtDai; } ``` ## StakerInfo ```solidity theme={null} struct StakerInfo { uint48 lastDepositTs; uint208 __placeholder; } ``` ## RewardState ```solidity theme={null} struct RewardState { uint128 accRewardPerGns; uint128 precisionDelta; } ``` ## RewardInfo ```solidity theme={null} struct RewardInfo { uint128 debtToken; uint128 __placeholder; } ``` ## UnlockSchedule ```solidity theme={null} struct UnlockSchedule { uint128 totalGns; uint128 claimedGns; uint128 debtDai; uint48 start; uint48 duration; bool revocable; enum IGNSStaking.UnlockType unlockType; uint16 __placeholder; } ``` ## UnlockScheduleInput ```solidity theme={null} struct UnlockScheduleInput { uint128 totalGns; uint48 start; uint48 duration; bool revocable; enum IGNSStaking.UnlockType unlockType; } ``` ## UnlockType ```solidity theme={null} enum UnlockType { LINEAR, CLIFF } ``` ## owner ```solidity theme={null} function owner() external view returns (address) ``` ## distributeReward ```solidity theme={null} function distributeReward(address _rewardToken, uint256 _amountToken) external ``` ## createUnlockSchedule ```solidity theme={null} function createUnlockSchedule(struct IGNSStaking.UnlockScheduleInput _schedule, address _staker) external ``` ## UnlockManagerUpdated ```solidity theme={null} event UnlockManagerUpdated(address manager, bool authorized) ``` ## DaiHarvested ```solidity theme={null} event DaiHarvested(address staker, uint128 amountDai) ``` ## RewardHarvested ```solidity theme={null} event RewardHarvested(address staker, address token, uint128 amountToken) ``` ## RewardHarvestedFromUnlock ```solidity theme={null} event RewardHarvestedFromUnlock(address staker, address token, bool isOldDai, uint256[] ids, uint128 amountToken) ``` ## RewardDistributed ```solidity theme={null} event RewardDistributed(address token, uint256 amount) ``` ## GnsStaked ```solidity theme={null} event GnsStaked(address staker, uint128 amountGns) ``` ## GnsUnstaked ```solidity theme={null} event GnsUnstaked(address staker, uint128 amountGns) ``` ## GnsClaimed ```solidity theme={null} event GnsClaimed(address staker, uint256[] ids, uint128 amountGns) ``` ## UnlockScheduled ```solidity theme={null} event UnlockScheduled(address staker, uint256 index, struct IGNSStaking.UnlockSchedule schedule) ``` ## UnlockScheduleRevoked ```solidity theme={null} event UnlockScheduleRevoked(address staker, uint256 index) ``` ## RewardTokenAdded ```solidity theme={null} event RewardTokenAdded(address token, uint256 index, uint128 precisionDelta) ``` # IGToken Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/igtoken *Interface for GToken contract* ## GnsPriceProvider ```solidity theme={null} struct GnsPriceProvider { address addr; bytes signature; } ``` ## LockedDeposit ```solidity theme={null} struct LockedDeposit { address owner; uint256 shares; uint256 assetsDeposited; uint256 assetsDiscount; uint256 atTimestamp; uint256 lockDuration; } ``` ## ContractAddresses ```solidity theme={null} struct ContractAddresses { address asset; address owner; address manager; address admin; address gnsToken; address lockedDepositNft; address pnlHandler; address openTradesPnlFeed; struct IGToken.GnsPriceProvider gnsPriceProvider; } ``` ## Meta ```solidity theme={null} struct Meta { string name; string symbol; } ``` ## manager ```solidity theme={null} function manager() external view returns (address) ``` ## admin ```solidity theme={null} function admin() external view returns (address) ``` ## currentEpoch ```solidity theme={null} function currentEpoch() external view returns (uint256) ``` ## currentEpochStart ```solidity theme={null} function currentEpochStart() external view returns (uint256) ``` ## currentEpochPositiveOpenPnl ```solidity theme={null} function currentEpochPositiveOpenPnl() external view returns (uint256) ``` ## updateAccPnlPerTokenUsed ```solidity theme={null} function updateAccPnlPerTokenUsed(uint256 prevPositiveOpenPnl, uint256 newPositiveOpenPnl) external returns (uint256) ``` ## getLockedDeposit ```solidity theme={null} function getLockedDeposit(uint256 depositId) external view returns (struct IGToken.LockedDeposit) ``` ## sendAssets ```solidity theme={null} function sendAssets(uint256 assets, address receiver) external ``` ## receiveAssets ```solidity theme={null} function receiveAssets(uint256 assets, address user) external ``` ## distributeReward ```solidity theme={null} function distributeReward(uint256 assets) external ``` ## tvl ```solidity theme={null} function tvl() external view returns (uint256) ``` ## marketCap ```solidity theme={null} function marketCap() external view returns (uint256) ``` ## shareToAssetsPrice ```solidity theme={null} function shareToAssetsPrice() external view returns (uint256) ``` ## collateralConfig ```solidity theme={null} function collateralConfig() external view returns (uint128, uint128) ``` ## ManagerUpdated ```solidity theme={null} event ManagerUpdated(address newValue) ``` ## AdminUpdated ```solidity theme={null} event AdminUpdated(address newValue) ``` ## PnlHandlerUpdated ```solidity theme={null} event PnlHandlerUpdated(address newValue) ``` ## OpenTradesPnlFeedUpdated ```solidity theme={null} event OpenTradesPnlFeedUpdated(address newValue) ``` ## GnsPriceProviderUpdated ```solidity theme={null} event GnsPriceProviderUpdated(struct IGToken.GnsPriceProvider newValue) ``` ## WithdrawLockThresholdsPUpdated ```solidity theme={null} event WithdrawLockThresholdsPUpdated(uint256[2] newValue) ``` ## MaxAccOpenPnlDeltaUpdated ```solidity theme={null} event MaxAccOpenPnlDeltaUpdated(uint256 newValue) ``` ## MaxDailyAccPnlDeltaUpdated ```solidity theme={null} event MaxDailyAccPnlDeltaUpdated(uint256 newValue) ``` ## MaxSupplyIncreaseDailyPUpdated ```solidity theme={null} event MaxSupplyIncreaseDailyPUpdated(uint256 newValue) ``` ## LossesBurnPUpdated ```solidity theme={null} event LossesBurnPUpdated(uint256 newValue) ``` ## MaxGnsSupplyMintDailyPUpdated ```solidity theme={null} event MaxGnsSupplyMintDailyPUpdated(uint256 newValue) ``` ## MaxDiscountPUpdated ```solidity theme={null} event MaxDiscountPUpdated(uint256 newValue) ``` ## MaxDiscountThresholdPUpdated ```solidity theme={null} event MaxDiscountThresholdPUpdated(uint256 newValue) ``` ## CurrentMaxSupplyUpdated ```solidity theme={null} event CurrentMaxSupplyUpdated(uint256 newValue) ``` ## DailyAccPnlDeltaReset ```solidity theme={null} event DailyAccPnlDeltaReset() ``` ## ShareToAssetsPriceUpdated ```solidity theme={null} event ShareToAssetsPriceUpdated(uint256 newValue) ``` ## OpenTradesPnlFeedCallFailed ```solidity theme={null} event OpenTradesPnlFeedCallFailed() ``` ## WithdrawRequested ```solidity theme={null} event WithdrawRequested(address sender, address owner, uint256 shares, uint256 currEpoch, uint256 unlockEpoch) ``` ## WithdrawCanceled ```solidity theme={null} event WithdrawCanceled(address sender, address owner, uint256 shares, uint256 currEpoch, uint256 unlockEpoch) ``` ## DepositLocked ```solidity theme={null} event DepositLocked(address sender, address owner, uint256 depositId, struct IGToken.LockedDeposit d) ``` ## DepositUnlocked ```solidity theme={null} event DepositUnlocked(address sender, address receiver, address owner, uint256 depositId, struct IGToken.LockedDeposit d) ``` ## RewardDistributed ```solidity theme={null} event RewardDistributed(address sender, uint256 assets) ``` ## AssetsSent ```solidity theme={null} event AssetsSent(address sender, address receiver, uint256 assets) ``` ## AssetsReceived ```solidity theme={null} event AssetsReceived(address sender, address user, uint256 assets, uint256 assetsLessDeplete) ``` ## Depleted ```solidity theme={null} event Depleted(address sender, uint256 assets, uint256 amountGns) ``` ## Refilled ```solidity theme={null} event Refilled(address sender, uint256 assets, uint256 amountGns) ``` ## AccPnlPerTokenUsedUpdated ```solidity theme={null} event AccPnlPerTokenUsedUpdated(address sender, uint256 newEpoch, uint256 prevPositiveOpenPnl, uint256 newPositiveOpenPnl, uint256 newEpochPositiveOpenPnl, int256 newAccPnlPerTokenUsed) ``` ## OnlyManager ```solidity theme={null} error OnlyManager() ``` ## OnlyTradingPnlHandler ```solidity theme={null} error OnlyTradingPnlHandler() ``` ## OnlyPnlFeed ```solidity theme={null} error OnlyPnlFeed() ``` ## AddressZero ```solidity theme={null} error AddressZero() ``` ## PriceZero ```solidity theme={null} error PriceZero() ``` ## ValueZero ```solidity theme={null} error ValueZero() ``` ## BytesZero ```solidity theme={null} error BytesZero() ``` ## NoActiveDiscount ```solidity theme={null} error NoActiveDiscount() ``` ## BelowMin ```solidity theme={null} error BelowMin() ``` ## AboveMax ```solidity theme={null} error AboveMax() ``` ## WrongValue ```solidity theme={null} error WrongValue() ``` ## WrongValues ```solidity theme={null} error WrongValues() ``` ## GnsPriceCallFailed ```solidity theme={null} error GnsPriceCallFailed() ``` ## GnsTokenPriceZero ```solidity theme={null} error GnsTokenPriceZero() ``` ## PendingWithdrawal ```solidity theme={null} error PendingWithdrawal() ``` ## EndOfEpoch ```solidity theme={null} error EndOfEpoch() ``` ## NotAllowed ```solidity theme={null} error NotAllowed() ``` ## NoDiscount ```solidity theme={null} error NoDiscount() ``` ## NotUnlocked ```solidity theme={null} error NotUnlocked() ``` ## NotEnoughAssets ```solidity theme={null} error NotEnoughAssets() ``` ## MaxDailyPnl ```solidity theme={null} error MaxDailyPnl() ``` ## NotUnderCollateralized ```solidity theme={null} error NotUnderCollateralized() ``` ## AboveInflationLimit ```solidity theme={null} error AboveInflationLimit() ``` ## OwnableInvalidOwner ```solidity theme={null} error OwnableInvalidOwner(address owner) ``` ## ERC4626ExceededMaxDeposit ```solidity theme={null} error ERC4626ExceededMaxDeposit() ``` ## ERC4626ExceededMaxMint ```solidity theme={null} error ERC4626ExceededMaxMint() ``` ## ERC4626ExceededMaxWithdraw ```solidity theme={null} error ERC4626ExceededMaxWithdraw() ``` ## ERC4626ExceededMaxRedeem ```solidity theme={null} error ERC4626ExceededMaxRedeem() ``` # IGTokenLockedDepositNft Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/igtokenlockeddepositnft *Interface for GTokenLockedDepositNft contract* ## mint ```solidity theme={null} function mint(address to, uint256 tokenId) external ``` ## burn ```solidity theme={null} function burn(uint256 tokenId) external ``` ## DesignUpdated ```solidity theme={null} event DesignUpdated(contract IGTokenLockedDepositNftDesign newValue) ``` ## DesignDecimalsUpdated ```solidity theme={null} event DesignDecimalsUpdated(uint8 newValue) ``` # IGTokenLockedDepositNftDesign Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/igtokenlockeddepositnftdesign *Interface for GTokenLockedDepositNftDesign contract* ## buildTokenURI ```solidity theme={null} function buildTokenURI(uint256 tokenId, struct IGToken.LockedDeposit lockedDeposit, string gTokenSymbol, string assetSymbol, uint8 numberInputDecimals, uint8 numberOutputDecimals) external pure returns (string) ``` # IGTokenOpenPnlFeed Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/igtokenopenpnlfeed *Interface for GTokenOpenPnlFeed contract* ## Request ```solidity theme={null} struct Request { bool initiated; bool active; uint256 linkFeePerNode; } ``` ## nextEpochValuesRequestCount ```solidity theme={null} function nextEpochValuesRequestCount() external view returns (uint256) ``` ## newOpenPnlRequestOrEpoch ```solidity theme={null} function newOpenPnlRequestOrEpoch() external ``` ## fulfill ```solidity theme={null} function fulfill(bytes32 requestId, int256 value) external ``` ## NumberParamUpdated ```solidity theme={null} event NumberParamUpdated(string name, uint256 newValue) ``` ## OracleUpdated ```solidity theme={null} event OracleUpdated(uint256 index, address newValue) ``` ## OraclesUpdated ```solidity theme={null} event OraclesUpdated(address[] newValues) ``` ## JobUpdated ```solidity theme={null} event JobUpdated(bytes32 newValue) ``` ## NextEpochValuesReset ```solidity theme={null} event NextEpochValuesReset(uint256 currEpoch, uint256 requestsResetCount) ``` ## NewEpochForced ```solidity theme={null} event NewEpochForced(uint256 newEpoch) ``` ## NextEpochValueRequested ```solidity theme={null} event NextEpochValueRequested(uint256 currEpoch, uint256 requestId, bytes32 job, uint256 oraclesCount, uint256 linkFeePerNode) ``` ## NewEpoch ```solidity theme={null} event NewEpoch(uint256 newEpoch, uint256 requestId, int256[] epochMedianValues, int256 epochAverageValue, uint256 newEpochPositiveOpenPnl) ``` ## RequestValueReceived ```solidity theme={null} event RequestValueReceived(bool isLate, uint256 currEpoch, uint256 requestId, bytes32 oracleRequestId, address oracle, int256 requestValue, uint256 linkFee) ``` ## RequestMedianValueSet ```solidity theme={null} event RequestMedianValueSet(uint256 currEpoch, uint256 requestId, int256[] requestValues, int256 medianValue) ``` # ILiquidityPool Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/iliquiditypool *Generic interface for liquidity pool methods for fetching observations (to calculate TWAP) and other basic information* ## getTimepoints ```solidity theme={null} function getTimepoints(uint32[] secondsAgos) external view returns (int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulatives, uint112[] volatilityCumulatives, uint256[] volumePerAvgLiquiditys) ``` *AlgebraPool V1.9 equivalent of Uniswap V3 `observe` function See [https://github.com/cryptoalgebra/AlgebraV1.9/blob/main/src/core/contracts/interfaces/pool/IAlgebraPoolDerivedState.sol](https://github.com/cryptoalgebra/AlgebraV1.9/blob/main/src/core/contracts/interfaces/pool/IAlgebraPoolDerivedState.sol) for more information* ## observe ```solidity theme={null} function observe(uint32[] secondsAgos) external view returns (int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s) ``` *Uniswap V3 `observe` function See `https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol` for more information* ## token0 ```solidity theme={null} function token0() external view returns (address) ``` The first of the two tokens of the pool, sorted by address ### Return Values | Name | Type | Description | | ---- | ------- | -------------------------- | | \[0] | address | The token contract address | ## token1 ```solidity theme={null} function token1() external view returns (address) ``` The second of the two tokens of the pool, sorted by address ### Return Values | Name | Type | Description | | ---- | ------- | -------------------------- | | \[0] | address | The token contract address | # IOwnable Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/iownable *Interface for ownable contracts* ## owner ```solidity theme={null} function owner() external view returns (address) ``` # IRateProvider Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/irateprovider ## getRate ```solidity theme={null} function getRate() external view returns (uint256) ``` # IBorrowingFeesUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/iborrowingfeesutils *Interface for GNSBorrowingFees facet (inherits types and also contains functions, events, and custom errors)* ## setBorrowingPairParams ```solidity theme={null} function setBorrowingPairParams(uint8 _collateralIndex, uint16 _pairIndex, struct IBorrowingFees.BorrowingPairParams _value) external ``` *Updates borrowing pair params of a pair* ### Parameters | Name | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_value | [IBorrowingFees.BorrowingPairParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new value | ## setBorrowingPairParamsArray ```solidity theme={null} function setBorrowingPairParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingPairParams[] _values) external ``` *Updates borrowing pair params of multiple pairs* ### Parameters | Name | Type | Description | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_indices | uint16\[] | indices of the pairs | | \_values | [IBorrowingFees.BorrowingPairParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new values | ## setBorrowingGroupParams ```solidity theme={null} function setBorrowingGroupParams(uint8 _collateralIndex, uint16 _groupIndex, struct IBorrowingFees.BorrowingGroupParams _value) external ``` *Updates borrowing group params of a group* ### Parameters | Name | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_value | [IBorrowingFees.BorrowingGroupParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new value | ## setBorrowingGroupParamsArray ```solidity theme={null} function setBorrowingGroupParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingGroupParams[] _values) external ``` *Updates borrowing group params of multiple groups* ### Parameters | Name | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_indices | uint16\[] | indices of the groups | | \_values | [IBorrowingFees.BorrowingGroupParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new values | ## handleTradeBorrowingCallback ```solidity theme={null} function handleTradeBorrowingCallback(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, uint256 _positionSizeCollateral, bool _open, bool _long) external ``` *Callback after a trade is opened/closed to store pending borrowing fees and adjust open interests* ### Parameters | Name | Type | Description | | ------------------------ | ------- | ------------------------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_trader | address | address of the trader | | \_pairIndex | uint16 | index of the pair | | \_index | uint32 | index of the trade | | \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens | | \_open | bool | true if trade has been opened, false if trade has been closed | | \_long | bool | true if trade is long, false if trade is short | ## resetTradeBorrowingFees ```solidity theme={null} function resetTradeBorrowingFees(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, bool _long) external ``` *Resets a trade borrowing fee to 0 (useful when new trade opened or when partial trade executed)* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_trader | address | address of the trader | | \_pairIndex | uint16 | index of the pair | | \_index | uint32 | index of the trade | | \_long | bool | true if trade is long, false if trade is short | ## getBorrowingPairPendingAccFees ```solidity theme={null} function getBorrowingPairPendingAccFees(uint8 _collateralIndex, uint16 _pairIndex, uint256 _currentBlock) external view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 pairAccFeeDelta) ``` *Returns the pending acc borrowing fees for a pair on both sides* ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_currentBlock | uint256 | current block number | ### Return Values | Name | Type | Description | | --------------- | ------ | ---------------------------------------------------- | | accFeeLong | uint64 | new pair acc borrowing fee on long side | | accFeeShort | uint64 | new pair acc borrowing fee on short side | | pairAccFeeDelta | uint64 | pair acc borrowing fee delta (for side that changed) | ## getBorrowingGroupPendingAccFees ```solidity theme={null} function getBorrowingGroupPendingAccFees(uint8 _collateralIndex, uint16 _groupIndex, uint256 _currentBlock) external view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 groupAccFeeDelta) ``` *Returns the pending acc borrowing fees for a borrowing group on both sides* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_currentBlock | uint256 | current block number | ### Return Values | Name | Type | Description | | ---------------- | ------ | ----------------------------------------------------- | | accFeeLong | uint64 | new group acc borrowing fee on long side | | accFeeShort | uint64 | new group acc borrowing fee on short side | | groupAccFeeDelta | uint64 | group acc borrowing fee delta (for side that changed) | ## getTradeBorrowingFee ```solidity theme={null} function getTradeBorrowingFee(struct IBorrowingFees.BorrowingFeeInput _input) external view returns (uint256 feeAmountCollateral) ``` *Returns the borrowing fee for a trade* ### Parameters | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | \_input | [IBorrowingFees.BorrowingFeeInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingfeeinput) | input data (collateralIndex, trader, pairIndex, index, long, collateral, leverage) | ### Return Values | Name | Type | Description | | ------------------- | ------- | ------------------------------------ | | feeAmountCollateral | uint256 | borrowing fee (collateral precision) | ## getTradeLiquidationPrice ```solidity theme={null} function getTradeLiquidationPrice(struct IBorrowingFees.LiqPriceInput _input) external view returns (uint256) ``` *Returns the liquidation price for a trade* ### Parameters | Name | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | \_input | [IBorrowingFees.LiqPriceInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#liqpriceinput) | input data (collateralIndex, trader, pairIndex, index, openPrice, long, collateral, leverage) | ## getPairOisCollateral ```solidity theme={null} function getPairOisCollateral(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256 longOi, uint256 shortOi) ``` *Returns the open interests for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ### Return Values | Name | Type | Description | | ------- | ------- | --------------------------- | | longOi | uint256 | open interest on long side | | shortOi | uint256 | open interest on short side | ## getBorrowingPairGroupIndex ```solidity theme={null} function getBorrowingPairGroupIndex(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint16 groupIndex) ``` *Returns the borrowing group index for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ### Return Values | Name | Type | Description | | ---------- | ------ | --------------------- | | groupIndex | uint16 | borrowing group index | ## getPairOiCollateral ```solidity theme={null} function getPairOiCollateral(uint8 _collateralIndex, uint16 _pairIndex, bool _long) external view returns (uint256) ``` *Returns the open interest in collateral tokens for a pair on one side* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_long | bool | true if long side | ## withinMaxBorrowingGroupOi ```solidity theme={null} function withinMaxBorrowingGroupOi(uint8 _collateralIndex, uint16 _pairIndex, bool _long, uint256 _positionSizeCollateral) external view returns (bool) ``` *Returns whether a trade is within the max group borrowing open interest* ### Parameters | Name | Type | Description | | ------------------------ | ------- | ----------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_long | bool | true if long side | | \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens | ## getBorrowingGroup ```solidity theme={null} function getBorrowingGroup(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.BorrowingData group) ``` *Returns a borrowing group's data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | ## getBorrowingGroupOi ```solidity theme={null} function getBorrowingGroupOi(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.OpenInterest group) ``` *Returns a borrowing group's oi data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | ## getBorrowingPair ```solidity theme={null} function getBorrowingPair(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingData) ``` *Returns a borrowing pair's data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getBorrowingPairOi ```solidity theme={null} function getBorrowingPairOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.OpenInterest) ``` *Returns a borrowing pair's oi data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getBorrowingPairGroups ```solidity theme={null} function getBorrowingPairGroups(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingPairGroup[]) ``` *Returns a borrowing pair's oi data* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getAllBorrowingPairs ```solidity theme={null} function getAllBorrowingPairs(uint8 _collateralIndex) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[], struct IBorrowingFees.BorrowingPairGroup[][]) ``` *Returns all borrowing pairs' borrowing data, oi data, and pair groups data* ### Parameters | Name | Type | Description | | ----------------- | ----- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | ## getBorrowingGroups ```solidity theme={null} function getBorrowingGroups(uint8 _collateralIndex, uint16[] _indices) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[]) ``` *Returns borrowing groups' data and oi data* ### Parameters | Name | Type | Description | | ----------------- | --------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_indices | uint16\[] | indices of the groups | ## getBorrowingInitialAccFees ```solidity theme={null} function getBorrowingInitialAccFees(uint8 _collateralIndex, address _trader, uint32 _index) external view returns (struct IBorrowingFees.BorrowingInitialAccFees) ``` *Returns borrowing groups' data* ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_trader | address | address of trader | | \_index | uint32 | index of trade | ## getPairMaxOi ```solidity theme={null} function getPairMaxOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256) ``` *Returns the max open interest for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## getPairMaxOiCollateral ```solidity theme={null} function getPairMaxOiCollateral(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256) ``` *Returns the max open interest in collateral tokens for a pair* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | ## BorrowingPairParamsUpdated ```solidity theme={null} event BorrowingPairParamsUpdated(uint8 collateralIndex, uint16 pairIndex, uint16 groupIndex, uint32 feePerBlock, uint48 feeExponent, uint72 maxOi) ``` *Emitted when a pair's borrowing params is updated* ### Parameters | Name | Type | Description | | --------------- | ------ | ---------------------- | | collateralIndex | uint8 | | | pairIndex | uint16 | index of the pair | | groupIndex | uint16 | index of its new group | | feePerBlock | uint32 | new fee per block | | feeExponent | uint48 | new fee exponent | | maxOi | uint72 | new max open interest | ## BorrowingPairGroupUpdated ```solidity theme={null} event BorrowingPairGroupUpdated(uint8 collateralIndex, uint16 pairIndex, uint16 prevGroupIndex, uint16 newGroupIndex) ``` *Emitted when a pair's borrowing group has been updated* ### Parameters | Name | Type | Description | | --------------- | ------ | ------------------------------ | | collateralIndex | uint8 | | | pairIndex | uint16 | index of the pair | | prevGroupIndex | uint16 | previous borrowing group index | | newGroupIndex | uint16 | new borrowing group index | ## BorrowingGroupUpdated ```solidity theme={null} event BorrowingGroupUpdated(uint8 collateralIndex, uint16 groupIndex, uint32 feePerBlock, uint72 maxOi, uint48 feeExponent) ``` *Emitted when a group's borrowing params is updated* ### Parameters | Name | Type | Description | | --------------- | ------ | --------------------- | | collateralIndex | uint8 | | | groupIndex | uint16 | index of the group | | feePerBlock | uint32 | new fee per block | | maxOi | uint72 | new max open interest | | feeExponent | uint48 | new fee exponent | ## BorrowingInitialAccFeesStored ```solidity theme={null} event BorrowingInitialAccFeesStored(uint8 collateralIndex, address trader, uint16 pairIndex, uint32 index, bool long, uint64 initialPairAccFee, uint64 initialGroupAccFee) ``` *Emitted when a trade's initial acc borrowing fees are stored* ### Parameters | Name | Type | Description | | ------------------ | ------- | ------------------------------------------------- | | collateralIndex | uint8 | | | trader | address | address of the trader | | pairIndex | uint16 | index of the pair | | index | uint32 | index of the trade | | long | bool | | | initialPairAccFee | uint64 | initial pair acc fee (for the side of the trade) | | initialGroupAccFee | uint64 | initial group acc fee (for the side of the trade) | ## TradeBorrowingCallbackHandled ```solidity theme={null} event TradeBorrowingCallbackHandled(uint8 collateralIndex, address trader, uint16 pairIndex, uint32 index, bool open, bool long, uint256 positionSizeCollateral) ``` *Emitted when a trade is executed and borrowing callback is handled* ### Parameters | Name | Type | Description | | ---------------------- | ------- | ------------------------------------------------------------- | | collateralIndex | uint8 | | | trader | address | address of the trader | | pairIndex | uint16 | index of the pair | | index | uint32 | index of the trade | | open | bool | true if trade has been opened, false if trade has been closed | | long | bool | true if trade is long, false if trade is short | | positionSizeCollateral | uint256 | position size of the trade in collateral tokens | ## BorrowingPairAccFeesUpdated ```solidity theme={null} event BorrowingPairAccFeesUpdated(uint8 collateralIndex, uint16 pairIndex, uint256 currentBlock, uint64 accFeeLong, uint64 accFeeShort) ``` *Emitted when a pair's borrowing acc fees are updated* ### Parameters | Name | Type | Description | | --------------- | ------- | ---------------------------------------- | | collateralIndex | uint8 | | | pairIndex | uint16 | index of the pair | | currentBlock | uint256 | current block number | | accFeeLong | uint64 | new pair acc borrowing fee on long side | | accFeeShort | uint64 | new pair acc borrowing fee on short side | ## BorrowingGroupAccFeesUpdated ```solidity theme={null} event BorrowingGroupAccFeesUpdated(uint8 collateralIndex, uint16 groupIndex, uint256 currentBlock, uint64 accFeeLong, uint64 accFeeShort) ``` *Emitted when a group's borrowing acc fees are updated* ### Parameters | Name | Type | Description | | --------------- | ------- | ----------------------------------------- | | collateralIndex | uint8 | | | groupIndex | uint16 | index of the borrowing group | | currentBlock | uint256 | current block number | | accFeeLong | uint64 | new group acc borrowing fee on long side | | accFeeShort | uint64 | new group acc borrowing fee on short side | ## BorrowingPairOiUpdated ```solidity theme={null} event BorrowingPairOiUpdated(uint8 collateralIndex, uint16 pairIndex, bool long, bool increase, uint72 delta, uint72 newOiLong, uint72 newOiShort) ``` *Emitted when a borrowing pair's open interests are updated* ### Parameters | Name | Type | Description | | --------------- | ------ | ------------------------------------------------------------- | | collateralIndex | uint8 | | | pairIndex | uint16 | index of the pair | | long | bool | true if long side | | increase | bool | true if open interest is increased, false if decreased | | delta | uint72 | change in open interest in collateral tokens (1e10 precision) | | newOiLong | uint72 | new open interest on long side | | newOiShort | uint72 | new open interest on short side | ## BorrowingGroupOiUpdated ```solidity theme={null} event BorrowingGroupOiUpdated(uint8 collateralIndex, uint16 groupIndex, bool long, bool increase, uint72 delta, uint72 newOiLong, uint72 newOiShort) ``` *Emitted when a borrowing group's open interests are updated* ### Parameters | Name | Type | Description | | --------------- | ------ | ------------------------------------------------------------- | | collateralIndex | uint8 | | | groupIndex | uint16 | index of the borrowing group | | long | bool | true if long side | | increase | bool | true if open interest is increased, false if decreased | | delta | uint72 | change in open interest in collateral tokens (1e10 precision) | | newOiLong | uint72 | new open interest on long side | | newOiShort | uint72 | new open interest on short side | ## BorrowingZeroGroup ```solidity theme={null} error BorrowingZeroGroup() ``` ## BorrowingWrongExponent ```solidity theme={null} error BorrowingWrongExponent() ``` # IFeeTiersUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/ifeetiersutils *Interface for GNSFeeTiers facet (inherits types and also contains functions, events, and custom errors)* ## initializeFeeTiers ```solidity theme={null} function initializeFeeTiers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers, uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) external ``` ### Parameters | Name | Type | Description | | ------------------------ | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | \_groupIndices | uint256\[] | group indices (pairs storage fee index) to initialize | | \_groupVolumeMultipliers | uint256\[] | corresponding group volume multipliers (1e3) | | \_feeTiersIndices | uint256\[] | fee tiers indices to initialize | | \_feeTiers | [IFeeTiers.FeeTier\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | fee tiers values to initialize (feeMultiplier, pointsThreshold) | ## setGroupVolumeMultipliers ```solidity theme={null} function setGroupVolumeMultipliers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers) external ``` *Updates groups volume multipliers* ### Parameters | Name | Type | Description | | ------------------------ | ---------- | ------------------------------------------ | | \_groupIndices | uint256\[] | indices of groups to update | | \_groupVolumeMultipliers | uint256\[] | corresponding new volume multipliers (1e3) | ## setFeeTiers ```solidity theme={null} function setFeeTiers(uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) external ``` *Updates fee tiers* ### Parameters | Name | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | \_feeTiersIndices | uint256\[] | indices of fee tiers to update | | \_feeTiers | [IFeeTiers.FeeTier\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | new fee tiers values (feeMultiplier, pointsThreshold) | ## setTradersFeeTiersEnrollment ```solidity theme={null} function setTradersFeeTiersEnrollment(address[] _traders, struct IFeeTiers.TraderEnrollment[] _values) external ``` *Updates traders enrollment status in fee tiers* ### Parameters | Name | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------- | | \_traders | address\[] | group of traders | | \_values | [IFeeTiers.TraderEnrollment\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#traderenrollment) | corresponding enrollment values | ## addTradersUnclaimedPoints ```solidity theme={null} function addTradersUnclaimedPoints(address[] _traders, enum IFeeTiers.CreditType[] _creditTypes, uint224[] _points) external ``` *Credits points to traders* ### Parameters | Name | Type | Description | | ------------- | ---------------------------- | -------------------------------------- | | \_traders | address\[] | traders addresses | | \_creditTypes | enum IFeeTiers.CreditType\[] | types of credit (IMMEDIATE, CLAIMABLE) | | \_points | uint224\[] | points to credit (1e18) | ## updateTraderPoints ```solidity theme={null} function updateTraderPoints(address _trader, uint256 _volumeUsd, uint256 _pairIndex) external ``` *Increases daily points from a new trade, re-calculate trailing points, and cache daily fee tier for a trader.* ### Parameters | Name | Type | Description | | ----------- | ------- | ---------------------------- | | \_trader | address | trader address | | \_volumeUsd | uint256 | trading volume in USD (1e18) | | \_pairIndex | uint256 | pair index | ## calculateFeeAmount ```solidity theme={null} function calculateFeeAmount(address _trader, uint256 _normalFeeAmountCollateral) external view returns (uint256) ``` *Returns fee amount after applying the trader's active fee tier multiplier* ### Parameters | Name | Type | Description | | --------------------------- | ------- | -------------------------------------- | | \_trader | address | address of trader | | \_normalFeeAmountCollateral | uint256 | base fee amount (collateral precision) | ## getFeeTiersCount ```solidity theme={null} function getFeeTiersCount() external view returns (uint256) ``` Returns the current number of active fee tiers ## getFeeTier ```solidity theme={null} function getFeeTier(uint256 _feeTierIndex) external view returns (struct IFeeTiers.FeeTier) ``` *Returns a fee tier's details (feeMultiplier, pointsThreshold)* ### Parameters | Name | Type | Description | | -------------- | ------- | -------------- | | \_feeTierIndex | uint256 | fee tier index | ## getGroupVolumeMultiplier ```solidity theme={null} function getGroupVolumeMultiplier(uint256 _groupIndex) external view returns (uint256) ``` *Returns a group's volume multiplier* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------------------- | | \_groupIndex | uint256 | group index (pairs storage fee index) | ## getFeeTiersTraderInfo ```solidity theme={null} function getFeeTiersTraderInfo(address _trader) external view returns (struct IFeeTiers.TraderInfo) ``` *Returns a trader's info (lastDayUpdated, trailingPoints)* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | ## getFeeTiersTraderDailyInfo ```solidity theme={null} function getFeeTiersTraderDailyInfo(address _trader, uint32 _day) external view returns (struct IFeeTiers.TraderDailyInfo) ``` *Returns a trader's daily fee tier info (feeMultiplierCache, points)* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | | \_day | uint32 | day | ## getTraderFeeTiersEnrollment ```solidity theme={null} function getTraderFeeTiersEnrollment(address _trader) external view returns (struct IFeeTiers.TraderEnrollment) ``` *Returns a trader's fee tiers enrollment status* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | ## getTraderUnclaimedPoints ```solidity theme={null} function getTraderUnclaimedPoints(address _trader) external view returns (uint224) ``` *Returns a trader's unclaimed points, credited by Governance* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | ## GroupVolumeMultipliersUpdated ```solidity theme={null} event GroupVolumeMultipliersUpdated(uint256[] groupIndices, uint256[] groupVolumeMultipliers) ``` *Emitted when group volume multipliers are updated* ### Parameters | Name | Type | Description | | ---------------------- | ---------- | ------------------------------------------ | | groupIndices | uint256\[] | indices of updated groups | | groupVolumeMultipliers | uint256\[] | new corresponding volume multipliers (1e3) | ## FeeTiersUpdated ```solidity theme={null} event FeeTiersUpdated(uint256[] feeTiersIndices, struct IFeeTiers.FeeTier[] feeTiers) ``` *Emitted when fee tiers are updated* ### Parameters | Name | Type | Description | | --------------- | --------------------------- | ------------------------------------------------------------------- | | feeTiersIndices | uint256\[] | indices of updated fee tiers | | feeTiers | struct IFeeTiers.FeeTier\[] | new corresponding fee tiers values (feeMultiplier, pointsThreshold) | ## TraderDailyPointsIncreased ```solidity theme={null} event TraderDailyPointsIncreased(address trader, uint32 day, uint224 points) ``` *Emitted when a trader's daily points are updated* ### Parameters | Name | Type | Description | | ------ | ------- | ----------------------------- | | trader | address | trader address | | day | uint32 | day | | points | uint224 | points added (1e18 precision) | ## TraderInfoFirstUpdate ```solidity theme={null} event TraderInfoFirstUpdate(address trader, uint32 day) ``` *Emitted when a trader info is updated for the first time* ### Parameters | Name | Type | Description | | ------ | ------- | ----------------- | | trader | address | address of trader | | day | uint32 | day | ## TraderTrailingPointsExpired ```solidity theme={null} event TraderTrailingPointsExpired(address trader, uint32 fromDay, uint32 toDay, uint224 expiredPoints) ``` *Emitted when a trader's trailing points are updated* ### Parameters | Name | Type | Description | | ------------- | ------- | -------------------------------------- | | trader | address | trader address | | fromDay | uint32 | from day | | toDay | uint32 | to day | | expiredPoints | uint224 | expired points amount (1e18 precision) | ## TraderInfoUpdated ```solidity theme={null} event TraderInfoUpdated(address trader, struct IFeeTiers.TraderInfo traderInfo) ``` *Emitted when a trader's info is updated* ### Parameters | Name | Type | Description | | ---------- | --------------------------- | ------------------------------------------------------ | | trader | address | address of trader | | traderInfo | struct IFeeTiers.TraderInfo | new trader info value (lastDayUpdated, trailingPoints) | ## TraderFeeMultiplierCached ```solidity theme={null} event TraderFeeMultiplierCached(address trader, uint32 day, uint32 feeMultiplier) ``` *Emitted when a trader's cached fee multiplier is updated (this is the one used in fee calculations)* ### Parameters | Name | Type | Description | | ------------- | ------- | ---------------------------------- | | trader | address | address of trader | | day | uint32 | day | | feeMultiplier | uint32 | new fee multiplier (1e3 precision) | ## TraderEnrollmentUpdated ```solidity theme={null} event TraderEnrollmentUpdated(address trader, struct IFeeTiers.TraderEnrollment enrollment) ``` *Emitted when a trader's enrollment status is updated* ### Parameters | Name | Type | Description | | ---------- | --------------------------------- | ------------------------------ | | trader | address | address of trader | | enrollment | struct IFeeTiers.TraderEnrollment | trader's new enrollment status | ## TraderPointsCredited ```solidity theme={null} event TraderPointsCredited(address trader, uint32 day, enum IFeeTiers.CreditType creditType, uint224 points) ``` *Emitted when a trader is credited points by governance* ### Parameters | Name | Type | Description | | ---------- | ------------------------- | -------------------------------------------------------------------------------------- | | trader | address | trader address | | day | uint32 | day the points were credited on, may be different from the day the points were claimed | | creditType | enum IFeeTiers.CreditType | credit type (IMMEDIATE, CLAIMABLE) | | points | uint224 | points added (1e18 precision) | ## TraderUnclaimedPointsClaimed ```solidity theme={null} event TraderUnclaimedPointsClaimed(address trader, uint32 day, uint224 points) ``` *Emitted when a trader's unclaimed points are claimed* ### Parameters | Name | Type | Description | | ------ | ------- | ----------------------------- | | trader | address | trader address | | day | uint32 | day of claim | | points | uint224 | points added (1e18 precision) | ## WrongFeeTier ```solidity theme={null} error WrongFeeTier() ``` ## PointsOverflow ```solidity theme={null} error PointsOverflow() ``` # IOtcUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/iotcutils *Interface for GNSOtc facet (inherits types and also contains functions, events, and custom errors)* ## initializeOtc ```solidity theme={null} function initializeOtc(struct IOtc.OtcConfig _config) external ``` *Initializer for OTC facet* ### Parameters | Name | Type | Description | | -------- | ------------------------------------------------------------------------------------------ | -------------- | | \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config | ## updateOtcConfig ```solidity theme={null} function updateOtcConfig(struct IOtc.OtcConfig _config) external ``` *Updates OTC config* ### Parameters | Name | Type | Description | | -------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | | \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config. Sum of `treasuryShareP`, `stakingShareP`, `burnShareP` must equal 100 and `premiumP` must be less than or equal to MAX\_PREMIUM\_P | ## addOtcCollateralBalance ```solidity theme={null} function addOtcCollateralBalance(uint8 _collateralIndex, uint256 _collateralAmount) external ``` *Increases OTC balance for a collateral* ### Parameters | Name | Type | Description | | ------------------ | ------- | ------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_collateralAmount | uint256 | amount of collateral to increase (collateral precision) | ## sellGnsForCollateral ```solidity theme={null} function sellGnsForCollateral(uint8 _collateralIndex, uint256 _collateralAmount) external ``` *OTC Buys GNS from caller for `_amountCollateral` of `_collateralIndex`* ### Parameters | Name | Type | Description | | ------------------ | ------- | ---------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_collateralAmount | uint256 | amount of collateral to trade (collateral precision) | ## getOtcConfig ```solidity theme={null} function getOtcConfig() external view returns (struct IOtc.OtcConfig) ``` *Returns OTC Config* ## getOtcBalance ```solidity theme={null} function getOtcBalance(uint8 _collateralIndex) external view returns (uint256) ``` *Returns OTC balance for a collateral (collateral precision)* ### Parameters | Name | Type | Description | | ----------------- | ----- | ---------------- | | \_collateralIndex | uint8 | collateral index | ## getOtcRate ```solidity theme={null} function getOtcRate(uint8 _collateralIndex) external view returns (uint256) ``` *Returns OTC rate (price + premium) of GNS in collateral (1e10)* ### Parameters | Name | Type | Description | | ----------------- | ----- | ---------------- | | \_collateralIndex | uint8 | collateral index | ## OtcConfigUpdated ```solidity theme={null} event OtcConfigUpdated(struct IOtc.OtcConfig config) ``` *Emitted when OTCConfig is updated* ### Parameters | Name | Type | Description | | ------ | --------------------- | -------------- | | config | struct IOtc.OtcConfig | new OTC config | ## OtcBalanceUpdated ```solidity theme={null} event OtcBalanceUpdated(uint8 collateralIndex, uint256 balanceCollateral) ``` *Emitted when OTC balance is updated* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------------- | | collateralIndex | uint8 | collateral index | | balanceCollateral | uint256 | new balance (collateral precision) | ## OtcExecuted ```solidity theme={null} event OtcExecuted(uint8 collateralIndex, uint256 collateralAmount, uint256 gnsPriceCollateral, uint256 treasuryAmountGns, uint256 stakingAmountGns, uint256 burnAmountGns) ``` *Emitted when an OTC trade is executed* ### Parameters | Name | Type | Description | | ------------------ | ------- | -------------------------------------------------------- | | collateralIndex | uint8 | collateral index | | collateralAmount | uint256 | amount of collateral traded (collateral precision) | | gnsPriceCollateral | uint256 | effective gns/collateral price, including premium (1e10) | | treasuryAmountGns | uint256 | amount of GNS sent to treasury (1e18) | | stakingAmountGns | uint256 | amount of GNS sent to GNS Staking (1e18) | | burnAmountGns | uint256 | amount of GNS burned (1e18) | ## InvalidShareSum ```solidity theme={null} error InvalidShareSum() ``` # IPairsStorageUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/ipairsstorageutils *Interface for GNSPairsStorage facet (inherits types and also contains functions, events, and custom errors)* ## initializeGroupLiquidationParams ```solidity theme={null} function initializeGroupLiquidationParams(struct IPairsStorage.GroupLiquidationParams[] _groupLiquidationParams) external ``` *Initializes liquidation params for all existing groups* ### Parameters | Name | Type | Description | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | \_groupLiquidationParams | [IPairsStorage.GroupLiquidationParams\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | liquidation params for each group (index corresponds to group index) | ## initializeNewFees ```solidity theme={null} function initializeNewFees(struct IPairsStorage.GlobalTradeFeeParams _tradeFeeParams) external ``` *Copies all existing fee groups to new mapping, multiplies existing groups min/max lev by 1e3, initializes new global trade fee params* ### Parameters | Name | Type | Description | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_tradeFeeParams | [IPairsStorage.GlobalTradeFeeParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#globaltradefeeparams) | global trade fee params | ## addPairs ```solidity theme={null} function addPairs(struct IPairsStorage.Pair[] _pairs) external ``` *Adds new trading pairs* ### Parameters | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------ | ------------ | | \_pairs | [IPairsStorage.Pair\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | pairs to add | ## updatePairs ```solidity theme={null} function updatePairs(uint256[] _pairIndices, struct IPairsStorage.Pair[] _pairs) external ``` *Updates trading pairs* ### Parameters | Name | Type | Description | | ------------- | ------------------------------------------------------------------------------------------------------ | ---------------- | | \_pairIndices | uint256\[] | indices of pairs | | \_pairs | [IPairsStorage.Pair\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | new pairs values | ## addGroups ```solidity theme={null} function addGroups(struct IPairsStorage.Group[] _groups) external ``` *Adds new pair groups* ### Parameters | Name | Type | Description | | -------- | -------------------------------------------------------------------------------------------------------- | ------------- | | \_groups | [IPairsStorage.Group\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | groups to add | ## updateGroups ```solidity theme={null} function updateGroups(uint256[] _ids, struct IPairsStorage.Group[] _groups) external ``` *Updates pair groups* ### Parameters | Name | Type | Description | | -------- | -------------------------------------------------------------------------------------------------------- | ----------------- | | \_ids | uint256\[] | indices of groups | | \_groups | [IPairsStorage.Group\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | new groups values | ## addFees ```solidity theme={null} function addFees(struct IPairsStorage.FeeGroup[] _fees) external ``` *Adds new pair fees groups* ### Parameters | Name | Type | Description | | ------ | -------------------------------------------------------------------------------------------------------------- | ----------- | | \_fees | [IPairsStorage.FeeGroup\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | fees to add | ## updateFees ```solidity theme={null} function updateFees(uint256[] _ids, struct IPairsStorage.FeeGroup[] _fees) external ``` *Updates pair fees groups* ### Parameters | Name | Type | Description | | ------ | -------------------------------------------------------------------------------------------------------------- | --------------- | | \_ids | uint256\[] | indices of fees | | \_fees | [IPairsStorage.FeeGroup\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | new fees values | ## setPairCustomMaxLeverages ```solidity theme={null} function setPairCustomMaxLeverages(uint256[] _indices, uint256[] _values) external ``` *Updates pair custom max leverages (if unset group default is used); useful to delist a pair if new value is below the pair's group minLeverage* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------------------------------- | | \_indices | uint256\[] | indices of pairs | | \_values | uint256\[] | new custom max leverages (1e3 precision) | ## setGroupLiquidationParams ```solidity theme={null} function setGroupLiquidationParams(uint256 _groupIndex, struct IPairsStorage.GroupLiquidationParams _params) external ``` *Updates group liquidation params (will only apply for trades opened after the change)* ### Parameters | Name | Type | Description | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | | \_groupIndex | uint256 | index of group | | \_params | [IPairsStorage.GroupLiquidationParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | new liquidation params | ## setGlobalTradeFeeParams ```solidity theme={null} function setGlobalTradeFeeParams(struct IPairsStorage.GlobalTradeFeeParams _feeParams) external ``` *Updates global trade fee params* ### Parameters | Name | Type | Description | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------- | -------------- | | \_feeParams | [IPairsStorage.GlobalTradeFeeParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#globaltradefeeparams) | new fee params | ## pairJob ```solidity theme={null} function pairJob(uint256 _pairIndex) external view returns (string from, string to) ``` *Returns data needed by price aggregator when doing a new price request* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ### Return Values | Name | Type | Description | | ---- | ------ | ------------------- | | from | string | pair from (eg. BTC) | | to | string | pair to (eg. USD) | ## isPairListed ```solidity theme={null} function isPairListed(string _from, string _to) external view returns (bool) ``` *Returns whether a pair is listed* ### Parameters | Name | Type | Description | | ------ | ------ | ------------------- | | \_from | string | pair from (eg. BTC) | | \_to | string | pair to (eg. USD) | ## isPairIndexListed ```solidity theme={null} function isPairIndexListed(uint256 _pairIndex) external view returns (bool) ``` *Returns whether a pair index is listed* ### Parameters | Name | Type | Description | | ----------- | ------- | ---------------------- | | \_pairIndex | uint256 | index of pair to check | ## pairs ```solidity theme={null} function pairs(uint256 _index) external view returns (struct IPairsStorage.Pair) ``` *Returns a pair's details* ### Parameters | Name | Type | Description | | ------- | ------- | ------------- | | \_index | uint256 | index of pair | ## pairsCount ```solidity theme={null} function pairsCount() external view returns (uint256) ``` *Returns number of listed pairs* ## pairSpreadP ```solidity theme={null} function pairSpreadP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's spread % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairMinLeverage ```solidity theme={null} function pairMinLeverage(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's min leverage (1e3 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairTotalPositionSizeFeeP ```solidity theme={null} function pairTotalPositionSizeFeeP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's total position size fee % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairTotalLiqCollateralFeeP ```solidity theme={null} function pairTotalLiqCollateralFeeP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's total liquidation collateral fee % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairOraclePositionSizeFeeP ```solidity theme={null} function pairOraclePositionSizeFeeP(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's oracle position size fee % (1e10 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairMinPositionSizeUsd ```solidity theme={null} function pairMinPositionSizeUsd(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's min position size in USD (1e18 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## getGlobalTradeFeeParams ```solidity theme={null} function getGlobalTradeFeeParams() external view returns (struct IPairsStorage.GlobalTradeFeeParams) ``` *Returns global trade fee params* ## pairMinFeeUsd ```solidity theme={null} function pairMinFeeUsd(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's minimum trading fee in USD (1e18 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## groups ```solidity theme={null} function groups(uint256 _index) external view returns (struct IPairsStorage.Group) ``` *Returns a group details* ### Parameters | Name | Type | Description | | ------- | ------- | -------------- | | \_index | uint256 | index of group | ## groupsCount ```solidity theme={null} function groupsCount() external view returns (uint256) ``` *Returns number of listed groups* ## fees ```solidity theme={null} function fees(uint256 _index) external view returns (struct IPairsStorage.FeeGroup) ``` *Returns a fee group details* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------ | | \_index | uint256 | index of fee group | ## feesCount ```solidity theme={null} function feesCount() external view returns (uint256) ``` *Returns number of listed fee groups* ## pairMaxLeverage ```solidity theme={null} function pairMaxLeverage(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's active max leverage; custom if set, otherwise group default (1e3 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## pairCustomMaxLeverage ```solidity theme={null} function pairCustomMaxLeverage(uint256 _pairIndex) external view returns (uint256) ``` *Returns a pair's custom max leverage; 0 if not set (1e3 precision)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## getAllPairsRestrictedMaxLeverage ```solidity theme={null} function getAllPairsRestrictedMaxLeverage() external view returns (uint256[]) ``` *Returns all listed pairs custom max leverages (1e3 precision)* ## getGroupLiquidationParams ```solidity theme={null} function getGroupLiquidationParams(uint256 _groupIndex) external view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Returns a group's liquidation params* ## getPairLiquidationParams ```solidity theme={null} function getPairLiquidationParams(uint256 _pairIndex) external view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Returns a pair's group liquidation params* ## PairAdded ```solidity theme={null} event PairAdded(uint256 index, string from, string to) ``` *Emitted when a new pair is listed* ### Parameters | Name | Type | Description | | ----- | ------- | ------------------- | | index | uint256 | index of pair | | from | string | pair from (eg. BTC) | | to | string | pair to (eg. USD) | ## PairUpdated ```solidity theme={null} event PairUpdated(uint256 index) ``` *Emitted when a pair is updated* ### Parameters | Name | Type | Description | | ----- | ------- | ------------- | | index | uint256 | index of pair | ## PairCustomMaxLeverageUpdated ```solidity theme={null} event PairCustomMaxLeverageUpdated(uint256 index, uint256 maxLeverage) ``` *Emitted when a pair's custom max leverage is updated* ### Parameters | Name | Type | Description | | ----------- | ------- | -------------------------------- | | index | uint256 | index of pair | | maxLeverage | uint256 | new max leverage (1e3 precision) | ## GroupAdded ```solidity theme={null} event GroupAdded(uint256 index, string name) ``` *Emitted when a new group is added* ### Parameters | Name | Type | Description | | ----- | ------- | -------------- | | index | uint256 | index of group | | name | string | name of group | ## GroupUpdated ```solidity theme={null} event GroupUpdated(uint256 index) ``` *Emitted when a group is updated* ### Parameters | Name | Type | Description | | ----- | ------- | -------------- | | index | uint256 | index of group | ## FeeAdded ```solidity theme={null} event FeeAdded(uint256 index, struct IPairsStorage.FeeGroup feeGroup) ``` *Emitted when a new fee group is added* ### Parameters | Name | Type | Description | | -------- | ----------------------------- | ------------------ | | index | uint256 | index of fee group | | feeGroup | struct IPairsStorage.FeeGroup | fee group | ## FeeUpdated ```solidity theme={null} event FeeUpdated(uint256 index, struct IPairsStorage.FeeGroup feeGroup) ``` *Emitted when a fee group is updated* ### Parameters | Name | Type | Description | | -------- | ----------------------------- | ------------------ | | index | uint256 | index of fee group | | feeGroup | struct IPairsStorage.FeeGroup | updated fee group | ## GroupLiquidationParamsUpdated ```solidity theme={null} event GroupLiquidationParamsUpdated(uint256 index, struct IPairsStorage.GroupLiquidationParams params) ``` *Emitted when a group liquidation params are updated* ### Parameters | Name | Type | Description | | ------ | ------------------------------------------- | ---------------------------- | | index | uint256 | index of group | | params | struct IPairsStorage.GroupLiquidationParams | new group liquidation params | ## GlobalTradeFeeParamsUpdated ```solidity theme={null} event GlobalTradeFeeParamsUpdated(struct IPairsStorage.GlobalTradeFeeParams feeParams) ``` *Emitted when global trade fee params are updated* ### Parameters | Name | Type | Description | | --------- | ----------------------------------------- | -------------- | | feeParams | struct IPairsStorage.GlobalTradeFeeParams | new fee params | ## PairNotListed ```solidity theme={null} error PairNotListed() ``` ## GroupNotListed ```solidity theme={null} error GroupNotListed() ``` ## FeeNotListed ```solidity theme={null} error FeeNotListed() ``` ## WrongLeverages ```solidity theme={null} error WrongLeverages() ``` ## WrongFees ```solidity theme={null} error WrongFees() ``` ## PairAlreadyListed ```solidity theme={null} error PairAlreadyListed() ``` ## MaxLiqSpreadPTooHigh ```solidity theme={null} error MaxLiqSpreadPTooHigh() ``` ## WrongLiqParamsThresholds ```solidity theme={null} error WrongLiqParamsThresholds() ``` ## WrongLiqParamsLeverages ```solidity theme={null} error WrongLiqParamsLeverages() ``` ## StartLiqThresholdTooHigh ```solidity theme={null} error StartLiqThresholdTooHigh() ``` ## EndLiqThresholdTooLow ```solidity theme={null} error EndLiqThresholdTooLow() ``` ## StartLeverageTooLow ```solidity theme={null} error StartLeverageTooLow() ``` ## EndLeverageTooHigh ```solidity theme={null} error EndLeverageTooHigh() ``` # IPriceAggregatorUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/ipriceaggregatorutils *Interface for GNSPriceAggregator facet (inherits types and also contains functions, events, and custom errors)* ## initializePriceAggregator ```solidity theme={null} function initializePriceAggregator(address _linkToken, contract IChainlinkFeed _linkUsdPriceFeed, uint24 _twapInterval, uint8 _minAnswers, address[] _oracles, bytes32[2] _jobIds, uint8[] _collateralIndices, struct IPriceAggregator.LiquidityPoolInput[] _gnsCollateralLiquidityPools, contract IChainlinkFeed[] _collateralUsdPriceFeeds) external ``` *Initializes price aggregator facet* ### Parameters | Name | Type | Description | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | \_linkToken | address | LINK token address | | \_linkUsdPriceFeed | contract IChainlinkFeed | LINK/USD price feed address | | \_twapInterval | uint24 | TWAP interval (seconds) | | \_minAnswers | uint8 | answers count at which a trade is executed with median | | \_oracles | address\[] | chainlink oracle addresses | | \_jobIds | bytes32\[2] | chainlink job ids (market/lookback) | | \_collateralIndices | uint8\[] | collateral indices | | \_gnsCollateralLiquidityPools | [IPriceAggregator.LiquidityPoolInput\[\]](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | corresponding GNS/collateral liquidity pool values | | \_collateralUsdPriceFeeds | contract IChainlinkFeed\[] | corresponding collateral/USD chainlink price feeds | ## updateLinkUsdPriceFeed ```solidity theme={null} function updateLinkUsdPriceFeed(contract IChainlinkFeed _value) external ``` *Updates LINK/USD chainlink price feed* ### Parameters | Name | Type | Description | | ------- | ----------------------- | ----------- | | \_value | contract IChainlinkFeed | new value | ## updateCollateralUsdPriceFeed ```solidity theme={null} function updateCollateralUsdPriceFeed(uint8 _collateralIndex, contract IChainlinkFeed _value) external ``` *Updates collateral/USD chainlink price feed* ### Parameters | Name | Type | Description | | ----------------- | ----------------------- | ---------------- | | \_collateralIndex | uint8 | collateral index | | \_value | contract IChainlinkFeed | new value | ## updateCollateralGnsLiquidityPool ```solidity theme={null} function updateCollateralGnsLiquidityPool(uint8 _collateralIndex, struct IPriceAggregator.LiquidityPoolInput _liquidityPoolInput) external ``` *Updates collateral/GNS liquidity pool* ### Parameters | Name | Type | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------- | | \_collateralIndex | uint8 | collateral index | | \_liquidityPoolInput | [IPriceAggregator.LiquidityPoolInput](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | new values | ## updateTwapInterval ```solidity theme={null} function updateTwapInterval(uint24 _twapInterval) external ``` *Updates TWAP interval* ### Parameters | Name | Type | Description | | -------------- | ------ | ------------------- | | \_twapInterval | uint24 | new value (seconds) | ## updateMinAnswers ```solidity theme={null} function updateMinAnswers(uint8 _value) external ``` *Updates minimum answers count* ### Parameters | Name | Type | Description | | ------- | ----- | ----------- | | \_value | uint8 | new value | ## addOracle ```solidity theme={null} function addOracle(address _a) external ``` *Adds an oracle* ### Parameters | Name | Type | Description | | ---- | ------- | ----------- | | \_a | address | new value | ## replaceOracle ```solidity theme={null} function replaceOracle(uint256 _index, address _a) external ``` *Replaces an oracle* ### Parameters | Name | Type | Description | | ------- | ------- | ------------ | | \_index | uint256 | oracle index | | \_a | address | new value | ## removeOracle ```solidity theme={null} function removeOracle(uint256 _index) external ``` *Removes an oracle* ### Parameters | Name | Type | Description | | ------- | ------- | ------------ | | \_index | uint256 | oracle index | ## setMarketJobId ```solidity theme={null} function setMarketJobId(bytes32 _jobId) external ``` *Updates market job id* ### Parameters | Name | Type | Description | | ------- | ------- | ----------- | | \_jobId | bytes32 | new value | ## setLimitJobId ```solidity theme={null} function setLimitJobId(bytes32 _jobId) external ``` *Updates lookback job id* ### Parameters | Name | Type | Description | | ------- | ------- | ----------- | | \_jobId | bytes32 | new value | ## getPrice ```solidity theme={null} function getPrice(uint8 _collateralIndex, uint16 _pairIndex, struct ITradingStorage.Id _tradeId, struct ITradingStorage.Id _orderId, enum ITradingStorage.PendingOrderType _orderType, uint256 _positionSizeCollateral, uint256 _fromBlock) external ``` *Requests price from oracles* ### Parameters | Name | Type | Description | | ------------------------ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_pairIndex | uint16 | pair index | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | trade id | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | order id | | \_orderType | enum ITradingStorage.PendingOrderType | order type | | \_positionSizeCollateral | uint256 | position size (collateral precision) | | \_fromBlock | uint256 | block number from which to start fetching prices (for lookbacks) | ## fulfill ```solidity theme={null} function fulfill(bytes32 _requestId, uint256 _priceData) external ``` *Fulfills price request, called by chainlink oracles* ### Parameters | Name | Type | Description | | ----------- | ------- | ----------- | | \_requestId | bytes32 | request id | | \_priceData | uint256 | price data | ## claimBackLink ```solidity theme={null} function claimBackLink() external ``` *Claims back LINK tokens, called by gov fund* ## getLinkFee ```solidity theme={null} function getLinkFee(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _positionSizeCollateral) external view returns (uint256) ``` *Returns LINK fee for price request* ### Parameters | Name | Type | Description | | ------------------------ | ------- | --------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_trader | address | trader address | | \_pairIndex | uint16 | pair index | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | ## getCollateralPriceUsd ```solidity theme={null} function getCollateralPriceUsd(uint8 _collateralIndex) external view returns (uint256) ``` *Returns collateral/USD price* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getUsdNormalizedValue ```solidity theme={null} function getUsdNormalizedValue(uint8 _collateralIndex, uint256 _collateralValue) external view returns (uint256) ``` *Returns USD normalized value from collateral value* ### Parameters | Name | Type | Description | | ----------------- | ------- | --------------------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_collateralValue | uint256 | collateral value (collateral precision) | ## getCollateralFromUsdNormalizedValue ```solidity theme={null} function getCollateralFromUsdNormalizedValue(uint8 _collateralIndex, uint256 _normalizedValue) external view returns (uint256) ``` *Returns collateral value (collateral precision) from USD normalized value* ### Parameters | Name | Type | Description | | ----------------- | ------- | --------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_normalizedValue | uint256 | normalized value (1e18 USD) | ## getGnsPriceUsd ```solidity theme={null} function getGnsPriceUsd(uint8 _collateralIndex) external view returns (uint256) ``` *Returns GNS/USD price based on GNS/collateral price* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getGnsPriceUsd ```solidity theme={null} function getGnsPriceUsd(uint8 _collateralIndex, uint256 _gnsPriceCollateral) external view returns (uint256) ``` *Returns GNS/USD price based on GNS/collateral price* ### Parameters | Name | Type | Description | | -------------------- | ------- | --------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_gnsPriceCollateral | uint256 | GNS/collateral price (1e10) | ## getGnsPriceCollateralIndex ```solidity theme={null} function getGnsPriceCollateralIndex(uint8 _collateralIndex) external view returns (uint256) ``` *Returns GNS/collateral price* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getGnsPriceCollateralAddress ```solidity theme={null} function getGnsPriceCollateralAddress(address _collateral) external view returns (uint256) ``` *Returns GNS/collateral price* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------- | | \_collateral | address | address of the collateral | ## getLinkUsdPriceFeed ```solidity theme={null} function getLinkUsdPriceFeed() external view returns (contract IChainlinkFeed) ``` *Returns the link/usd price feed address* ## getTwapInterval ```solidity theme={null} function getTwapInterval() external view returns (uint24) ``` *Returns the twap interval in seconds* ## getMinAnswers ```solidity theme={null} function getMinAnswers() external view returns (uint8) ``` *Returns the minimum answers to execute an order and take the median* ## getMarketJobId ```solidity theme={null} function getMarketJobId() external view returns (bytes32) ``` *Returns the market job id* ## getLimitJobId ```solidity theme={null} function getLimitJobId() external view returns (bytes32) ``` *Returns the limit job id* ## getOracle ```solidity theme={null} function getOracle(uint256 _index) external view returns (address) ``` *Returns a specific oracle* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------- | | \_index | uint256 | index of the oracle | ## getOracles ```solidity theme={null} function getOracles() external view returns (address[]) ``` *Returns all oracles* ## getCollateralGnsLiquidityPool ```solidity theme={null} function getCollateralGnsLiquidityPool(uint8 _collateralIndex) external view returns (struct IPriceAggregator.LiquidityPoolInfo) ``` *Returns collateral/gns liquidity pool info* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getCollateralUsdPriceFeed ```solidity theme={null} function getCollateralUsdPriceFeed(uint8 _collateralIndex) external view returns (contract IChainlinkFeed) ``` *Returns collateral/usd chainlink price feed* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | ## getPriceAggregatorOrder ```solidity theme={null} function getPriceAggregatorOrder(bytes32 _requestId) external view returns (struct IPriceAggregator.Order) ``` *Returns order data* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------- | | \_requestId | bytes32 | index of collateral | ## getPriceAggregatorOrderAnswers ```solidity theme={null} function getPriceAggregatorOrderAnswers(struct ITradingStorage.Id _orderId) external view returns (struct IPriceAggregator.OrderAnswer[]) ``` *Returns order data* ### Parameters | Name | Type | Description | | --------- | ------------------ | ----------- | | \_orderId | ITradingStorage.Id | order id | ## getChainlinkToken ```solidity theme={null} function getChainlinkToken() external view returns (address) ``` *Returns chainlink token address* ## getRequestCount ```solidity theme={null} function getRequestCount() external view returns (uint256) ``` *Returns requestCount (used by ChainlinkClientUtils)* ## getPendingRequest ```solidity theme={null} function getPendingRequest(bytes32 _id) external view returns (address) ``` *Returns pendingRequests mapping entry (used by ChainlinkClientUtils)* ## LinkUsdPriceFeedUpdated ```solidity theme={null} event LinkUsdPriceFeedUpdated(address value) ``` *Emitted when LINK/USD price feed is updated* ### Parameters | Name | Type | Description | | ----- | ------- | ----------- | | value | address | new value | ## CollateralUsdPriceFeedUpdated ```solidity theme={null} event CollateralUsdPriceFeedUpdated(uint8 collateralIndex, address value) ``` *Emitted when collateral/USD price feed is updated* ### Parameters | Name | Type | Description | | --------------- | ------- | ---------------- | | collateralIndex | uint8 | collateral index | | value | address | new value | ## CollateralGnsLiquidityPoolUpdated ```solidity theme={null} event CollateralGnsLiquidityPoolUpdated(uint8 collateralIndex, struct IPriceAggregator.LiquidityPoolInfo newValue) ``` *Emitted when collateral/GNS Uniswap V3 pool is updated* ### Parameters | Name | Type | Description | | --------------- | ----------------------------------------- | ---------------- | | collateralIndex | uint8 | collateral index | | newValue | struct IPriceAggregator.LiquidityPoolInfo | new value | ## TwapIntervalUpdated ```solidity theme={null} event TwapIntervalUpdated(uint32 newValue) ``` *Emitted when TWAP interval is updated* ### Parameters | Name | Type | Description | | -------- | ------ | ----------- | | newValue | uint32 | new value | ## MinAnswersUpdated ```solidity theme={null} event MinAnswersUpdated(uint8 value) ``` *Emitted when minimum answers count is updated* ### Parameters | Name | Type | Description | | ----- | ----- | ----------- | | value | uint8 | new value | ## OracleAdded ```solidity theme={null} event OracleAdded(uint256 index, address value) ``` *Emitted when an oracle is added* ### Parameters | Name | Type | Description | | ----- | ------- | ---------------- | | index | uint256 | new oracle index | | value | address | value | ## OracleReplaced ```solidity theme={null} event OracleReplaced(uint256 index, address oldOracle, address newOracle) ``` *Emitted when an oracle is replaced* ### Parameters | Name | Type | Description | | --------- | ------- | ------------ | | index | uint256 | oracle index | | oldOracle | address | old value | | newOracle | address | new value | ## OracleRemoved ```solidity theme={null} event OracleRemoved(uint256 index, address oldOracle) ``` *Emitted when an oracle is removed* ### Parameters | Name | Type | Description | | --------- | ------- | ------------ | | index | uint256 | oracle index | | oldOracle | address | old value | ## JobIdUpdated ```solidity theme={null} event JobIdUpdated(uint256 index, bytes32 jobId) ``` *Emitted when market job id is updated* ### Parameters | Name | Type | Description | | ----- | ------- | ----------- | | index | uint256 | index | | jobId | bytes32 | new value | ## LinkRequestCreated ```solidity theme={null} event LinkRequestCreated(struct Chainlink.Request request) ``` *Emitted when a chainlink request is created* ### Parameters | Name | Type | Description | | ------- | ------------------------ | -------------------- | | request | struct Chainlink.Request | link request details | ## PriceRequested ```solidity theme={null} event PriceRequested(uint8 collateralIndex, uint256 pairIndex, struct ITradingStorage.Id tradeId, struct ITradingStorage.Id pendingOrderId, enum ITradingStorage.PendingOrderType orderType, uint256 fromBlock, bool isLookback, bytes32 job, uint256 linkFeePerNode, uint256 nodesCount) ``` *Emitted when a price is requested to the oracles* ### Parameters | Name | Type | Description | | --------------- | ------------------------------------- | ---------------------------------------------------------------- | | collateralIndex | uint8 | collateral index | | pairIndex | uint256 | trading pair index | | tradeId | struct ITradingStorage.Id | trader id | | pendingOrderId | struct ITradingStorage.Id | pending order id | | orderType | enum ITradingStorage.PendingOrderType | order type (market open/market close/limit open/stop open/etc.) | | fromBlock | uint256 | block number from which to start fetching prices (for lookbacks) | | isLookback | bool | true if lookback | | job | bytes32 | chainlink job id (market/lookback) | | linkFeePerNode | uint256 | link fee distributed per node (1e18 precision) | | nodesCount | uint256 | amount of nodes to fetch prices from | ## TradingCallbackExecuted ```solidity theme={null} event TradingCallbackExecuted(struct ITradingCallbacks.AggregatorAnswer a, enum ITradingStorage.PendingOrderType orderType) ``` *Emitted when a trading callback is called from the price aggregator* ### Parameters | Name | Type | Description | | --------- | ----------------------------------------- | ---------------------- | | a | struct ITradingCallbacks.AggregatorAnswer | aggregator answer data | | orderType | enum ITradingStorage.PendingOrderType | order type | ## PriceReceived ```solidity theme={null} event PriceReceived(struct ITradingStorage.Id orderId, uint16 pairIndex, bytes32 request, uint256 priceData, bool isLookback, bool usedInMedian) ``` *Emitted when a price is received from the oracles* ### Parameters | Name | Type | Description | | ------------ | ------------------------- | ----------------------------------------------------------------------------- | | orderId | struct ITradingStorage.Id | pending order id | | pairIndex | uint16 | trading pair index | | request | bytes32 | chainlink request id | | priceData | uint256 | OrderAnswer compressed into uint256 | | isLookback | bool | true if lookback | | usedInMedian | bool | false if order already executed because min answers count was already reached | ## LinkClaimedBack ```solidity theme={null} event LinkClaimedBack(uint256 amountLink) ``` *Emitted when LINK tokens are claimed back by gov fund* ### Parameters | Name | Type | Description | | ---------- | ------- | ---------------------------------- | | amountLink | uint256 | amount of LINK tokens claimed back | ## TransferAndCallToOracleFailed ```solidity theme={null} error TransferAndCallToOracleFailed() ``` ## SourceNotOracleOfRequest ```solidity theme={null} error SourceNotOracleOfRequest() ``` ## RequestAlreadyPending ```solidity theme={null} error RequestAlreadyPending() ``` ## OracleAlreadyListed ```solidity theme={null} error OracleAlreadyListed() ``` ## InvalidCandle ```solidity theme={null} error InvalidCandle() ``` ## WrongCollateralUsdDecimals ```solidity theme={null} error WrongCollateralUsdDecimals() ``` ## InvalidPoolType ```solidity theme={null} error InvalidPoolType() ``` # IPriceImpactUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/ipriceimpactutils *Interface for GNSPriceImpact facet (inherits types and also contains functions, events, and custom errors)* ## initializePriceImpact ```solidity theme={null} function initializePriceImpact(uint48 _windowsDuration, uint48 _windowsCount) external ``` *Initializes price impact facet* ### Parameters | Name | Type | Description | | ----------------- | ------ | -------------------------- | | \_windowsDuration | uint48 | windows duration (seconds) | | \_windowsCount | uint48 | windows count | ## initializeNegPnlCumulVolMultiplier ```solidity theme={null} function initializeNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) external ``` *Initializes negative pnl cumulative volume multiplier* ### Parameters | Name | Type | Description | | -------------------------- | ------ | ---------------- | | \_negPnlCumulVolMultiplier | uint40 | new value (1e10) | ## initializePairFactors ```solidity theme={null} function initializePairFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors, uint32[] _protectionCloseFactorBlocks, uint40[] _cumulativeFactors) external ``` *Initializes pair factors* ### Parameters | Name | Type | Description | | ----------------------------- | --------- | ------------------------------- | | \_pairIndices | uint16\[] | pair indices to initialize | | \_protectionCloseFactors | uint40\[] | protection close factors (1e10) | | \_protectionCloseFactorBlocks | uint32\[] | protection close factor blocks | | \_cumulativeFactors | uint40\[] | cumulative factors (1e10) | ## setPriceImpactWindowsCount ```solidity theme={null} function setPriceImpactWindowsCount(uint48 _newWindowsCount) external ``` *Updates price impact windows count* ### Parameters | Name | Type | Description | | ----------------- | ------ | ----------------- | | \_newWindowsCount | uint48 | new windows count | ## setPriceImpactWindowsDuration ```solidity theme={null} function setPriceImpactWindowsDuration(uint48 _newWindowsDuration) external ``` *Updates price impact windows duration* ### Parameters | Name | Type | Description | | -------------------- | ------ | ------------------------------ | | \_newWindowsDuration | uint48 | new windows duration (seconds) | ## setNegPnlCumulVolMultiplier ```solidity theme={null} function setNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) external ``` *Updates negative pnl cumulative volume multiplier* ### Parameters | Name | Type | Description | | -------------------------- | ------ | ---------------- | | \_negPnlCumulVolMultiplier | uint40 | new value (1e10) | ## setProtectionCloseFactorWhitelist ```solidity theme={null} function setProtectionCloseFactorWhitelist(address[] _traders, bool[] _whitelisted) external ``` *Whitelists/unwhitelists traders from protection close factor* ### Parameters | Name | Type | Description | | ------------- | ---------- | ----------------- | | \_traders | address\[] | traders addresses | | \_whitelisted | bool\[] | values | ## setPairDepths ```solidity theme={null} function setPairDepths(uint256[] _indices, uint128[] _depthsAboveUsd, uint128[] _depthsBelowUsd) external ``` *Updates pairs 1% depths above and below* ### Parameters | Name | Type | Description | | ---------------- | ---------- | ----------------------------- | | \_indices | uint256\[] | indices of pairs | | \_depthsAboveUsd | uint128\[] | depths above the price in USD | | \_depthsBelowUsd | uint128\[] | depths below the price in USD | ## setProtectionCloseFactors ```solidity theme={null} function setProtectionCloseFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors) external ``` *Sets protection close factors for pairs* ### Parameters | Name | Type | Description | | ------------------------ | --------- | ----------------------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_protectionCloseFactors | uint40\[] | new protection close factors (1e10) | ## setProtectionCloseFactorBlocks ```solidity theme={null} function setProtectionCloseFactorBlocks(uint16[] _pairIndices, uint32[] _protectionCloseFactorBlocks) external ``` *Sets protection close factor blocks duration for pairs* ### Parameters | Name | Type | Description | | ----------------------------- | --------- | ---------------------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_protectionCloseFactorBlocks | uint32\[] | new protection close factor blocks | ## setCumulativeFactors ```solidity theme={null} function setCumulativeFactors(uint16[] _pairIndices, uint40[] _cumulativeFactors) external ``` *Sets cumulative factors for pairs* ### Parameters | Name | Type | Description | | ------------------- | --------- | ----------------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_cumulativeFactors | uint40\[] | new cumulative factors (1e10) | ## setExemptOnOpen ```solidity theme={null} function setExemptOnOpen(uint16[] _pairIndices, bool[] _exemptOnOpen) external ``` *Sets whether pairs are exempt from price impact on open* ### Parameters | Name | Type | Description | | -------------- | --------- | ---------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_exemptOnOpen | bool\[] | new values | ## setExemptAfterProtectionCloseFactor ```solidity theme={null} function setExemptAfterProtectionCloseFactor(uint16[] _pairIndices, bool[] _exemptAfterProtectionCloseFactor) external ``` *Sets whether pairs are exempt from price impact on close once protection close factor has expired* ### Parameters | Name | Type | Description | | ---------------------------------- | --------- | ---------------------- | | \_pairIndices | uint16\[] | pair indices to update | | \_exemptAfterProtectionCloseFactor | bool\[] | new values | ## addPriceImpactOpenInterest ```solidity theme={null} function addPriceImpactOpenInterest(address _trader, uint32 _index, uint256 _oiDeltaCollateral, bool _open, bool _isPnlPositive) external ``` *Adds open interest to current window* ### Parameters | Name | Type | Description | | ------------------- | ------- | ---------------------------------------------------------------------------------- | | \_trader | address | trader address | | \_index | uint32 | trade index | | \_oiDeltaCollateral | uint256 | open interest to add (collateral precision) | | \_open | bool | whether it corresponds to opening or closing a trade | | \_isPnlPositive | bool | whether it corresponds to a positive pnl trade (only relevant when \_open = false) | ## getPriceImpactOi ```solidity theme={null} function getPriceImpactOi(uint256 _pairIndex, bool _long) external view returns (uint256 activeOi) ``` *Returns active open interest used in price impact calculation for a pair and side (long/short)* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------------------ | | \_pairIndex | uint256 | index of pair | | \_long | bool | true for long, false for short | ## getTradePriceImpact ```solidity theme={null} function getTradePriceImpact(address _trader, uint256 _marketPrice, uint256 _pairIndex, bool _long, uint256 _tradeOpenInterestUsd, bool _isPnlPositive, bool _open, uint256 _lastPosIncreaseBlock, enum ITradingStorage.ContractsVersion _contractsVersion) external view returns (uint256 priceImpactP, uint256 priceAfterImpact) ``` *Returns price impact % (1e10 precision) and price after impact (1e10 precision) for a trade* ### Parameters | Name | Type | Description | | ---------------------- | ------------------------------------- | ------------------------------------------------------------------------------------- | | \_trader | address | trader address (to check if whitelisted from protection close factor) | | \_marketPrice | uint256 | market price (1e10 precision) | | \_pairIndex | uint256 | index of pair | | \_long | bool | true for long, false for short | | \_tradeOpenInterestUsd | uint256 | open interest of trade in USD (1e18 precision) | | \_isPnlPositive | bool | true if positive pnl, false if negative pnl (only relevant when \_open = false) | | \_open | bool | true on open, false on close | | \_lastPosIncreaseBlock | uint256 | block when trade position size was last increased (only relevant when \_open = false) | | \_contractsVersion | enum ITradingStorage.ContractsVersion | trade contracts version | ## getPairDepth ```solidity theme={null} function getPairDepth(uint256 _pairIndex) external view returns (struct IPriceImpact.PairDepth) ``` *Returns a pair's depths above and below the price* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------- | | \_pairIndex | uint256 | index of pair | ## getOiWindowsSettings ```solidity theme={null} function getOiWindowsSettings() external view returns (struct IPriceImpact.OiWindowsSettings) ``` *Returns current price impact windows settings* ## getOiWindow ```solidity theme={null} function getOiWindow(uint48 _windowsDuration, uint256 _pairIndex, uint256 _windowId) external view returns (struct IPriceImpact.PairOi) ``` *Returns OI window details (long/short OI)* ### Parameters | Name | Type | Description | | ----------------- | ------- | -------------------------- | | \_windowsDuration | uint48 | windows duration (seconds) | | \_pairIndex | uint256 | index of pair | | \_windowId | uint256 | id of window | ## getOiWindows ```solidity theme={null} function getOiWindows(uint48 _windowsDuration, uint256 _pairIndex, uint256[] _windowIds) external view returns (struct IPriceImpact.PairOi[]) ``` *Returns multiple OI windows details (long/short OI)* ### Parameters | Name | Type | Description | | ----------------- | ---------- | -------------------------- | | \_windowsDuration | uint48 | windows duration (seconds) | | \_pairIndex | uint256 | index of pair | | \_windowIds | uint256\[] | ids of windows | ## getPairDepths ```solidity theme={null} function getPairDepths(uint256[] _indices) external view returns (struct IPriceImpact.PairDepth[]) ``` *Returns depths above and below the price for multiple pairs* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------- | | \_indices | uint256\[] | indices of pairs | ## getPairFactors ```solidity theme={null} function getPairFactors(uint256[] _indices) external view returns (struct IPriceImpact.PairFactors[]) ``` *Returns factors for a set of pairs (1e10)* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------- | | \_indices | uint256\[] | indices of pairs | ## getNegPnlCumulVolMultiplier ```solidity theme={null} function getNegPnlCumulVolMultiplier() external view returns (uint48) ``` *Returns negative pnl cumulative volume multiplier* ## getProtectionCloseFactorWhitelist ```solidity theme={null} function getProtectionCloseFactorWhitelist(address _trader) external view returns (bool) ``` *Returns whether a trader is whitelisted from protection close factor* ## OiWindowsSettingsInitialized ```solidity theme={null} event OiWindowsSettingsInitialized(uint48 windowsDuration, uint48 windowsCount) ``` *Triggered when OiWindowsSettings is initialized (once)* ### Parameters | Name | Type | Description | | --------------- | ------ | --------------------------------- | | windowsDuration | uint48 | duration of each window (seconds) | | windowsCount | uint48 | number of windows | ## PriceImpactWindowsCountUpdated ```solidity theme={null} event PriceImpactWindowsCountUpdated(uint48 windowsCount) ``` *Triggered when OiWindowsSettings.windowsCount is updated* ### Parameters | Name | Type | Description | | ------------ | ------ | --------------------- | | windowsCount | uint48 | new number of windows | ## PriceImpactWindowsDurationUpdated ```solidity theme={null} event PriceImpactWindowsDurationUpdated(uint48 windowsDuration) ``` *Triggered when OiWindowsSettings.windowsDuration is updated* ### Parameters | Name | Type | Description | | --------------- | ------ | ------------------------------------- | | windowsDuration | uint48 | new duration of each window (seconds) | ## NegPnlCumulVolMultiplierUpdated ```solidity theme={null} event NegPnlCumulVolMultiplierUpdated(uint40 negPnlCumulVolMultiplier) ``` *Triggered when negPnlCumulVolMultiplier is updated* ### Parameters | Name | Type | Description | | ------------------------ | ------ | ---------------- | | negPnlCumulVolMultiplier | uint40 | new value (1e10) | ## ProtectionCloseFactorWhitelistUpdated ```solidity theme={null} event ProtectionCloseFactorWhitelistUpdated(address trader, bool whitelisted) ``` *Triggered when a trader is whitelisted/unwhitelisted from protection close factor* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------------------------------- | | trader | address | trader address | | whitelisted | bool | true if whitelisted, false if unwhitelisted | ## ProtectionCloseFactorUpdated ```solidity theme={null} event ProtectionCloseFactorUpdated(uint256 pairIndex, uint40 protectionCloseFactor) ``` *Triggered when a pair's protection close factor is updated* ### Parameters | Name | Type | Description | | --------------------- | ------- | ---------------------------------- | | pairIndex | uint256 | index of the pair | | protectionCloseFactor | uint40 | new protection close factor (1e10) | ## ProtectionCloseFactorBlocksUpdated ```solidity theme={null} event ProtectionCloseFactorBlocksUpdated(uint256 pairIndex, uint32 protectionCloseFactorBlocks) ``` *Triggered when a pair's protection close factor duration is updated* ### Parameters | Name | Type | Description | | --------------------------- | ------- | ---------------------------------- | | pairIndex | uint256 | index of the pair | | protectionCloseFactorBlocks | uint32 | new protection close factor blocks | ## CumulativeFactorUpdated ```solidity theme={null} event CumulativeFactorUpdated(uint256 pairIndex, uint40 cumulativeFactor) ``` *Triggered when a pair's cumulative factor is updated* ### Parameters | Name | Type | Description | | ---------------- | ------- | ---------------------------- | | pairIndex | uint256 | index of the pair | | cumulativeFactor | uint40 | new cumulative factor (1e10) | ## ExemptOnOpenUpdated ```solidity theme={null} event ExemptOnOpenUpdated(uint256 pairIndex, bool exemptOnOpen) ``` *Triggered when a pair's exemptOnOpen value is updated* ### Parameters | Name | Type | Description | | ------------ | ------- | -------------------------------------------------- | | pairIndex | uint256 | index of the pair | | exemptOnOpen | bool | whether the pair is exempt of price impact on open | ## ExemptAfterProtectionCloseFactorUpdated ```solidity theme={null} event ExemptAfterProtectionCloseFactorUpdated(uint256 pairIndex, bool exemptAfterProtectionCloseFactor) ``` *Triggered when a pair's exemptAfterProtectionCloseFactor value is updated* ### Parameters | Name | Type | Description | | -------------------------------- | ------- | -------------------------------------------------------------------------------------------- | | pairIndex | uint256 | index of the pair | | exemptAfterProtectionCloseFactor | bool | whether the pair is exempt of price impact on close once protection close factor has expired | ## PriceImpactOpenInterestAdded ```solidity theme={null} event PriceImpactOpenInterestAdded(struct IPriceImpact.OiWindowUpdate oiWindowUpdate) ``` *Triggered when OI is added to a window.* ### Parameters | Name | Type | Description | | -------------- | ---------------------------------- | --------------------------------------------------------------------- | | oiWindowUpdate | struct IPriceImpact.OiWindowUpdate | OI window update details (windowsDuration, pairIndex, windowId, etc.) | ## PriceImpactOiTransferredPairs ```solidity theme={null} event PriceImpactOiTransferredPairs(uint256 pairsCount, uint256 prevCurrentWindowId, uint256 prevEarliestWindowId, uint256 newCurrentWindowId) ``` *Triggered when multiple pairs' OI are transferred to a new window (when updating windows duration).* ### Parameters | Name | Type | Description | | -------------------- | ------- | --------------------------------------------------------------------- | | pairsCount | uint256 | number of pairs | | prevCurrentWindowId | uint256 | previous current window ID corresponding to previous window duration | | prevEarliestWindowId | uint256 | previous earliest window ID corresponding to previous window duration | | newCurrentWindowId | uint256 | new current window ID corresponding to new window duration | ## PriceImpactOiTransferredPair ```solidity theme={null} event PriceImpactOiTransferredPair(uint256 pairIndex, struct IPriceImpact.PairOi totalPairOi) ``` *Triggered when a pair's OI is transferred to a new window.* ### Parameters | Name | Type | Description | | ----------- | -------------------------- | ---------------------------------------------------- | | pairIndex | uint256 | index of the pair | | totalPairOi | struct IPriceImpact.PairOi | total USD long/short OI of the pair (1e18 precision) | ## OnePercentDepthUpdated ```solidity theme={null} event OnePercentDepthUpdated(uint256 pairIndex, uint128 valueAboveUsd, uint128 valueBelowUsd) ``` *Triggered when a pair's depth is updated.* ### Parameters | Name | Type | Description | | ------------- | ------- | ----------------------------- | | pairIndex | uint256 | index of the pair | | valueAboveUsd | uint128 | new USD depth above the price | | valueBelowUsd | uint128 | new USD depth below the price | ## WrongWindowsDuration ```solidity theme={null} error WrongWindowsDuration() ``` ## WrongWindowsCount ```solidity theme={null} error WrongWindowsCount() ``` # IReferralsUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/ireferralsutils *Interface for GNSReferrals facet (inherits types and also contains functions, events, and custom errors)* ## initializeReferrals ```solidity theme={null} function initializeReferrals(uint256 _allyFeeP, uint256 _startReferrerFeeP, uint256 _targetVolumeUsd) external ``` ### Parameters | Name | Type | Description | | ------------------- | ------- | ---------------------------------------------------------------- | | \_allyFeeP | uint256 | % of total referral fee going to ally | | \_startReferrerFeeP | uint256 | initial % of total referral fee earned when zero volume referred | | \_targetVolumeUsd | uint256 | usd opening volume to refer to reach 100% of referral fee | ## updateAllyFeeP ```solidity theme={null} function updateAllyFeeP(uint256 _value) external ``` *Updates allyFeeP* ### Parameters | Name | Type | Description | | ------- | ------- | -------------- | | \_value | uint256 | new ally fee % | ## updateStartReferrerFeeP ```solidity theme={null} function updateStartReferrerFeeP(uint256 _value) external ``` *Updates startReferrerFeeP* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------------ | | \_value | uint256 | new start referrer fee % | ## updateReferralsTargetVolumeUsd ```solidity theme={null} function updateReferralsTargetVolumeUsd(uint256 _value) external ``` *Updates targetVolumeUsd* ### Parameters | Name | Type | Description | | ------- | ------- | ------------------------ | | \_value | uint256 | new target volume in usd | ## whitelistAllies ```solidity theme={null} function whitelistAllies(address[] _allies) external ``` *Whitelists ally addresses* ### Parameters | Name | Type | Description | | -------- | ---------- | ----------------------- | | \_allies | address\[] | array of ally addresses | ## unwhitelistAllies ```solidity theme={null} function unwhitelistAllies(address[] _allies) external ``` *Unwhitelists ally addresses* ### Parameters | Name | Type | Description | | -------- | ---------- | ----------------------- | | \_allies | address\[] | array of ally addresses | ## whitelistReferrers ```solidity theme={null} function whitelistReferrers(address[] _referrers, address[] _allies) external ``` *Whitelists referrer addresses* ### Parameters | Name | Type | Description | | ----------- | ---------- | ------------------------------------- | | \_referrers | address\[] | array of referrer addresses | | \_allies | address\[] | array of corresponding ally addresses | ## unwhitelistReferrers ```solidity theme={null} function unwhitelistReferrers(address[] _referrers) external ``` *Unwhitelists referrer addresses* ### Parameters | Name | Type | Description | | ----------- | ---------- | --------------------------- | | \_referrers | address\[] | array of referrer addresses | ## registerPotentialReferrer ```solidity theme={null} function registerPotentialReferrer(address _trader, address _referral) external ``` *Registers potential referrer for trader (only works if trader wasn't referred yet by someone else)* ### Parameters | Name | Type | Description | | ---------- | ------- | ---------------- | | \_trader | address | trader address | | \_referral | address | referrer address | ## distributeReferralReward ```solidity theme={null} function distributeReferralReward(address _trader, uint256 _volumeUsd, uint256 _referrerFeeUsd, uint256 _gnsPriceUsd) external ``` *Distributes ally and referrer rewards* ### Parameters | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | \_trader | address | trader address | | \_volumeUsd | uint256 | trading volume in usd (1e18 precision) | | \_referrerFeeUsd | uint256 | referrer fee in USD (1e18 precision) | | \_gnsPriceUsd | uint256 | token price in usd (1e10 precision) | ## claimAllyRewards ```solidity theme={null} function claimAllyRewards() external ``` *Claims pending GNS ally rewards of caller* ## claimReferrerRewards ```solidity theme={null} function claimReferrerRewards() external ``` *Claims pending GNS referrer rewards of caller* ## getReferrerFeeProgressP ```solidity theme={null} function getReferrerFeeProgressP(address _referrer) external view returns (uint256) ``` *Returns referrer fee % progress towards earning 100% based on his volume referred (1e10)* ### Parameters | Name | Type | Description | | ---------- | ------- | ---------------- | | \_referrer | address | referrer address | ## getTraderLastReferrer ```solidity theme={null} function getTraderLastReferrer(address _trader) external view returns (address) ``` *Returns last referrer of trader (whether referrer active or not)* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------- | | \_trader | address | address of trader | ## getTraderActiveReferrer ```solidity theme={null} function getTraderActiveReferrer(address _trader) external view returns (address) ``` *Returns active referrer of trader* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------- | | \_trader | address | address of trader | ## getReferrersReferred ```solidity theme={null} function getReferrersReferred(address _ally) external view returns (address[]) ``` *Returns referrers referred by ally* ### Parameters | Name | Type | Description | | ------ | ------- | --------------- | | \_ally | address | address of ally | ## getTradersReferred ```solidity theme={null} function getTradersReferred(address _referrer) external view returns (address[]) ``` *Returns traders referred by referrer* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------- | | \_referrer | address | address of referrer | ## getReferralsAllyFeeP ```solidity theme={null} function getReferralsAllyFeeP() external view returns (uint256) ``` *Returns ally fee % of total referral fee* ## getReferralsStartReferrerFeeP ```solidity theme={null} function getReferralsStartReferrerFeeP() external view returns (uint256) ``` *Returns start referrer fee % of total referral fee when zero volume was referred* ## getReferralsTargetVolumeUsd ```solidity theme={null} function getReferralsTargetVolumeUsd() external view returns (uint256) ``` *Returns target volume in usd to reach 100% of referral fee* ## getAllyDetails ```solidity theme={null} function getAllyDetails(address _ally) external view returns (struct IReferrals.AllyDetails) ``` *Returns ally details* ### Parameters | Name | Type | Description | | ------ | ------- | --------------- | | \_ally | address | address of ally | ## getReferrerDetails ```solidity theme={null} function getReferrerDetails(address _referrer) external view returns (struct IReferrals.ReferrerDetails) ``` *Returns referrer details* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------- | | \_referrer | address | address of referrer | ## UpdatedAllyFeeP ```solidity theme={null} event UpdatedAllyFeeP(uint256 value) ``` *Emitted when allyFeeP is updated* ### Parameters | Name | Type | Description | | ----- | ------- | -------------- | | value | uint256 | new ally fee % | ## UpdatedStartReferrerFeeP ```solidity theme={null} event UpdatedStartReferrerFeeP(uint256 value) ``` *Emitted when startReferrerFeeP is updated* ### Parameters | Name | Type | Description | | ----- | ------- | ------------------------ | | value | uint256 | new start referrer fee % | ## UpdatedOpenFeeP ```solidity theme={null} event UpdatedOpenFeeP(uint256 value) ``` *Emitted when openFeeP is updated* ### Parameters | Name | Type | Description | | ----- | ------- | -------------- | | value | uint256 | new open fee % | ## UpdatedTargetVolumeUsd ```solidity theme={null} event UpdatedTargetVolumeUsd(uint256 value) ``` *Emitted when targetVolumeUsd is updated* ### Parameters | Name | Type | Description | | ----- | ------- | ------------------------ | | value | uint256 | new target volume in usd | ## AllyWhitelisted ```solidity theme={null} event AllyWhitelisted(address ally) ``` *Emitted when an ally is whitelisted* ### Parameters | Name | Type | Description | | ---- | ------- | ------------ | | ally | address | ally address | ## AllyUnwhitelisted ```solidity theme={null} event AllyUnwhitelisted(address ally) ``` *Emitted when an ally is unwhitelisted* ### Parameters | Name | Type | Description | | ---- | ------- | ------------ | | ally | address | ally address | ## ReferrerWhitelisted ```solidity theme={null} event ReferrerWhitelisted(address referrer, address ally) ``` *Emitted when a referrer is whitelisted* ### Parameters | Name | Type | Description | | -------- | ------- | ---------------- | | referrer | address | referrer address | | ally | address | ally address | ## ReferrerUnwhitelisted ```solidity theme={null} event ReferrerUnwhitelisted(address referrer) ``` *Emitted when a referrer is unwhitelisted* ### Parameters | Name | Type | Description | | -------- | ------- | ---------------- | | referrer | address | referrer address | ## ReferrerRegistered ```solidity theme={null} event ReferrerRegistered(address trader, address referrer) ``` *Emitted when a trader has a new active referrer* ## AllyRewardDistributed ```solidity theme={null} event AllyRewardDistributed(address ally, address trader, uint256 volumeUsd, uint256 amountGns, uint256 amountValueUsd) ``` *Emitted when ally rewards are distributed for a trade* ### Parameters | Name | Type | Description | | -------------- | ------- | ---------------------------------------- | | ally | address | address of ally | | trader | address | address of trader | | volumeUsd | uint256 | trade volume in usd (1e18 precision) | | amountGns | uint256 | amount of GNS reward (1e18 precision) | | amountValueUsd | uint256 | USD value of GNS reward (1e18 precision) | ## ReferrerRewardDistributed ```solidity theme={null} event ReferrerRewardDistributed(address referrer, address trader, uint256 volumeUsd, uint256 amountGns, uint256 amountValueUsd) ``` *Emitted when referrer rewards are distributed for a trade* ### Parameters | Name | Type | Description | | -------------- | ------- | ---------------------------------------- | | referrer | address | address of referrer | | trader | address | address of trader | | volumeUsd | uint256 | trade volume in usd (1e18 precision) | | amountGns | uint256 | amount of GNS reward (1e18 precision) | | amountValueUsd | uint256 | USD value of GNS reward (1e18 precision) | ## AllyRewardsClaimed ```solidity theme={null} event AllyRewardsClaimed(address ally, uint256 amountGns) ``` *Emitted when an ally claims his pending rewards* ### Parameters | Name | Type | Description | | --------- | ------- | -------------------------- | | ally | address | address of ally | | amountGns | uint256 | GNS pending rewards amount | ## ReferrerRewardsClaimed ```solidity theme={null} event ReferrerRewardsClaimed(address referrer, uint256 amountGns) ``` *Emitted when a referrer claims his pending rewards* ### Parameters | Name | Type | Description | | --------- | ------- | -------------------------- | | referrer | address | address of referrer | | amountGns | uint256 | GNS pending rewards amount | ## NoPendingRewards ```solidity theme={null} error NoPendingRewards() ``` ## AlreadyActive ```solidity theme={null} error AlreadyActive() ``` ## AlreadyInactive ```solidity theme={null} error AlreadyInactive() ``` ## AllyNotActive ```solidity theme={null} error AllyNotActive() ``` # ITradingCallbacksUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/itradingcallbacksutils *Interface for GNSTradingCallbacks facet (inherits types and also contains functions, events, and custom errors)* ## initializeCallbacks ```solidity theme={null} function initializeCallbacks(uint8 _vaultClosingFeeP) external ``` ### Parameters | Name | Type | Description | | ------------------ | ----- | ----------------------------------- | | \_vaultClosingFeeP | uint8 | the % of closing fee going to vault | ## initializeTreasuryAddress ```solidity theme={null} function initializeTreasuryAddress(address _treasury) external ``` *Initialize the treasury address* ### Parameters | Name | Type | Description | | ---------- | ------- | -------------------- | | \_treasury | address | the treasury address | ## updateVaultClosingFeeP ```solidity theme={null} function updateVaultClosingFeeP(uint8 _valueP) external ``` *Update the % of closing fee going to vault* ### Parameters | Name | Type | Description | | -------- | ----- | ----------------------------------- | | \_valueP | uint8 | the % of closing fee going to vault | ## updateTreasuryAddress ```solidity theme={null} function updateTreasuryAddress(address _treasury) external ``` *Updates the treasury address* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------ | | \_treasury | address | the new treasury address | ## claimPendingGovFees ```solidity theme={null} function claimPendingGovFees() external ``` *Claim the pending gov fees for all collaterals* ## openTradeMarketCallback ```solidity theme={null} function openTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external ``` *Executes a pending open trade market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## closeTradeMarketCallback ```solidity theme={null} function closeTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external ``` *Executes a pending close trade market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## executeTriggerOpenOrderCallback ```solidity theme={null} function executeTriggerOpenOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) external ``` *Executes a pending open trigger order (for limit/stop orders)* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## executeTriggerCloseOrderCallback ```solidity theme={null} function executeTriggerCloseOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) external ``` *Executes a pending close trigger order (for tp/sl/liq orders)* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## updateLeverageCallback ```solidity theme={null} function updateLeverageCallback(struct ITradingCallbacks.AggregatorAnswer _a) external ``` *Executes a pending update leverage order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## increasePositionSizeMarketCallback ```solidity theme={null} function increasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external ``` *Executes a pending increase position size market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## decreasePositionSizeMarketCallback ```solidity theme={null} function decreasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external ``` *Executes a pending decrease position size market order* ### Parameters | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | \_a | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) | ## getVaultClosingFeeP ```solidity theme={null} function getVaultClosingFeeP() external view returns (uint8) ``` *Returns the current vaultClosingFeeP value (%)* ## getPendingGovFeesCollateral ```solidity theme={null} function getPendingGovFeesCollateral(uint8 _collateralIndex) external view returns (uint256) ``` *Returns the current pending gov fees for a collateral index (collateral precision)* ## validateTriggerOpenOrderCallback ```solidity theme={null} function validateTriggerOpenOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) external view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v) ``` *Makes open trigger (STOP/LIMIT) checks like slippage, price impact, missed targets and returns cancellation reason if any* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the trade | | \_orderType | enum ITradingStorage.PendingOrderType | the pending order type | | \_open | uint64 | the `open` value from an aggregator answer | | \_high | uint64 | the `high` value from an aggregator answer | | \_low | uint64 | the `low` value from an aggregator answer | ## validateTriggerCloseOrderCallback ```solidity theme={null} function validateTriggerCloseOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) external view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v) ``` *Makes close trigger (SL/TP/LIQ) checks like slippage and price impact and returns cancellation reason if any* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the trade | | \_orderType | enum ITradingStorage.PendingOrderType | the pending order type | | \_open | uint64 | the `open` value from an aggregator answer | | \_high | uint64 | the `high` value from an aggregator answer | | \_low | uint64 | the `low` value from an aggregator answer | ## VaultClosingFeePUpdated ```solidity theme={null} event VaultClosingFeePUpdated(uint8 valueP) ``` *Emitted when vaultClosingFeeP is updated* ### Parameters | Name | Type | Description | | ------ | ----- | ----------------------------------- | | valueP | uint8 | the % of closing fee going to vault | ## PendingGovFeesClaimed ```solidity theme={null} event PendingGovFeesClaimed(uint8 collateralIndex, uint256 amountCollateral) ``` *Emitted when gov fees are claimed for a collateral* ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------------------- | | collateralIndex | uint8 | the collateral index | | amountCollateral | uint256 | the amount of fees claimed (collateral precision) | ## MarketExecuted ```solidity theme={null} event MarketExecuted(struct ITradingStorage.Id orderId, address user, uint32 index, struct ITradingStorage.Trade t, bool open, uint256 oraclePrice, uint256 marketPrice, uint256 liqPrice, uint256 priceImpactP, int256 percentProfit, uint256 amountSentToTrader, uint256 collateralPriceUsd) ``` *Emitted when a market order is executed (open/close)* ### Parameters | Name | Type | Description | | ------------------ | ---------------------------- | ------------------------------------------------------------ | | orderId | struct ITradingStorage.Id | the id of the corresponding pending market order | | user | address | trade user | | index | uint32 | trade index | | t | struct ITradingStorage.Trade | the trade object | | open | bool | true for a market open order, false for a market close order | | oraclePrice | uint256 | the oracle price without spread/impact (1e10 precision) | | marketPrice | uint256 | the price at which the trade was executed (1e10 precision) | | liqPrice | uint256 | trade liquidation price (1e10 precision) | | priceImpactP | uint256 | the price impact in percentage (1e10 precision) | | percentProfit | int256 | the profit in percentage (1e10 precision) | | amountSentToTrader | uint256 | the final amount of collateral sent to the trader | | collateralPriceUsd | uint256 | the price of the collateral in USD (1e8 precision) | ## LimitExecuted ```solidity theme={null} event LimitExecuted(struct ITradingStorage.Id orderId, address user, uint32 index, uint32 limitIndex, struct ITradingStorage.Trade t, address triggerCaller, enum ITradingStorage.PendingOrderType orderType, uint256 oraclePrice, uint256 marketPrice, uint256 liqPrice, uint256 priceImpactP, int256 percentProfit, uint256 amountSentToTrader, uint256 collateralPriceUsd, bool exactExecution) ``` *Emitted when a limit/stop order is executed* ### Parameters | Name | Type | Description | | ------------------ | ------------------------------------- | ---------------------------------------------------------- | | orderId | struct ITradingStorage.Id | the id of the corresponding pending trigger order | | user | address | trade user | | index | uint32 | trade index | | limitIndex | uint32 | limit index | | t | struct ITradingStorage.Trade | the trade object | | triggerCaller | address | the address that triggered the limit order | | orderType | enum ITradingStorage.PendingOrderType | the type of the pending order | | oraclePrice | uint256 | the oracle price without spread/impact (1e10 precision) | | marketPrice | uint256 | the price at which the trade was executed (1e10 precision) | | liqPrice | uint256 | trade liquidation price (1e10 precision) | | priceImpactP | uint256 | the price impact in percentage (1e10 precision) | | percentProfit | int256 | the profit in percentage (1e10 precision) | | amountSentToTrader | uint256 | the final amount of collateral sent to the trader | | collateralPriceUsd | uint256 | the price of the collateral in USD (1e8 precision) | | exactExecution | bool | true if guaranteed execution was used | ## MarketOpenCanceled ```solidity theme={null} event MarketOpenCanceled(struct ITradingStorage.Id orderId, address trader, uint256 pairIndex, enum ITradingCallbacks.CancelReason cancelReason) ``` *Emitted when a pending market open order is canceled* ### Parameters | Name | Type | Description | | ------------ | ----------------------------------- | ----------------------------------------- | | orderId | struct ITradingStorage.Id | order id of the pending market open order | | trader | address | address of the trader | | pairIndex | uint256 | index of the trading pair | | cancelReason | enum ITradingCallbacks.CancelReason | reason for the cancellation | ## MarketCloseCanceled ```solidity theme={null} event MarketCloseCanceled(struct ITradingStorage.Id orderId, address trader, uint256 pairIndex, uint256 index, enum ITradingCallbacks.CancelReason cancelReason) ``` *Emitted when a pending market close order is canceled* ### Parameters | Name | Type | Description | | ------------ | ----------------------------------- | ------------------------------------------ | | orderId | struct ITradingStorage.Id | order id of the pending market close order | | trader | address | address of the trader | | pairIndex | uint256 | index of the trading pair | | index | uint256 | index of the trade for trader | | cancelReason | enum ITradingCallbacks.CancelReason | reason for the cancellation | ## TriggerOrderCanceled ```solidity theme={null} event TriggerOrderCanceled(struct ITradingStorage.Id orderId, address triggerCaller, enum ITradingStorage.PendingOrderType orderType, enum ITradingCallbacks.CancelReason cancelReason) ``` *Emitted when a pending trigger order is canceled* ### Parameters | Name | Type | Description | | ------------- | ------------------------------------- | ------------------------------------- | | orderId | struct ITradingStorage.Id | order id of the pending trigger order | | triggerCaller | address | address of the trigger caller | | orderType | enum ITradingStorage.PendingOrderType | type of the pending trigger order | | cancelReason | enum ITradingCallbacks.CancelReason | reason for the cancellation | ## BorrowingFeeCharged ```solidity theme={null} event BorrowingFeeCharged(address trader, uint32 index, uint8 collateralIndex, uint256 amountCollateral) ``` ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------- | | trader | address | address of the trader | | index | uint32 | index of the trade | | collateralIndex | uint8 | index of the collateral | | amountCollateral | uint256 | amount charged (collateral precision) | # ITradingCommonUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/itradingcommonutils *Interface for TradingCommonUtils library* ## TradePriceImpactInput ```solidity theme={null} struct TradePriceImpactInput { struct ITradingStorage.Trade trade; uint256 oraclePrice; uint256 spreadP; uint256 positionSizeCollateral; } ``` ## GovFeeCharged ```solidity theme={null} event GovFeeCharged(address trader, uint8 collateralIndex, uint256 amountCollateral) ``` *Emitted when gov fee is charged* ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------- | | trader | address | address of the trader | | collateralIndex | uint8 | index of the collateral | | amountCollateral | uint256 | amount charged (collateral precision) | ## ReferralFeeCharged ```solidity theme={null} event ReferralFeeCharged(address trader, uint8 collateralIndex, uint256 amountCollateral) ``` *Emitted when referral fee is charged* ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------- | | trader | address | address of the trader | | collateralIndex | uint8 | index of the collateral | | amountCollateral | uint256 | amount charged (collateral precision) | ## GnsOtcFeeCharged ```solidity theme={null} event GnsOtcFeeCharged(address trader, uint8 collateralIndex, uint256 amountCollateral) ``` *Emitted when GNS otc fee is charged* ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------- | | trader | address | address of the trader | | collateralIndex | uint8 | index of the collateral | | amountCollateral | uint256 | amount charged (collateral precision) | ## TriggerFeeCharged ```solidity theme={null} event TriggerFeeCharged(address trader, uint8 collateralIndex, uint256 amountCollateral) ``` *Emitted when trigger fee is charged* ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------- | | trader | address | address of the trader | | collateralIndex | uint8 | index of the collateral | | amountCollateral | uint256 | amount charged (collateral precision) | ## GTokenFeeCharged ```solidity theme={null} event GTokenFeeCharged(address trader, uint8 collateralIndex, uint256 amountCollateral) ``` *Emitted when gToken fee is charged* ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------- | | trader | address | address of the trader | | collateralIndex | uint8 | index of the collateral | | amountCollateral | uint256 | amount charged (collateral precision) | # ITradingInteractionsUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils *Interface for GNSTradingInteractions facet (inherits types and also contains functions, events, and custom errors)* ## initializeTrading ```solidity theme={null} function initializeTrading(uint16 _marketOrdersTimeoutBlocks, address[] _usersByPassTriggerLink) external ``` *Initializes the trading facet* ### Parameters | Name | Type | Description | | --------------------------- | ---------- | ----------------------------------------------------------------------- | | \_marketOrdersTimeoutBlocks | uint16 | The number of blocks after which a market order is considered timed out | | \_usersByPassTriggerLink | address\[] | | ## updateMarketOrdersTimeoutBlocks ```solidity theme={null} function updateMarketOrdersTimeoutBlocks(uint16 _valueBlocks) external ``` *Updates marketOrdersTimeoutBlocks* ### Parameters | Name | Type | Description | | ------------- | ------ | ------------------------------------------- | | \_valueBlocks | uint16 | blocks after which a market order times out | ## updateByPassTriggerLink ```solidity theme={null} function updateByPassTriggerLink(address[] _users, bool[] _shouldByPass) external ``` *Updates the users that can bypass the link cost of triggerOrder* ### Parameters | Name | Type | Description | | -------------- | ---------- | ---------------------------------------------------------------- | | \_users | address\[] | array of addresses that can bypass the link cost of triggerOrder | | \_shouldByPass | bool\[] | whether each user should bypass the link cost | ## setTradingDelegate ```solidity theme={null} function setTradingDelegate(address _delegate) external ``` \_Sets *delegate as the new delegate of caller (can call delegatedAction)* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------ | | \_delegate | address | the new delegate address | ## removeTradingDelegate ```solidity theme={null} function removeTradingDelegate() external ``` *Removes the delegate of caller (can't call delegatedAction)* ## delegatedTradingAction ```solidity theme={null} function delegatedTradingAction(address _trader, bytes _callData) external returns (bytes) ``` \_Caller executes a trading action on behalf of *trader using delegatecall* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------------------------------------ | | \_trader | address | the trader address to execute the trading action for | | \_callData | bytes | the data to be executed (open trade/close trade, etc.) | ## openTrade ```solidity theme={null} function openTrade(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external ``` *Opens a new trade/limit order/stop order* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | the trade to be opened | | \_maxSlippageP | uint16 | the maximum allowed slippage % when open the trade (1e3 precision) | | \_referrer | address | the address of the referrer (can only be set once for a trader) | ## openTradeNative ```solidity theme={null} function openTradeNative(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external payable ``` *Wraps native token and opens a new trade/limit order/stop order* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | the trade to be opened | | \_maxSlippageP | uint16 | the maximum allowed slippage % when open the trade (1e3 precision) | | \_referrer | address | the address of the referrer (can only be set once for a trader) | ## updateMaxClosingSlippageP ```solidity theme={null} function updateMaxClosingSlippageP(uint32 _index, uint16 _maxSlippageP) external ``` *Updates existing trade's max closing slippage % for caller* ### Parameters | Name | Type | Description | | -------------- | ------ | ------------------------------------------ | | \_index | uint32 | index of trade | | \_maxSlippageP | uint16 | new max closing slippage % (1e3 precision) | ## closeTradeMarket ```solidity theme={null} function closeTradeMarket(uint32 _index, uint64 _expectedPrice) external ``` *Closes an open trade (market order) for caller* ### Parameters | Name | Type | Description | | --------------- | ------ | ------------------------------------------------------------------- | | \_index | uint32 | the index of the trade of caller | | \_expectedPrice | uint64 | expected closing price, used to check max slippage (1e10 precision) | ## updateOpenOrder ```solidity theme={null} function updateOpenOrder(uint32 _index, uint64 _triggerPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external ``` *Updates an existing limit/stop order for caller* ### Parameters | Name | Type | Description | | -------------- | ------ | ------------------------------------------------------ | | \_index | uint32 | index of limit/stop order of caller | | \_triggerPrice | uint64 | new trigger price of limit/stop order (1e10 precision) | | \_tp | uint64 | new tp of limit/stop order (1e10 precision) | | \_sl | uint64 | new sl of limit/stop order (1e10 precision) | | \_maxSlippageP | uint16 | new max slippage % of limit/stop order (1e3 precision) | ## cancelOpenOrder ```solidity theme={null} function cancelOpenOrder(uint32 _index) external ``` *Cancels an open limit/stop order for caller* ### Parameters | Name | Type | Description | | ------- | ------ | ----------------------------------- | | \_index | uint32 | index of limit/stop order of caller | ## updateTp ```solidity theme={null} function updateTp(uint32 _index, uint64 _newTp) external ``` *Updates the tp of an open trade for caller* ### Parameters | Name | Type | Description | | ------- | ------ | ------------------------------------- | | \_index | uint32 | index of open trade of caller | | \_newTp | uint64 | new tp of open trade (1e10 precision) | ## updateSl ```solidity theme={null} function updateSl(uint32 _index, uint64 _newSl) external ``` *Updates the sl of an open trade for caller* ### Parameters | Name | Type | Description | | ------- | ------ | ------------------------------------- | | \_index | uint32 | index of open trade of caller | | \_newSl | uint64 | new sl of open trade (1e10 precision) | ## triggerOrder ```solidity theme={null} function triggerOrder(uint256 _packed) external ``` *Initiates a new trigger order (for tp/sl/liq/limit/stop orders)* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------------------------------------------------- | | \_packed | uint256 | the packed data of the trigger order (orderType, trader, index) | ## cancelOrderAfterTimeout ```solidity theme={null} function cancelOrderAfterTimeout(uint32 _orderIndex) external ``` *Safety function in case oracles don't answer in time, allows caller to cancel a pending order and if relevant claim back any stuck collateral Only allowed for MARKET\_OPEN, MARKET\_CLOSE, UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE orders* ### Parameters | Name | Type | Description | | ------------ | ------ | ------------------------------------- | | \_orderIndex | uint32 | the id of the pending order to cancel | ## updateLeverage ```solidity theme={null} function updateLeverage(uint32 _index, uint24 _newLeverage) external ``` *Update trade leverage* ### Parameters | Name | Type | Description | | ------------- | ------ | ------------------ | | \_index | uint32 | index of trade | | \_newLeverage | uint24 | new leverage (1e3) | ## increasePositionSize ```solidity theme={null} function increasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice, uint16 _maxSlippageP) external ``` *Increase trade position size* ### Parameters | Name | Type | Description | | ----------------- | ------- | -------------------------------------------- | | \_index | uint32 | index of trade | | \_collateralDelta | uint120 | collateral to add (collateral precision) | | \_leverageDelta | uint24 | partial trade leverage (1e3) | | \_expectedPrice | uint64 | expected price of execution (1e10 precision) | | \_maxSlippageP | uint16 | max slippage % (1e3) | ## decreasePositionSize ```solidity theme={null} function decreasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice) external ``` *Decrease trade position size* ### Parameters | Name | Type | Description | | ----------------- | ------- | ------------------------------------------------------------------- | | \_index | uint32 | index of trade | | \_collateralDelta | uint120 | collateral to remove (collateral precision) | | \_leverageDelta | uint24 | leverage to reduce by (1e3) | | \_expectedPrice | uint64 | expected closing price, used to check max slippage (1e10 precision) | ## getWrappedNativeToken ```solidity theme={null} function getWrappedNativeToken() external view returns (address) ``` *Returns the wrapped native token or address(0) if the current chain, or the wrapped token, is not supported.* ## isWrappedNativeToken ```solidity theme={null} function isWrappedNativeToken(address _token) external view returns (bool) ``` *Returns true if the token is the wrapped native token for the current chain, where supported.* ### Parameters | Name | Type | Description | | ------- | ------- | ------------- | | \_token | address | token address | ## getTradingDelegate ```solidity theme={null} function getTradingDelegate(address _trader) external view returns (address) ``` *Returns the address a trader delegates his trading actions to* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getMarketOrdersTimeoutBlocks ```solidity theme={null} function getMarketOrdersTimeoutBlocks() external view returns (uint16) ``` *Returns the current marketOrdersTimeoutBlocks value* ## getByPassTriggerLink ```solidity theme={null} function getByPassTriggerLink(address _user) external view returns (bool) ``` *Returns whether a user bypasses trigger link costs* ### Parameters | Name | Type | Description | | ------ | ------- | ------------------- | | \_user | address | address of the user | ## MarketOrdersTimeoutBlocksUpdated ```solidity theme={null} event MarketOrdersTimeoutBlocksUpdated(uint256 newValueBlocks) ``` *Emitted when marketOrdersTimeoutBlocks is updated* ### Parameters | Name | Type | Description | | -------------- | ------- | ------------------------------------------ | | newValueBlocks | uint256 | the new value of marketOrdersTimeoutBlocks | ## ByPassTriggerLinkUpdated ```solidity theme={null} event ByPassTriggerLinkUpdated(address user, bool bypass) ``` *Emitted when a user is allowed/disallowed to bypass the link cost of triggerOrder* ### Parameters | Name | Type | Description | | ------ | ------- | --------------------------------------------------------- | | user | address | address of the user | | bypass | bool | whether the user can bypass the link cost of triggerOrder | ## MarketOrderInitiated ```solidity theme={null} event MarketOrderInitiated(struct ITradingStorage.Id orderId, address trader, uint16 pairIndex, bool open) ``` *Emitted when a market order is initiated* ### Parameters | Name | Type | Description | | --------- | ------------------------- | ---------------------------------------------------------- | | orderId | struct ITradingStorage.Id | price aggregator order id of the pending market order | | trader | address | address of the trader | | pairIndex | uint16 | index of the trading pair | | open | bool | whether the market order is for opening or closing a trade | ## OpenOrderPlaced ```solidity theme={null} event OpenOrderPlaced(address trader, uint16 pairIndex, uint32 index) ``` *Emitted when a new limit/stop order is placed* ### Parameters | Name | Type | Description | | --------- | ------- | ---------------------------------------- | | trader | address | address of the trader | | pairIndex | uint16 | index of the trading pair | | index | uint32 | index of the open limit order for caller | ## OpenLimitUpdated ```solidity theme={null} event OpenLimitUpdated(address trader, uint16 pairIndex, uint32 index, uint64 newPrice, uint64 newTp, uint64 newSl, uint64 maxSlippageP) ``` ### Parameters | Name | Type | Description | | ------------ | ------- | --------------------------------------------- | | trader | address | address of the trader | | pairIndex | uint16 | index of the trading pair | | index | uint32 | index of the open limit/stop order for caller | | newPrice | uint64 | new trigger price (1e10 precision) | | newTp | uint64 | new tp (1e10 precision) | | newSl | uint64 | new sl (1e10 precision) | | maxSlippageP | uint64 | new max slippage % (1e3 precision) | ## OpenLimitCanceled ```solidity theme={null} event OpenLimitCanceled(address trader, uint16 pairIndex, uint32 index) ``` *Emitted when a limit/stop order is canceled (collateral sent back to trader)* ### Parameters | Name | Type | Description | | --------- | ------- | --------------------------------------------- | | trader | address | address of the trader | | pairIndex | uint16 | index of the trading pair | | index | uint32 | index of the open limit/stop order for caller | ## TriggerOrderInitiated ```solidity theme={null} event TriggerOrderInitiated(struct ITradingStorage.Id orderId, address trader, uint16 pairIndex, bool byPassesLinkCost) ``` *Emitted when a trigger order is initiated (tp/sl/liq/limit/stop orders)* ### Parameters | Name | Type | Description | | ---------------- | ------------------------- | ------------------------------------------------------ | | orderId | struct ITradingStorage.Id | price aggregator order id of the pending trigger order | | trader | address | address of the trader | | pairIndex | uint16 | index of the trading pair | | byPassesLinkCost | bool | whether the caller bypasses the link cost | ## ChainlinkCallbackTimeout ```solidity theme={null} event ChainlinkCallbackTimeout(struct ITradingStorage.Id pendingOrderId, uint256 pairIndex) ``` *Emitted when a pending market order is canceled due to timeout* ### Parameters | Name | Type | Description | | -------------- | ------------------------- | ------------------------- | | pendingOrderId | struct ITradingStorage.Id | id of the pending order | | pairIndex | uint256 | index of the trading pair | ## CouldNotCloseTrade ```solidity theme={null} event CouldNotCloseTrade(address trader, uint16 pairIndex, uint32 index) ``` *Emitted when a pending market order is canceled due to timeout and new closeTradeMarket() call failed* ### Parameters | Name | Type | Description | | --------- | ------- | ---------------------------------- | | trader | address | address of the trader | | pairIndex | uint16 | index of the trading pair | | index | uint32 | index of the open trade for caller | ## NativeTokenWrapped ```solidity theme={null} event NativeTokenWrapped(address trader, uint256 nativeTokenAmount) ``` *Emitted when a native token is wrapped* ### Parameters | Name | Type | Description | | ----------------- | ------- | ------------------------------ | | trader | address | address of the trader | | nativeTokenAmount | uint256 | amount of native token wrapped | ## NotWrappedNativeToken ```solidity theme={null} error NotWrappedNativeToken() ``` ## DelegateNotApproved ```solidity theme={null} error DelegateNotApproved() ``` ## PriceZero ```solidity theme={null} error PriceZero() ``` ## AboveExposureLimits ```solidity theme={null} error AboveExposureLimits() ``` ## CollateralNotActive ```solidity theme={null} error CollateralNotActive() ``` ## PriceImpactTooHigh ```solidity theme={null} error PriceImpactTooHigh() ``` ## NoTrade ```solidity theme={null} error NoTrade() ``` ## NoOrder ```solidity theme={null} error NoOrder() ``` ## AlreadyBeingMarketClosed ```solidity theme={null} error AlreadyBeingMarketClosed() ``` ## ConflictingPendingOrder ```solidity theme={null} error ConflictingPendingOrder(enum ITradingStorage.PendingOrderType) ``` ## WrongLeverage ```solidity theme={null} error WrongLeverage() ``` ## WrongTp ```solidity theme={null} error WrongTp() ``` ## WrongSl ```solidity theme={null} error WrongSl() ``` ## WaitTimeout ```solidity theme={null} error WaitTimeout() ``` ## PendingTrigger ```solidity theme={null} error PendingTrigger() ``` ## NoSl ```solidity theme={null} error NoSl() ``` ## NoTp ```solidity theme={null} error NoTp() ``` ## NotYourOrder ```solidity theme={null} error NotYourOrder() ``` ## DelegatedActionNotAllowed ```solidity theme={null} error DelegatedActionNotAllowed() ``` ## InsufficientCollateral ```solidity theme={null} error InsufficientCollateral() ``` # ITradingStorageUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/itradingstorageutils *Interface for GNSTradingStorage facet (inherits types and also contains functions, events, and custom errors)* ## initializeTradingStorage ```solidity theme={null} function initializeTradingStorage(address _gns, address _gnsStaking, address[] _collaterals, address[] _gTokens) external ``` *Initializes the trading storage facet* ### Parameters | Name | Type | Description | | ------------- | ---------- | ----------------------------------- | | \_gns | address | address of the gns token | | \_gnsStaking | address | address of the gns staking contract | | \_collaterals | address\[] | | | \_gTokens | address\[] | | ## updateTradingActivated ```solidity theme={null} function updateTradingActivated(enum ITradingStorage.TradingActivated _activated) external ``` *Updates the trading activated state* ### Parameters | Name | Type | Description | | ----------- | ------------------------------------- | ------------------------------- | | \_activated | enum ITradingStorage.TradingActivated | the new trading activated state | ## addCollateral ```solidity theme={null} function addCollateral(address _collateral, address _gToken) external ``` *Adds a new supported collateral* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------------------- | | \_collateral | address | the address of the collateral | | \_gToken | address | the gToken contract of the collateral | ## toggleCollateralActiveState ```solidity theme={null} function toggleCollateralActiveState(uint8 _collateralIndex) external ``` *Toggles the active state of a supported collateral* ### Parameters | Name | Type | Description | | ----------------- | ----- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | ## updateGToken ```solidity theme={null} function updateGToken(address _collateral, address _gToken) external ``` *Updates the contracts of a supported collateral trading stack* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------------------- | | \_collateral | address | address of the collateral | | \_gToken | address | the gToken contract of the collateral | ## storeTrade ```solidity theme={null} function storeTrade(struct ITradingStorage.Trade _trade, struct ITradingStorage.TradeInfo _tradeInfo) external returns (struct ITradingStorage.Trade) ``` *Stores a new trade (trade/limit/stop)* ### Parameters | Name | Type | Description | | ----------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade to be stored | | \_tradeInfo | [ITradingStorage.TradeInfo](/developer/technical-reference/contracts/interfaces/types/itradingstorage#tradeinfo) | trade info to be stored | ## updateTradeMaxClosingSlippageP ```solidity theme={null} function updateTradeMaxClosingSlippageP(struct ITradingStorage.Id _tradeId, uint16 _maxSlippageP) external ``` *Updates an existing trade max closing slippage %* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the trade | | \_maxSlippageP | uint16 | new max slippage % (1e3 precision) | ## updateTradeCollateralAmount ```solidity theme={null} function updateTradeCollateralAmount(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount) external ``` *Updates an open trade collateral* ### Parameters | Name | Type | Description | | ------------------ | -------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade | | \_collateralAmount | uint120 | new collateral amount value (collateral precision) | ## updateTradePosition ```solidity theme={null} function updateTradePosition(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount, uint24 _leverage, uint64 _openPrice, bool _isPartialIncrease, bool _isPnlPositive) external ``` *Updates an open trade collateral* ### Parameters | Name | Type | Description | | ------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade | | \_collateralAmount | uint120 | new collateral amount value (collateral precision) | | \_leverage | uint24 | new leverage value | | \_openPrice | uint64 | new open price value | | \_isPartialIncrease | bool | refreshes trade liquidation params if true | | \_isPnlPositive | bool | whether the pnl is positive (only relevant when closing) | ## updateOpenOrderDetails ```solidity theme={null} function updateOpenOrderDetails(struct ITradingStorage.Id _tradeId, uint64 _openPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external ``` *Updates an open order details (limit/stop)* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------- | ------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade | | \_openPrice | uint64 | new open price (1e10) | | \_tp | uint64 | new take profit price (1e10) | | \_sl | uint64 | new stop loss price (1e10) | | \_maxSlippageP | uint16 | new max slippage % value (1e3) | ## updateTradeTp ```solidity theme={null} function updateTradeTp(struct ITradingStorage.Id _tradeId, uint64 _newTp) external ``` *Updates the take profit of an open trade* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ------------------------------------ | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id | | \_newTp | uint64 | the new take profit (1e10 precision) | ## updateTradeSl ```solidity theme={null} function updateTradeSl(struct ITradingStorage.Id _tradeId, uint64 _newSl) external ``` *Updates the stop loss of an open trade* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | --------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id | | \_newSl | uint64 | the new sl (1e10 precision) | ## closeTrade ```solidity theme={null} function closeTrade(struct ITradingStorage.Id _tradeId, bool _isPnlPositive) external ``` *Marks an open trade/limit/stop as closed* ### Parameters | Name | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------- | --------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id | | \_isPnlPositive | bool | whether the pnl is positive | ## storePendingOrder ```solidity theme={null} function storePendingOrder(struct ITradingStorage.PendingOrder _pendingOrder) external returns (struct ITradingStorage.PendingOrder) ``` *Stores a new pending order* ### Parameters | Name | Type | Description | | -------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------ | | \_pendingOrder | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | the pending order to be stored | ## closePendingOrder ```solidity theme={null} function closePendingOrder(struct ITradingStorage.Id _orderId) external ``` *Closes a pending order* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------- | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the pending order to be closed | ## getCollateral ```solidity theme={null} function getCollateral(uint8 _index) external view returns (struct ITradingStorage.Collateral) ``` *Returns collateral data by index* ### Parameters | Name | Type | Description | | ------- | ----- | ------------------------------------- | | \_index | uint8 | the index of the supported collateral | ## isCollateralActive ```solidity theme={null} function isCollateralActive(uint8 _index) external view returns (bool) ``` *Returns whether can open new trades with a collateral* ### Parameters | Name | Type | Description | | ------- | ----- | ------------------------------------ | | \_index | uint8 | the index of the collateral to check | ## isCollateralListed ```solidity theme={null} function isCollateralListed(uint8 _index) external view returns (bool) ``` *Returns whether a collateral has been listed* ### Parameters | Name | Type | Description | | ------- | ----- | ------------------------------------ | | \_index | uint8 | the index of the collateral to check | ## getCollateralsCount ```solidity theme={null} function getCollateralsCount() external view returns (uint8) ``` *Returns the number of supported collaterals* ## getCollaterals ```solidity theme={null} function getCollaterals() external view returns (struct ITradingStorage.Collateral[]) ``` *Returns the supported collaterals* ## getCollateralIndex ```solidity theme={null} function getCollateralIndex(address _collateral) external view returns (uint8) ``` *Returns the index of a supported collateral* ### Parameters | Name | Type | Description | | ------------ | ------- | ----------------------------- | | \_collateral | address | the address of the collateral | ## getTradingActivated ```solidity theme={null} function getTradingActivated() external view returns (enum ITradingStorage.TradingActivated) ``` *Returns the trading activated state* ## getTraderStored ```solidity theme={null} function getTraderStored(address _trader) external view returns (bool) ``` *Returns whether a trader is stored in the traders array* ### Parameters | Name | Type | Description | | -------- | ------- | --------------- | | \_trader | address | trader to check | ## getTradersCount ```solidity theme={null} function getTradersCount() external view returns (uint256) ``` *Returns the length of the traders array* ## getTraders ```solidity theme={null} function getTraders(uint32 _offset, uint32 _limit) external view returns (address[]) ``` *Returns all traders that have open trades using a pagination system* ### Parameters | Name | Type | Description | | -------- | ------ | -------------------------------- | | \_offset | uint32 | start index in the traders array | | \_limit | uint32 | end index in the traders array | ## getTrade ```solidity theme={null} function getTrade(address _trader, uint32 _index) external view returns (struct ITradingStorage.Trade) ``` *Returns open trade/limit/stop order* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------------------- | | \_trader | address | address of the trader | | \_index | uint32 | index of the trade for trader | ## getTrades ```solidity theme={null} function getTrades(address _trader) external view returns (struct ITradingStorage.Trade[]) ``` *Returns all open trades/limit/stop orders for a trader* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getAllTradesForTraders ```solidity theme={null} function getAllTradesForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.Trade[]) ``` *Returns all trade/limit/stop orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | ------------------------------------ | | \_traders | address\[] | list of traders to return trades for | | \_offset | uint256 | index of first trade to return | | \_limit | uint256 | index of last trade to return | ## getAllTrades ```solidity theme={null} function getAllTrades(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.Trade[]) ``` *Returns all trade/limit/stop orders using a pagination system. Calls `getAllTradesForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ------------------------------ | | \_offset | uint256 | index of first trade to return | | \_limit | uint256 | index of last trade to return | ## getTradeInfo ```solidity theme={null} function getTradeInfo(address _trader, uint32 _index) external view returns (struct ITradingStorage.TradeInfo) ``` *Returns trade info of an open trade/limit/stop order* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------------------- | | \_trader | address | address of the trader | | \_index | uint32 | index of the trade for trader | ## getTradeInfos ```solidity theme={null} function getTradeInfos(address _trader) external view returns (struct ITradingStorage.TradeInfo[]) ``` *Returns all trade infos of open trade/limit/stop orders for a trader* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getAllTradeInfosForTraders ```solidity theme={null} function getAllTradeInfosForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.TradeInfo[]) ``` *Returns all trade infos of open trade/limit/stop orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | --------------------------------------- | | \_traders | address\[] | list of traders to return tradeInfo for | | \_offset | uint256 | index of first tradeInfo to return | | \_limit | uint256 | index of last tradeInfo to return | ## getAllTradeInfos ```solidity theme={null} function getAllTradeInfos(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.TradeInfo[]) ``` *Returns all trade infos of open trade/limit/stop orders using a pagination system. Calls `getAllTradeInfosForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ---------------------------------- | | \_offset | uint256 | index of first tradeInfo to return | | \_limit | uint256 | index of last tradeInfo to return | ## getPendingOrder ```solidity theme={null} function getPendingOrder(struct ITradingStorage.Id _orderId) external view returns (struct ITradingStorage.PendingOrder) ``` *Returns a pending ordeer* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ----------------------- | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the pending order | ## getPendingOrders ```solidity theme={null} function getPendingOrders(address _user) external view returns (struct ITradingStorage.PendingOrder[]) ``` *Returns all pending orders for a trader* ### Parameters | Name | Type | Description | | ------ | ------- | --------------------- | | \_user | address | address of the trader | ## getAllPendingOrdersForTraders ```solidity theme={null} function getAllPendingOrdersForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.PendingOrder[]) ``` *Returns all pending orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | ------------------------------------------ | | \_traders | address\[] | list of traders to return pendingOrder for | | \_offset | uint256 | index of first pendingOrder to return | | \_limit | uint256 | index of last pendingOrder to return | ## getAllPendingOrders ```solidity theme={null} function getAllPendingOrders(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.PendingOrder[]) ``` *Returns all pending orders using a pagination system Calls `getAllPendingOrdersForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ------------------------------------- | | \_offset | uint256 | index of first pendingOrder to return | | \_limit | uint256 | index of last pendingOrder to return | ## getTradePendingOrderBlock ```solidity theme={null} function getTradePendingOrderBlock(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType) external view returns (uint256) ``` *Returns the block number of the pending order for a trade (0 = doesn't exist)* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | --------------------------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the trade | | \_orderType | enum ITradingStorage.PendingOrderType | pending order type to check | ## getCounters ```solidity theme={null} function getCounters(address _trader, enum ITradingStorage.CounterType _type) external view returns (struct ITradingStorage.Counter) ``` *Returns the counters of a trader (currentIndex / open count for trades/tradeInfos and pendingOrders mappings)* ### Parameters | Name | Type | Description | | -------- | -------------------------------- | -------------------------------------- | | \_trader | address | address of the trader | | \_type | enum ITradingStorage.CounterType | the counter type (trade/pending order) | ## getCountersForTraders ```solidity theme={null} function getCountersForTraders(address[] _traders, enum ITradingStorage.CounterType _type) external view returns (struct ITradingStorage.Counter[]) ``` *Returns the counters for a list of traders* ### Parameters | Name | Type | Description | | --------- | -------------------------------- | -------------------------------------- | | \_traders | address\[] | the list of traders | | \_type | enum ITradingStorage.CounterType | the counter type (trade/pending order) | ## getGToken ```solidity theme={null} function getGToken(uint8 _collateralIndex) external view returns (address) ``` *Returns the address of the gToken for a collateral stack* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------------------------- | | \_collateralIndex | uint8 | the index of the supported collateral | ## getTradeLiquidationParams ```solidity theme={null} function getTradeLiquidationParams(address _trader, uint32 _index) external view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Returns the liquidation params for a trade* ### Parameters | Name | Type | Description | | -------- | ------- | ----------------------------- | | \_trader | address | address of the trader | | \_index | uint32 | index of the trade for trader | ## getTradesLiquidationParams ```solidity theme={null} function getTradesLiquidationParams(address _trader) external view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Returns all trade liquidation params of open trade/limit/stop orders for a trader* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_trader | address | address of the trader | ## getAllTradesLiquidationParamsForTraders ```solidity theme={null} function getAllTradesLiquidationParamsForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Returns all trade liquidation params of open trade/limit/stop orders using a pagination system* ### Parameters | Name | Type | Description | | --------- | ---------- | ---------------------------------------- | | \_traders | address\[] | list of traders to return liq params for | | \_offset | uint256 | index of first liq param to return | | \_limit | uint256 | index of last liq param to return | ## getAllTradesLiquidationParams ```solidity theme={null} function getAllTradesLiquidationParams(uint256 _offset, uint256 _limit) external view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Returns all trade liquidation params of open trade/limit/stop orders using a pagination system Calls `getAllTradesLiquidationParamsForTraders` internally with all traders.* ### Parameters | Name | Type | Description | | -------- | ------- | ---------------------------------- | | \_offset | uint256 | index of first liq param to return | | \_limit | uint256 | index of last liq param to return | ## getCurrentContractsVersion ```solidity theme={null} function getCurrentContractsVersion() external pure returns (enum ITradingStorage.ContractsVersion) ``` *Returns the current contracts version* ## TradingActivatedUpdated ```solidity theme={null} event TradingActivatedUpdated(enum ITradingStorage.TradingActivated activated) ``` *Emitted when the trading activated state is updated* ### Parameters | Name | Type | Description | | --------- | ------------------------------------- | ------------------------------- | | activated | enum ITradingStorage.TradingActivated | the new trading activated state | ## CollateralAdded ```solidity theme={null} event CollateralAdded(address collateral, uint8 index, address gToken) ``` *Emitted when a new supported collateral is added* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------------------- | | collateral | address | the address of the collateral | | index | uint8 | the index of the supported collateral | | gToken | address | the gToken contract of the collateral | ## CollateralUpdated ```solidity theme={null} event CollateralUpdated(uint8 index, bool isActive) ``` *Emitted when an existing supported collateral active state is updated* ### Parameters | Name | Type | Description | | -------- | ----- | ------------------------------------- | | index | uint8 | the index of the supported collateral | | isActive | bool | the new active state | ## CollateralDisabled ```solidity theme={null} event CollateralDisabled(uint8 index) ``` *Emitted when an existing supported collateral is disabled (can still close trades but not open new ones)* ### Parameters | Name | Type | Description | | ----- | ----- | ------------------------------------- | | index | uint8 | the index of the supported collateral | ## GTokenUpdated ```solidity theme={null} event GTokenUpdated(address collateral, uint8 index, address gToken) ``` *Emitted when the contracts of a supported collateral trading stack are updated* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------------------------- | | collateral | address | the address of the collateral | | index | uint8 | the index of the supported collateral | | gToken | address | the gToken contract of the collateral | ## TradeStored ```solidity theme={null} event TradeStored(address user, uint32 index, struct ITradingStorage.Trade trade, struct ITradingStorage.TradeInfo tradeInfo, struct IPairsStorage.GroupLiquidationParams liquidationParams) ``` *Emitted when a new trade is stored* ### Parameters | Name | Type | Description | | ----------------- | ------------------------------------------- | ----------------------------------- | | user | address | trade user | | index | uint32 | trade index | | trade | struct ITradingStorage.Trade | the trade stored | | tradeInfo | struct ITradingStorage.TradeInfo | the trade info stored | | liquidationParams | struct IPairsStorage.GroupLiquidationParams | the trade liquidation params stored | ## TradeMaxClosingSlippagePUpdated ```solidity theme={null} event TradeMaxClosingSlippagePUpdated(address user, uint32 index, uint16 maxClosingSlippageP) ``` *Emitted when the max closing slippage % of an open trade is updated* ### Parameters | Name | Type | Description | | ------------------- | ------- | ------------------------------------------------ | | user | address | trade user | | index | uint32 | trade index | | maxClosingSlippageP | uint16 | new max closing slippage % value (1e3 precision) | ## TradeCollateralUpdated ```solidity theme={null} event TradeCollateralUpdated(address user, uint32 index, uint120 collateralAmount) ``` *Emitted when an open trade collateral is updated* ### Parameters | Name | Type | Description | | ---------------- | ------- | ------------------------------------------- | | user | address | trade user | | index | uint32 | trade index | | collateralAmount | uint120 | new collateral value (collateral precision) | ## TradePositionUpdated ```solidity theme={null} event TradePositionUpdated(address user, uint32 index, uint120 collateralAmount, uint24 leverage, uint64 openPrice, uint64 newTp, uint64 newSl, bool isPartialIncrease, bool isPnlPositive) ``` *Emitted when an open trade collateral is updated* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------------------------------------- | | user | address | trade user | | index | uint32 | trade index | | collateralAmount | uint120 | new collateral value (collateral precision) | | leverage | uint24 | new leverage value if present | | openPrice | uint64 | new open price value if present | | newTp | uint64 | | | newSl | uint64 | | | isPartialIncrease | bool | true if trade liquidation params were refreshed | | isPnlPositive | bool | true if trade pnl is positive (only relevant when closing) | ## OpenOrderDetailsUpdated ```solidity theme={null} event OpenOrderDetailsUpdated(address user, uint32 index, uint64 openPrice, uint64 tp, uint64 sl, uint16 maxSlippageP) ``` *Emitted when an existing trade/limit order/stop order is updated* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------------ | | user | address | trade user | | index | uint32 | trade index | | openPrice | uint64 | new open price value (1e10) | | tp | uint64 | new take profit value (1e10) | | sl | uint64 | new stop loss value (1e10) | | maxSlippageP | uint16 | new max slippage % value (1e3) | ## TradeTpUpdated ```solidity theme={null} event TradeTpUpdated(address user, uint32 index, uint64 newTp) ``` *Emitted when the take profit of an open trade is updated* ### Parameters | Name | Type | Description | | ----- | ------- | ------------------------------------ | | user | address | trade user | | index | uint32 | trade index | | newTp | uint64 | the new take profit (1e10 precision) | ## TradeSlUpdated ```solidity theme={null} event TradeSlUpdated(address user, uint32 index, uint64 newSl) ``` *Emitted when the stop loss of an open trade is updated* ### Parameters | Name | Type | Description | | ----- | ------- | --------------------------- | | user | address | trade user | | index | uint32 | trade index | | newSl | uint64 | the new sl (1e10 precision) | ## TradeClosed ```solidity theme={null} event TradeClosed(address user, uint32 index, bool isPnlPositive) ``` *Emitted when an open trade is closed* ### Parameters | Name | Type | Description | | ------------- | ------- | ----------------------------- | | user | address | trade user | | index | uint32 | trade index | | isPnlPositive | bool | true if trade pnl is positive | ## PendingOrderStored ```solidity theme={null} event PendingOrderStored(struct ITradingStorage.PendingOrder pendingOrder) ``` *Emitted when a new pending order is stored* ### Parameters | Name | Type | Description | | ------------ | ----------------------------------- | ------------------------ | | pendingOrder | struct ITradingStorage.PendingOrder | the pending order stored | ## PendingOrderClosed ```solidity theme={null} event PendingOrderClosed(struct ITradingStorage.Id orderId) ``` *Emitted when a pending order is closed* ### Parameters | Name | Type | Description | | ------- | ------------------------- | ---------------------------------- | | orderId | struct ITradingStorage.Id | the id of the pending order closed | ## MissingCollaterals ```solidity theme={null} error MissingCollaterals() ``` ## CollateralAlreadyActive ```solidity theme={null} error CollateralAlreadyActive() ``` ## CollateralAlreadyDisabled ```solidity theme={null} error CollateralAlreadyDisabled() ``` ## TradePositionSizeZero ```solidity theme={null} error TradePositionSizeZero() ``` ## TradeOpenPriceZero ```solidity theme={null} error TradeOpenPriceZero() ``` ## TradePairNotListed ```solidity theme={null} error TradePairNotListed() ``` ## TradeTpInvalid ```solidity theme={null} error TradeTpInvalid() ``` ## TradeSlInvalid ```solidity theme={null} error TradeSlInvalid() ``` ## MaxSlippageZero ```solidity theme={null} error MaxSlippageZero() ``` ## TradeInfoCollateralPriceUsdZero ```solidity theme={null} error TradeInfoCollateralPriceUsdZero() ``` # ITriggerRewardsUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/itriggerrewardsutils *Interface for GNSTriggerRewards facet (inherits types and also contains functions, events, and custom errors)* ## initializeTriggerRewards ```solidity theme={null} function initializeTriggerRewards(uint16 _timeoutBlocks) external ``` *Initializes parameters for trigger rewards facet* ### Parameters | Name | Type | Description | | --------------- | ------ | -------------------------------------- | | \_timeoutBlocks | uint16 | blocks after which a trigger times out | ## updateTriggerTimeoutBlocks ```solidity theme={null} function updateTriggerTimeoutBlocks(uint16 _timeoutBlocks) external ``` *Updates the blocks after which a trigger times out* ### Parameters | Name | Type | Description | | --------------- | ------ | -------------------------------------- | | \_timeoutBlocks | uint16 | blocks after which a trigger times out | ## distributeTriggerReward ```solidity theme={null} function distributeTriggerReward(uint256 _rewardGns) external ``` *Distributes GNS rewards to oracles for a specific trigger* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------------------------------------ | | \_rewardGns | uint256 | total GNS reward to be distributed among oracles | ## claimPendingTriggerRewards ```solidity theme={null} function claimPendingTriggerRewards(address _oracle) external ``` *Claims pending GNS trigger rewards for the caller* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_oracle | address | address of the oracle | ## getTriggerTimeoutBlocks ```solidity theme={null} function getTriggerTimeoutBlocks() external view returns (uint16) ``` *Returns current triggerTimeoutBlocks value* ## hasActiveOrder ```solidity theme={null} function hasActiveOrder(uint256 _orderBlock) external view returns (bool) ``` *Checks if an order is active (exists and has not timed out)* ### Parameters | Name | Type | Description | | ------------ | ------- | ------------------------- | | \_orderBlock | uint256 | block number of the order | ## getTriggerPendingRewardsGns ```solidity theme={null} function getTriggerPendingRewardsGns(address _oracle) external view returns (uint256) ``` *Returns the pending GNS trigger rewards for an oracle* ### Parameters | Name | Type | Description | | -------- | ------- | --------------------- | | \_oracle | address | address of the oracle | ## TriggerTimeoutBlocksUpdated ```solidity theme={null} event TriggerTimeoutBlocksUpdated(uint16 timeoutBlocks) ``` *Emitted when timeoutBlocks is updated* ### Parameters | Name | Type | Description | | ------------- | ------ | -------------------------------------- | | timeoutBlocks | uint16 | blocks after which a trigger times out | ## TriggerRewarded ```solidity theme={null} event TriggerRewarded(uint256 rewardsPerOracleGns, uint256 oraclesCount) ``` *Emitted when trigger rewards are distributed for a specific order* ### Parameters | Name | Type | Description | | ------------------- | ------- | ------------------------------------ | | rewardsPerOracleGns | uint256 | reward in GNS distributed per oracle | | oraclesCount | uint256 | number of oracles rewarded | ## TriggerRewardsClaimed ```solidity theme={null} event TriggerRewardsClaimed(address oracle, uint256 rewardsGns) ``` *Emitted when pending GNS trigger rewards are claimed by an oracle* ### Parameters | Name | Type | Description | | ---------- | ------- | --------------------- | | oracle | address | address of the oracle | | rewardsGns | uint256 | GNS rewards claimed | ## TimeoutBlocksZero ```solidity theme={null} error TimeoutBlocksZero() ``` ## NoPendingTriggerRewards ```solidity theme={null} error NoPendingTriggerRewards() ``` # IUpdateLeverageUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/iupdateleverageutils *Interface for leverage updates* ## LeverageUpdateInitiated ```solidity theme={null} event LeverageUpdateInitiated(struct ITradingStorage.Id orderId, address trader, uint256 pairIndex, uint256 index, bool isIncrease, uint256 newLeverage) ``` ### Parameters | Name | Type | Description | | ----------- | ------------------------- | -------------------------------------------- | | orderId | struct ITradingStorage.Id | request order id | | trader | address | address of trader | | pairIndex | uint256 | index of pair | | index | uint256 | index of trade | | isIncrease | bool | true if increase leverage, false if decrease | | newLeverage | uint256 | new leverage value (1e3) | ## LeverageUpdateExecuted ```solidity theme={null} event LeverageUpdateExecuted(struct ITradingStorage.Id orderId, bool isIncrease, enum ITradingCallbacks.CancelReason cancelReason, uint8 collateralIndex, address trader, uint256 pairIndex, uint256 index, uint256 oraclePrice, uint256 collateralDelta, struct IUpdateLeverage.UpdateLeverageValues values) ``` ### Parameters | Name | Type | Description | | --------------- | ------------------------------------------- | --------------------------------------------------------------------------- | | orderId | struct ITradingStorage.Id | request order id | | isIncrease | bool | true if leverage increased, false if decreased | | cancelReason | enum ITradingCallbacks.CancelReason | cancel reason (executed if none) | | collateralIndex | uint8 | collateral index | | trader | address | address of trader | | pairIndex | uint256 | index of pair | | index | uint256 | index of trade | | oraclePrice | uint256 | current oracle price (1e10) | | collateralDelta | uint256 | collateral delta (collateral precision) | | values | struct IUpdateLeverage.UpdateLeverageValues | useful values (new collateral, new leverage, liq price, gov fee collateral) | # IUpdatePositionSizeUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/iupdatepositionsizeutils *Interface for position size updates* ## PositionSizeUpdateInitiated ```solidity theme={null} event PositionSizeUpdateInitiated(struct ITradingStorage.Id orderId, address trader, uint256 pairIndex, uint256 index, bool isIncrease, uint256 collateralDelta, uint256 leverageDelta) ``` ### Parameters | Name | Type | Description | | --------------- | ------------------------- | ------------------------------------------------- | | orderId | struct ITradingStorage.Id | request order id | | trader | address | address of the trader | | pairIndex | uint256 | index of the pair | | index | uint256 | index of user trades | | isIncrease | bool | true if increase position size, false if decrease | | collateralDelta | uint256 | collateral delta (collateral precision) | | leverageDelta | uint256 | leverage delta (1e3) | ## PositionSizeIncreaseExecuted ```solidity theme={null} event PositionSizeIncreaseExecuted(struct ITradingStorage.Id orderId, enum ITradingCallbacks.CancelReason cancelReason, uint8 collateralIndex, address trader, uint256 pairIndex, uint256 index, bool long, uint256 oraclePrice, uint256 collateralPriceUsd, uint256 collateralDelta, uint256 leverageDelta, struct IUpdatePositionSize.IncreasePositionSizeValues values) ``` ### Parameters | Name | Type | Description | | ------------------ | ----------------------------------------------------- | --------------------------------------------------------------------- | | orderId | struct ITradingStorage.Id | request order id | | cancelReason | enum ITradingCallbacks.CancelReason | cancel reason if canceled or none if executed | | collateralIndex | uint8 | collateral index | | trader | address | address of trader | | pairIndex | uint256 | index of pair | | index | uint256 | index of trade | | long | bool | true for long, false for short | | oraclePrice | uint256 | oracle price (1e10) | | collateralPriceUsd | uint256 | collateral price in USD (1e8) | | collateralDelta | uint256 | collateral delta (collateral precision) | | leverageDelta | uint256 | leverage delta (1e3) | | values | struct IUpdatePositionSize.IncreasePositionSizeValues | important values (new open price, new leverage, new collateral, etc.) | ## PositionSizeDecreaseExecuted ```solidity theme={null} event PositionSizeDecreaseExecuted(struct ITradingStorage.Id orderId, enum ITradingCallbacks.CancelReason cancelReason, uint8 collateralIndex, address trader, uint256 pairIndex, uint256 index, bool long, uint256 oraclePrice, uint256 collateralPriceUsd, uint256 collateralDelta, uint256 leverageDelta, struct IUpdatePositionSize.DecreasePositionSizeValues values) ``` ### Parameters | Name | Type | Description | | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------- | | orderId | struct ITradingStorage.Id | request order id | | cancelReason | enum ITradingCallbacks.CancelReason | cancel reason if canceled or none if executed | | collateralIndex | uint8 | collateral index | | trader | address | address of trader | | pairIndex | uint256 | index of pair | | index | uint256 | index of trade | | long | bool | true for long, false for short | | oraclePrice | uint256 | oracle price (1e10) | | collateralPriceUsd | uint256 | collateral price in USD (1e8) | | collateralDelta | uint256 | collateral delta (collateral precision) | | leverageDelta | uint256 | leverage delta (1e3) | | values | struct IUpdatePositionSize.DecreasePositionSizeValues | important values (pnl, new leverage, new collateral, etc.) | ## InvalidIncreasePositionSizeInput ```solidity theme={null} error InvalidIncreasePositionSizeInput() ``` ## InvalidDecreasePositionSizeInput ```solidity theme={null} error InvalidDecreasePositionSizeInput() ``` ## NewPositionSizeSmaller ```solidity theme={null} error NewPositionSizeSmaller() ``` # IAddressStore Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/iaddressstore *Contains the types for the GNSAddressStore facet* ## Role ```solidity theme={null} enum Role { ROLES_MANAGER, GOV, MANAGER } ``` ## Addresses ```solidity theme={null} struct Addresses { address gns; address gnsStaking; } ``` ## AddressStore ```solidity theme={null} struct AddressStore { uint256 __deprecated; mapping(address => mapping(enum IAddressStore.Role => bool)) accessControl; struct IAddressStore.Addresses globalAddresses; uint256[8] __gap1; uint256[38] __gap2; } ``` # IBorrowingFees Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/iborrowingfees *Contains the types for the GNSBorrowingFees facet* ## BorrowingFeesStorage ```solidity theme={null} struct BorrowingFeesStorage { mapping(uint8 => mapping(uint16 => struct IBorrowingFees.BorrowingData)) pairs; mapping(uint8 => mapping(uint16 => struct IBorrowingFees.BorrowingPairGroup[])) pairGroups; mapping(uint8 => mapping(uint16 => struct IBorrowingFees.OpenInterest)) pairOis; mapping(uint8 => mapping(uint16 => struct IBorrowingFees.BorrowingData)) groups; mapping(uint8 => mapping(uint16 => struct IBorrowingFees.OpenInterest)) groupOis; mapping(uint8 => mapping(address => mapping(uint32 => struct IBorrowingFees.BorrowingInitialAccFees))) initialAccFees; uint256[44] __gap; } ``` ## BorrowingData ```solidity theme={null} struct BorrowingData { uint32 feePerBlock; uint64 accFeeLong; uint64 accFeeShort; uint48 accLastUpdatedBlock; uint48 feeExponent; } ``` ## BorrowingPairGroup ```solidity theme={null} struct BorrowingPairGroup { uint16 groupIndex; uint48 block; uint64 initialAccFeeLong; uint64 initialAccFeeShort; uint64 prevGroupAccFeeLong; uint64 prevGroupAccFeeShort; uint64 pairAccFeeLong; uint64 pairAccFeeShort; uint64 __placeholder; } ``` ## OpenInterest ```solidity theme={null} struct OpenInterest { uint72 long; uint72 short; uint72 max; uint40 __placeholder; } ``` ## BorrowingInitialAccFees ```solidity theme={null} struct BorrowingInitialAccFees { uint64 accPairFee; uint64 accGroupFee; uint48 block; uint80 __placeholder; } ``` ## BorrowingPairParams ```solidity theme={null} struct BorrowingPairParams { uint16 groupIndex; uint32 feePerBlock; uint48 feeExponent; uint72 maxOi; } ``` ## BorrowingGroupParams ```solidity theme={null} struct BorrowingGroupParams { uint32 feePerBlock; uint72 maxOi; uint48 feeExponent; } ``` ## BorrowingFeeInput ```solidity theme={null} struct BorrowingFeeInput { uint8 collateralIndex; address trader; uint16 pairIndex; uint32 index; bool long; uint256 collateral; uint256 leverage; } ``` ## LiqPriceInput ```solidity theme={null} struct LiqPriceInput { uint8 collateralIndex; address trader; uint16 pairIndex; uint32 index; uint64 openPrice; bool long; uint256 collateral; uint256 leverage; bool useBorrowingFees; struct IPairsStorage.GroupLiquidationParams liquidationParams; } ``` ## PendingBorrowingAccFeesInput ```solidity theme={null} struct PendingBorrowingAccFeesInput { uint64 accFeeLong; uint64 accFeeShort; uint256 oiLong; uint256 oiShort; uint32 feePerBlock; uint256 currentBlock; uint256 accLastUpdatedBlock; uint72 maxOi; uint48 feeExponent; uint128 collateralPrecision; } ``` # IDiamondStorage Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/idiamondstorage *Based on EIP-2535: Diamonds ([https://eips.ethereum.org/EIPS/eip-2535](https://eips.ethereum.org/EIPS/eip-2535)) Follows diamond-3 implementation ([https://github.com/mudgen/diamond-3-hardhat/](https://github.com/mudgen/diamond-3-hardhat/)) Contains the types used in the diamond management contracts.* ## DiamondStorage ```solidity theme={null} struct DiamondStorage { mapping(bytes4 => struct IDiamondStorage.FacetAddressAndPosition) selectorToFacetAndPosition; mapping(address => struct IDiamondStorage.FacetFunctionSelectors) facetFunctionSelectors; address[] facetAddresses; address[47] __gap; } ``` ## FacetAddressAndPosition ```solidity theme={null} struct FacetAddressAndPosition { address facetAddress; uint96 functionSelectorPosition; } ``` ## FacetFunctionSelectors ```solidity theme={null} struct FacetFunctionSelectors { bytes4[] functionSelectors; uint256 facetAddressPosition; } ``` ## FacetCutAction ```solidity theme={null} enum FacetCutAction { ADD, REPLACE, REMOVE, NOP } ``` ## FacetCut ```solidity theme={null} struct FacetCut { address facetAddress; enum IDiamondStorage.FacetCutAction action; bytes4[] functionSelectors; } ``` # IFeeTiers Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/ifeetiers *Contains the types for the GNSFeeTiers facet* ## FeeTiersStorage ```solidity theme={null} struct FeeTiersStorage { struct IFeeTiers.FeeTier[8] feeTiers; mapping(uint256 => uint256) groupVolumeMultipliers; mapping(address => struct IFeeTiers.TraderInfo) traderInfos; mapping(address => mapping(uint32 => struct IFeeTiers.TraderDailyInfo)) traderDailyInfos; mapping(address => struct IFeeTiers.TraderEnrollment) traderEnrollments; mapping(address => uint224) unclaimedPoints; uint256[37] __gap; } ``` ## TraderEnrollmentStatus ```solidity theme={null} enum TraderEnrollmentStatus { ENROLLED, EXCLUDED } ``` ## CreditType ```solidity theme={null} enum CreditType { IMMEDIATE, CLAIMABLE } ``` ## FeeTier ```solidity theme={null} struct FeeTier { uint32 feeMultiplier; uint32 pointsThreshold; } ``` ## TraderInfo ```solidity theme={null} struct TraderInfo { uint32 lastDayUpdated; uint224 trailingPoints; } ``` ## TraderDailyInfo ```solidity theme={null} struct TraderDailyInfo { uint32 feeMultiplierCache; uint224 points; } ``` ## TraderEnrollment ```solidity theme={null} struct TraderEnrollment { enum IFeeTiers.TraderEnrollmentStatus status; uint248 __placeholder; } ``` # IOtc Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/iotc *Contains the types for the GNSPairsStorage facet* ## OtcStorage ```solidity theme={null} struct OtcStorage { mapping(uint8 => uint256) collateralBalances; struct IOtc.OtcConfig otcConfig; uint256[47] __gap; } ``` ## OtcConfig ```solidity theme={null} struct OtcConfig { address gnsTreasury; uint64 treasuryShareP; uint64 stakingShareP; uint64 burnShareP; uint64 premiumP; } ``` # IPairsStorage Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/ipairsstorage *Contains the types for the GNSPairsStorage facet* ## PairsStorage ```solidity theme={null} struct PairsStorage { mapping(uint256 => struct IPairsStorage.Pair) pairs; mapping(uint256 => struct IPairsStorage.Group) groups; mapping(uint256 => struct IPairsStorage.Fee) fees; mapping(string => mapping(string => bool)) isPairListed; mapping(uint256 => uint256) pairCustomMaxLeverage; uint256 currentOrderId; uint256 pairsCount; uint256 groupsCount; uint256 feesCount; mapping(uint256 => struct IPairsStorage.GroupLiquidationParams) groupLiquidationParams; mapping(uint256 => struct IPairsStorage.FeeGroup) feeGroups; struct IPairsStorage.GlobalTradeFeeParams globalTradeFeeParams; uint256[38] __gap; } ``` ## Pair ```solidity theme={null} struct Pair { string from; string to; struct IPairsStorage.Feed feed; uint256 spreadP; uint256 groupIndex; uint256 feeIndex; } ``` ## Group ```solidity theme={null} struct Group { string name; bytes32 job; uint256 minLeverage; uint256 maxLeverage; } ``` ## GlobalTradeFeeParams ```solidity theme={null} struct GlobalTradeFeeParams { uint24 referralFeeP; uint24 govFeeP; uint24 triggerOrderFeeP; uint24 gnsOtcFeeP; uint24 gTokenFeeP; uint136 __placeholder; } ``` ## FeeGroup ```solidity theme={null} struct FeeGroup { uint40 totalPositionSizeFeeP; uint40 totalLiqCollateralFeeP; uint40 oraclePositionSizeFeeP; uint32 minPositionSizeUsd; uint104 __placeholder; } ``` ## TradeFees ```solidity theme={null} struct TradeFees { uint256 totalFeeCollateral; uint256 referralFeeCollateral; uint256 govFeeCollateral; uint256 triggerOrderFeeCollateral; uint256 gnsOtcFeeCollateral; uint256 gTokenFeeCollateral; } ``` ## GroupLiquidationParams ```solidity theme={null} struct GroupLiquidationParams { uint40 maxLiqSpreadP; uint40 startLiqThresholdP; uint40 endLiqThresholdP; uint24 startLeverage; uint24 endLeverage; } ``` ## FeedCalculation ```solidity theme={null} enum FeedCalculation { DEFAULT, INVERT, COMBINE } ``` ## Feed @custom:deprecated ```solidity theme={null} struct Feed { address feed1; address feed2; enum IPairsStorage.FeedCalculation feedCalculation; uint256 maxDeviationP; } ``` ## Fee @custom:deprecated ```solidity theme={null} struct Fee { string name; uint256 openFeeP; uint256 closeFeeP; uint256 oracleFeeP; uint256 triggerOrderFeeP; uint256 minPositionSizeUsd; } ``` # IPriceAggregator Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/ipriceaggregator *Contains the types for the GNSPriceAggregator facet* ## PriceAggregatorStorage ```solidity theme={null} struct PriceAggregatorStorage { contract IChainlinkFeed linkUsdPriceFeed; uint24 twapInterval; uint8 minAnswers; bytes32[2] jobIds; address[] oracles; mapping(uint8 => struct IPriceAggregator.LiquidityPoolInfo) collateralGnsLiquidityPools; mapping(uint8 => contract IChainlinkFeed) collateralUsdPriceFeed; mapping(bytes32 => struct IPriceAggregator.Order) orders; mapping(address => mapping(uint32 => struct IPriceAggregator.OrderAnswer[])) orderAnswers; contract LinkTokenInterface linkErc677; uint96 __placeholder; uint256 requestCount; mapping(bytes32 => address) pendingRequests; uint256[39] __gap; } ``` ## LiquidityPoolInfo ```solidity theme={null} struct LiquidityPoolInfo { contract ILiquidityPool pool; bool isGnsToken0InLp; enum IPriceAggregator.PoolType poolType; uint80 __placeholder; } ``` ## Order ```solidity theme={null} struct Order { address user; uint32 index; enum ITradingStorage.PendingOrderType orderType; uint16 pairIndex; bool isLookback; uint32 __placeholder; } ``` ## OrderAnswer ```solidity theme={null} struct OrderAnswer { uint64 open; uint64 high; uint64 low; uint64 ts; } ``` ## LiquidityPoolInput ```solidity theme={null} struct LiquidityPoolInput { contract ILiquidityPool pool; enum IPriceAggregator.PoolType poolType; } ``` ## PoolType ```solidity theme={null} enum PoolType { UNISWAP_V3, ALGEBRA_v1_9 } ``` # IPriceImpact Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/ipriceimpact *Contains the types for the GNSPriceImpact facet* ## PriceImpactStorage ```solidity theme={null} struct PriceImpactStorage { struct IPriceImpact.OiWindowsSettings oiWindowsSettings; mapping(uint48 => mapping(uint256 => mapping(uint256 => struct IPriceImpact.PairOi))) windows; mapping(uint256 => struct IPriceImpact.PairDepth) pairDepths; mapping(address => mapping(uint32 => struct IPriceImpact.TradePriceImpactInfo)) tradePriceImpactInfos; mapping(uint256 => struct IPriceImpact.PairFactors) pairFactors; uint40 negPnlCumulVolMultiplier; uint216 __placeholder; mapping(address => bool) protectionCloseFactorWhitelist; uint256[43] __gap; } ``` ## OiWindowsSettings ```solidity theme={null} struct OiWindowsSettings { uint48 startTs; uint48 windowsDuration; uint48 windowsCount; } ``` ## PairOi ```solidity theme={null} struct PairOi { uint128 oiLongUsd; uint128 oiShortUsd; } ``` ## OiWindowUpdate ```solidity theme={null} struct OiWindowUpdate { address trader; uint32 index; uint48 windowsDuration; uint256 pairIndex; uint256 windowId; bool long; bool open; bool isPnlPositive; uint128 openInterestUsd; } ``` ## PairDepth ```solidity theme={null} struct PairDepth { uint128 onePercentDepthAboveUsd; uint128 onePercentDepthBelowUsd; } ``` ## PairFactors ```solidity theme={null} struct PairFactors { uint40 protectionCloseFactor; uint32 protectionCloseFactorBlocks; uint40 cumulativeFactor; bool exemptOnOpen; bool exemptAfterProtectionCloseFactor; uint128 __placeholder; } ``` ## TradePriceImpactInfo ```solidity theme={null} struct TradePriceImpactInfo { uint128 lastWindowOiUsd; uint128 __placeholder; } ``` # IReferrals Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/ireferrals *Contains the types for the GNSReferrals facet* ## ReferralsStorage ```solidity theme={null} struct ReferralsStorage { mapping(address => struct IReferrals.AllyDetails) allyDetails; mapping(address => struct IReferrals.ReferrerDetails) referrerDetails; mapping(address => address) referrerByTrader; uint256 allyFeeP; uint256 startReferrerFeeP; uint256 openFeeP; uint256 targetVolumeUsd; uint256[43] __gap; } ``` ## AllyDetails ```solidity theme={null} struct AllyDetails { address[] referrersReferred; uint256 volumeReferredUsd; uint256 pendingRewardsGns; uint256 totalRewardsGns; uint256 totalRewardsValueUsd; bool active; } ``` ## ReferrerDetails ```solidity theme={null} struct ReferrerDetails { address ally; address[] tradersReferred; uint256 volumeReferredUsd; uint256 pendingRewardsGns; uint256 totalRewardsGns; uint256 totalRewardsValueUsd; bool active; } ``` # ITradingCallbacks Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/itradingcallbacks *Contains the types for the GNSTradingCallbacks facet* ## TradingCallbacksStorage ```solidity theme={null} struct TradingCallbacksStorage { uint8 vaultClosingFeeP; uint248 __placeholder; mapping(uint8 => uint256) pendingGovFees; uint256[48] __gap; } ``` ## CancelReason ```solidity theme={null} enum CancelReason { NONE, PAUSED, MARKET_CLOSED, SLIPPAGE, TP_REACHED, SL_REACHED, EXPOSURE_LIMITS, PRICE_IMPACT, MAX_LEVERAGE, NO_TRADE, WRONG_TRADE, NOT_HIT, LIQ_REACHED } ``` ## AggregatorAnswer ```solidity theme={null} struct AggregatorAnswer { struct ITradingStorage.Id orderId; uint256 spreadP; uint64 price; uint64 open; uint64 high; uint64 low; } ``` ## Values ```solidity theme={null} struct Values { int256 profitP; uint256 executionPrice; uint256 liqPrice; uint256 amountSentToTrader; uint256 collateralPriceUsd; bool exactExecution; uint256 collateralLeftInStorage; uint256 oraclePrice; uint32 limitIndex; uint256 priceImpactP; } ``` # ITradingInteractions Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/itradinginteractions *Contains the types for the GNSTradingInteractions facet* ## TradingInteractionsStorage ```solidity theme={null} struct TradingInteractionsStorage { address senderOverride; uint16 marketOrdersTimeoutBlocks; uint80 __placeholder; mapping(address => address) delegations; mapping(address => bool) byPassTriggerLink; uint256[47] __gap; } ``` # ITradingStorage Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/itradingstorage *Contains the types for the GNSTradingStorage facet* ## TradingStorage ```solidity theme={null} struct TradingStorage { enum ITradingStorage.TradingActivated tradingActivated; uint8 lastCollateralIndex; uint240 __placeholder; mapping(uint8 => struct ITradingStorage.Collateral) collaterals; mapping(uint8 => address) gTokens; mapping(address => uint8) collateralIndex; mapping(address => mapping(uint32 => struct ITradingStorage.Trade)) trades; mapping(address => mapping(uint32 => struct ITradingStorage.TradeInfo)) tradeInfos; mapping(address => mapping(uint32 => mapping(enum ITradingStorage.PendingOrderType => uint256))) tradePendingOrderBlock; mapping(address => mapping(uint32 => struct ITradingStorage.PendingOrder)) pendingOrders; mapping(address => mapping(enum ITradingStorage.CounterType => struct ITradingStorage.Counter)) userCounters; address[] traders; mapping(address => bool) traderStored; mapping(address => mapping(uint32 => struct IPairsStorage.GroupLiquidationParams)) tradeLiquidationParams; uint256[38] __gap; } ``` ## PendingOrderType ```solidity theme={null} enum PendingOrderType { MARKET_OPEN, MARKET_CLOSE, LIMIT_OPEN, STOP_OPEN, TP_CLOSE, SL_CLOSE, LIQ_CLOSE, UPDATE_LEVERAGE, MARKET_PARTIAL_OPEN, MARKET_PARTIAL_CLOSE } ``` ## CounterType ```solidity theme={null} enum CounterType { TRADE, PENDING_ORDER } ``` ## TradeType ```solidity theme={null} enum TradeType { TRADE, LIMIT, STOP } ``` ## TradingActivated ```solidity theme={null} enum TradingActivated { ACTIVATED, CLOSE_ONLY, PAUSED } ``` ## ContractsVersion ```solidity theme={null} enum ContractsVersion { BEFORE_V9_2, V9_2 } ``` ## Collateral ```solidity theme={null} struct Collateral { address collateral; bool isActive; uint88 __placeholder; uint128 precision; uint128 precisionDelta; } ``` ## Id ```solidity theme={null} struct Id { address user; uint32 index; } ``` ## Trade ```solidity theme={null} struct Trade { address user; // 160 bits uint32 index; // max: 4,294,967,295 uint16 pairIndex; // max: 65,535 uint24 leverage; // 1e3; max: 16,777.215 bool long; // 8 bits bool isOpen; // 8 bits uint8 collateralIndex; // max: 255 TradeType tradeType; // 8 bits uint120 collateralAmount; // collateral precision; max: 3.402e+38 uint64 openPrice; // 1e10; max: 1.8e19 uint64 tp; // 1e10; max: 1.8e19 uint64 sl; // 1e10; max: 1.8e19 bool isCounterTrade; uint160 positionSizeToken; // 1e18, assuming 1e-9 collateral price, 1e-9 pair price => max value is 1.46 trillion USD (1e12) uint24 __placeholder; } ``` ## TradeInfo ```solidity theme={null} struct TradeInfo { uint32 createdBlock; uint32 tpLastUpdatedBlock; uint32 slLastUpdatedBlock; uint16 maxSlippageP; uint48 lastOiUpdateTs; uint48 collateralPriceUsd; enum ITradingStorage.ContractsVersion contractsVersion; uint32 lastPosIncreaseBlock; uint8 __placeholder; } ``` ## PendingOrder ```solidity theme={null} struct PendingOrder { struct ITradingStorage.Trade trade; address user; uint32 index; bool isOpen; enum ITradingStorage.PendingOrderType orderType; uint32 createdBlock; uint16 maxSlippageP; } ``` ## Counter ```solidity theme={null} struct Counter { uint32 currentIndex; uint32 openCount; uint192 __placeholder; } ``` # ITriggerRewards Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/itriggerrewards *Contains the types for the GNSTriggerRewards facet* ## TriggerRewardsStorage ```solidity theme={null} struct TriggerRewardsStorage { uint16 triggerTimeoutBlocks; uint240 __placeholder; mapping(address => uint256) pendingRewardsGns; uint256[48] __gap; } ``` # ITypes Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/itypes *Contains the types of all diamond facets* # IUpdateLeverage Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/iupdateleverage *Interface for leverage updates types* ## UpdateLeverageInput *Update leverage input values* ```solidity theme={null} struct UpdateLeverageInput { address user; uint32 index; uint24 newLeverage; } ``` ## UpdateLeverageValues *Useful values for increase leverage callback* ```solidity theme={null} struct UpdateLeverageValues { uint256 newLeverage; uint256 newCollateralAmount; uint256 liqPrice; uint256 govFeeCollateral; } ``` # IUpdatePositionSize Source: https://docs.gains.trade/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize *Interface for position size updates types* ## DecreasePositionSizeInput *Request decrease position input values* ```solidity theme={null} struct DecreasePositionSizeInput { address user; uint32 index; uint120 collateralDelta; uint24 leverageDelta; uint64 expectedPrice; } ``` ## IncreasePositionSizeInput *Request increase position input values* ```solidity theme={null} struct IncreasePositionSizeInput { address user; uint32 index; uint120 collateralDelta; uint24 leverageDelta; uint64 expectedPrice; uint16 maxSlippageP; } ``` ## DecreasePositionSizeValues *Useful values for decrease position size callback* ```solidity theme={null} struct DecreasePositionSizeValues { uint256 positionSizeCollateralDelta; uint256 existingPositionSizeCollateral; uint256 existingLiqPrice; uint256 priceAfterImpact; int256 existingPnlCollateral; uint256 borrowingFeeCollateral; uint256 closingFeeCollateral; int256 availableCollateralInDiamond; int256 collateralSentToTrader; uint120 newCollateralAmount; uint24 newLeverage; } ``` ## IncreasePositionSizeValues *Useful values for increase position size callback* ```solidity theme={null} struct IncreasePositionSizeValues { uint256 positionSizeCollateralDelta; uint256 existingPositionSizeCollateral; uint256 newPositionSizeCollateral; uint256 newCollateralAmount; uint256 newLeverage; uint256 priceAfterImpact; int256 existingPnlCollateral; uint256 newOpenPrice; uint256 borrowingFeeCollateral; uint256 openingFeesCollateral; uint256 existingLiqPrice; uint256 newLiqPrice; } ``` # AddressStoreUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/addressstoreutils *GNSAddressStore facet internal library* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching addresses* ## getAddresses ```solidity theme={null} function getAddresses() internal pure returns (struct IAddressStore.Addresses s) ``` *Returns storage pointer for Addresses struct in global diamond contract, at defined slot* # ArrayGetters Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/arraygetters *External library for array getters to save bytecode size in facet libraries* ## getTraders ```solidity theme={null} function getTraders(uint32 _offset, uint32 _limit) public view returns (address[]) ``` *Check ITradingStorageUtils interface for documentation* ## getTrades ```solidity theme={null} function getTrades(address _trader) public view returns (struct ITradingStorage.Trade[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllTradesForTraders ```solidity theme={null} function getAllTradesForTraders(address[] _traders, uint256 _offset, uint256 _limit) public view returns (struct ITradingStorage.Trade[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllTrades ```solidity theme={null} function getAllTrades(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.Trade[]) ``` *Check ITradingStorageUtils interface for documentation* ## getTradeInfos ```solidity theme={null} function getTradeInfos(address _trader) public view returns (struct ITradingStorage.TradeInfo[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllTradeInfosForTraders ```solidity theme={null} function getAllTradeInfosForTraders(address[] _traders, uint256 _offset, uint256 _limit) public view returns (struct ITradingStorage.TradeInfo[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllTradeInfos ```solidity theme={null} function getAllTradeInfos(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.TradeInfo[]) ``` *Check ITradingStorageUtils interface for documentation* ## getPendingOrders ```solidity theme={null} function getPendingOrders(address _trader) public view returns (struct ITradingStorage.PendingOrder[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllPendingOrdersForTraders ```solidity theme={null} function getAllPendingOrdersForTraders(address[] _traders, uint256 _offset, uint256 _limit) public view returns (struct ITradingStorage.PendingOrder[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllPendingOrders ```solidity theme={null} function getAllPendingOrders(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.PendingOrder[]) ``` *Check ITradingStorageUtils interface for documentation* ## getTradesLiquidationParams ```solidity theme={null} function getTradesLiquidationParams(address _trader) public view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllTradesLiquidationParamsForTraders ```solidity theme={null} function getAllTradesLiquidationParamsForTraders(address[] _traders, uint256 _offset, uint256 _limit) public view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Check ITradingStorageUtils interface for documentation* ## getAllTradesLiquidationParams ```solidity theme={null} function getAllTradesLiquidationParams(uint256 _offset, uint256 _limit) external view returns (struct IPairsStorage.GroupLiquidationParams[]) ``` *Check ITradingStorageUtils interface for documentation* ## getCountersForTraders ```solidity theme={null} function getCountersForTraders(address[] _traders, enum ITradingStorage.CounterType _counterType) external view returns (struct ITradingStorage.Counter[]) ``` *Check ITradingStorageUtils interface for documentation* # BorrowingFeesUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/borrowingfeesutils *GNSBorrowingFees facet internal library* ## setBorrowingPairParams ```solidity theme={null} function setBorrowingPairParams(uint8 _collateralIndex, uint16 _pairIndex, struct IBorrowingFees.BorrowingPairParams _value) internal ``` *Check IBorrowingFeesUtils interface for documentation* ## setBorrowingPairParamsArray ```solidity theme={null} function setBorrowingPairParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingPairParams[] _values) internal ``` *Check IBorrowingFeesUtils interface for documentation* ## setBorrowingGroupParams ```solidity theme={null} function setBorrowingGroupParams(uint8 _collateralIndex, uint16 _groupIndex, struct IBorrowingFees.BorrowingGroupParams _value) internal ``` *Check IBorrowingFeesUtils interface for documentation* ## setBorrowingGroupParamsArray ```solidity theme={null} function setBorrowingGroupParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingGroupParams[] _values) internal ``` *Check IBorrowingFeesUtils interface for documentation* ## handleTradeBorrowingCallback ```solidity theme={null} function handleTradeBorrowingCallback(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, uint256 _positionSizeCollateral, bool _open, bool _long) internal ``` *Check IBorrowingFeesUtils interface for documentation* ## resetTradeBorrowingFees ```solidity theme={null} function resetTradeBorrowingFees(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, bool _long) internal ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingPairPendingAccFees ```solidity theme={null} function getBorrowingPairPendingAccFees(uint8 _collateralIndex, uint16 _pairIndex, uint256 _currentBlock) internal view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 pairAccFeeDelta) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingGroupPendingAccFees ```solidity theme={null} function getBorrowingGroupPendingAccFees(uint8 _collateralIndex, uint16 _groupIndex, uint256 _currentBlock) internal view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 groupAccFeeDelta) ``` *Check IBorrowingFeesUtils interface for documentation* ## getTradeBorrowingFee ```solidity theme={null} function getTradeBorrowingFee(struct IBorrowingFees.BorrowingFeeInput _input) internal view returns (uint256 feeAmountCollateral) ``` *Check IBorrowingFeesUtils interface for documentation* ## getTradeLiquidationPrice ```solidity theme={null} function getTradeLiquidationPrice(struct IBorrowingFees.LiqPriceInput _input) internal view returns (uint256) ``` *Check IBorrowingFeesUtils interface for documentation* ## getPairOisCollateral ```solidity theme={null} function getPairOisCollateral(uint8 _collateralIndex, uint16 _pairIndex) internal view returns (uint256 longOiCollateral, uint256 shortOiCollateral) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingPairGroupIndex ```solidity theme={null} function getBorrowingPairGroupIndex(uint8 _collateralIndex, uint16 _pairIndex) internal view returns (uint16 groupIndex) ``` *Check IBorrowingFeesUtils interface for documentation* ## getPairOiCollateral ```solidity theme={null} function getPairOiCollateral(uint8 _collateralIndex, uint16 _pairIndex, bool _long) internal view returns (uint256) ``` *Check IBorrowingFeesUtils interface for documentation* ## withinMaxBorrowingGroupOi ```solidity theme={null} function withinMaxBorrowingGroupOi(uint8 _collateralIndex, uint16 _pairIndex, bool _long, uint256 _positionSizeCollateral) internal view returns (bool) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingGroup ```solidity theme={null} function getBorrowingGroup(uint8 _collateralIndex, uint16 _groupIndex) internal view returns (struct IBorrowingFees.BorrowingData) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingGroupOi ```solidity theme={null} function getBorrowingGroupOi(uint8 _collateralIndex, uint16 _groupIndex) internal view returns (struct IBorrowingFees.OpenInterest) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingPair ```solidity theme={null} function getBorrowingPair(uint8 _collateralIndex, uint16 _pairIndex) internal view returns (struct IBorrowingFees.BorrowingData) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingPairOi ```solidity theme={null} function getBorrowingPairOi(uint8 _collateralIndex, uint16 _pairIndex) internal view returns (struct IBorrowingFees.OpenInterest) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingPairGroups ```solidity theme={null} function getBorrowingPairGroups(uint8 _collateralIndex, uint16 _pairIndex) internal view returns (struct IBorrowingFees.BorrowingPairGroup[]) ``` *Check IBorrowingFeesUtils interface for documentation* ## getAllBorrowingPairs ```solidity theme={null} function getAllBorrowingPairs(uint8 _collateralIndex) internal view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[], struct IBorrowingFees.BorrowingPairGroup[][]) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingGroups ```solidity theme={null} function getBorrowingGroups(uint8 _collateralIndex, uint16[] _indices) internal view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[]) ``` *Check IBorrowingFeesUtils interface for documentation* ## getBorrowingInitialAccFees ```solidity theme={null} function getBorrowingInitialAccFees(uint8 _collateralIndex, address _trader, uint32 _index) internal view returns (struct IBorrowingFees.BorrowingInitialAccFees) ``` *Check IBorrowingFeesUtils interface for documentation* ## getPairMaxOi ```solidity theme={null} function getPairMaxOi(uint8 _collateralIndex, uint16 _pairIndex) internal view returns (uint256) ``` *Check IBorrowingFeesUtils interface for documentation* ## getPairMaxOiCollateral ```solidity theme={null} function getPairMaxOiCollateral(uint8 _collateralIndex, uint16 _pairIndex) internal view returns (uint256) ``` *Check IBorrowingFeesUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IBorrowingFees.BorrowingFeesStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## validCollateralIndex ```solidity theme={null} modifier validCollateralIndex(uint8 _collateralIndex) ``` *Reverts if collateral index is not valid* ## \_getBorrowingPairPendingAccFee ```solidity theme={null} function _getBorrowingPairPendingAccFee(uint8 _collateralIndex, uint16 _pairIndex, uint256 _currentBlock, bool _long) internal view returns (uint64 accFee) ``` *Returns pending acc borrowing fee for a pair on one side only* ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_currentBlock | uint256 | current block number | | \_long | bool | true if long side | ### Return Values | Name | Type | Description | | ------ | ------ | -------------------------- | | accFee | uint64 | new pair acc borrowing fee | ## \_getBorrowingGroupPendingAccFee ```solidity theme={null} function _getBorrowingGroupPendingAccFee(uint8 _collateralIndex, uint16 _groupIndex, uint256 _currentBlock, bool _long) internal view returns (uint64 accFee) ``` *Returns pending acc borrowing fee for a borrowing group on one side only* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_currentBlock | uint256 | current block number | | \_long | bool | true if long side | ### Return Values | Name | Type | Description | | ------ | ------ | --------------------------- | | accFee | uint64 | new group acc borrowing fee | ## \_getBorrowingPendingAccFees ```solidity theme={null} function _getBorrowingPendingAccFees(struct IBorrowingFees.PendingBorrowingAccFeesInput _input) internal pure returns (uint64 newAccFeeLong, uint64 newAccFeeShort, uint64 delta) ``` *Pure function that returns the new acc borrowing fees and delta between two blocks (for pairs and groups)* ### Parameters | Name | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | \_input | [IBorrowingFees.PendingBorrowingAccFeesInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#pendingborrowingaccfeesinput) | input data (last acc fees, OIs, fee per block, current block, etc.) | ### Return Values | Name | Type | Description | | -------------- | ------ | ------------------------------------------------------------ | | newAccFeeLong | uint64 | new acc borrowing fee on long side | | newAccFeeShort | uint64 | new acc borrowing fee on short side | | delta | uint64 | delta with current acc borrowing fee (for side that changed) | ## \_getTradeLiquidationPrice ```solidity theme={null} function _getTradeLiquidationPrice(uint256 _openPrice, bool _long, uint256 _collateral, uint256 _leverage, uint256 _feesCollateral, uint256 _collateralPrecisionDelta, struct IPairsStorage.GroupLiquidationParams _liquidationParams, enum ITradingStorage.ContractsVersion _contractsVersion, uint256 _pairSpreadP) internal pure returns (uint256) ``` *Pure function that returns the liquidation price for a trade (1e10 precision)* ### Parameters | Name | Type | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | \_openPrice | uint256 | trade open price (1e10 precision) | | \_long | bool | true if long, false if short | | \_collateral | uint256 | trade collateral (collateral precision) | | \_leverage | uint256 | trade leverage (1e3 precision) | | \_feesCollateral | uint256 | closing fees + borrowing fees amount (collateral precision) | | \_collateralPrecisionDelta | uint256 | collateral precision delta (10^18/10^decimals) | | \_liquidationParams | [IPairsStorage.GroupLiquidationParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | liquidation parameters for the trade | | \_contractsVersion | enum ITradingStorage.ContractsVersion | contracts version of the trade | | \_pairSpreadP | uint256 | pair spread percentage (1e10) | ## \_setBorrowingPairParams ```solidity theme={null} function _setBorrowingPairParams(uint8 _collateralIndex, uint16 _pairIndex, struct IBorrowingFees.BorrowingPairParams _value) internal ``` *Function to set borrowing pair params* ### Parameters | Name | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_value | [IBorrowingFees.BorrowingPairParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new pair params | ## \_setBorrowingGroupParams ```solidity theme={null} function _setBorrowingGroupParams(uint8 _collateralIndex, uint16 _groupIndex, struct IBorrowingFees.BorrowingGroupParams _value) internal ``` *Function to set borrowing group params* ### Parameters | Name | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_value | [IBorrowingFees.BorrowingGroupParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new group params | ## \_updateOi ```solidity theme={null} function _updateOi(struct IBorrowingFees.OpenInterest _oiStorage, bool _long, bool _increase, uint256 _amountCollateral, uint128 _collateralPrecision) internal returns (uint72 newOiLong, uint72 newOiShort, uint72 delta) ``` *Function to update a borrowing pair/group open interest* ### Parameters | Name | Type | Description | | --------------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | \_oiStorage | [IBorrowingFees.OpenInterest](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#openinterest) | open interest storage reference | | \_long | bool | true if long, false if short | | \_increase | bool | true if increase, false if decrease | | \_amountCollateral | uint256 | amount of collateral to increase/decrease (collateral precision) | | \_collateralPrecision | uint128 | collateral precision (10^decimals) | ### Return Values | Name | Type | Description | | ---------- | ------ | ------------------------------------------------------- | | newOiLong | uint72 | new long open interest (1e10) | | newOiShort | uint72 | new short open interest (1e10) | | delta | uint72 | difference between new and current open interest (1e10) | ## \_updatePairOi ```solidity theme={null} function _updatePairOi(uint8 _collateralIndex, uint16 _pairIndex, bool _long, bool _increase, uint256 _amountCollateral) internal ``` *Function to update a borrowing group's open interest* ### Parameters | Name | Type | Description | | ------------------ | ------- | ---------------------------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the borrowing group | | \_long | bool | true if long, false if short | | \_increase | bool | true if increase, false if decrease | | \_amountCollateral | uint256 | amount of collateral to increase/decrease (collateral precision) | ## \_updateGroupOi ```solidity theme={null} function _updateGroupOi(uint8 _collateralIndex, uint16 _groupIndex, bool _long, bool _increase, uint256 _amountCollateral) internal ``` *Function to update a borrowing group's open interest* ### Parameters | Name | Type | Description | | ------------------ | ------- | ---------------------------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_long | bool | true if long, false if short | | \_increase | bool | true if increase, false if decrease | | \_amountCollateral | uint256 | amount of collateral to increase/decrease (collateral precision) | ## \_getBorrowingPairGroupAccFeesDeltas ```solidity theme={null} function _getBorrowingPairGroupAccFeesDeltas(uint8 _collateralIndex, uint256 _i, struct IBorrowingFees.BorrowingPairGroup[] _pairGroups, struct IBorrowingFees.BorrowingInitialAccFees _initialFees, uint16 _pairIndex, bool _long, uint256 _currentBlock) internal view returns (uint64 deltaGroup, uint64 deltaPair, bool beforeTradeOpen) ``` \_Calculates the borrowing group and pair acc fees deltas for a trade between pair group at index *i and next one* ### Parameters | Name | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_i | uint256 | index of the borrowing pair group | | \_pairGroups | [IBorrowingFees.BorrowingPairGroup\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairgroup) | all pair's historical borrowing groups | | \_initialFees | [IBorrowingFees.BorrowingInitialAccFees](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinginitialaccfees) | trade initial borrowing fees | | \_pairIndex | uint16 | index of the pair | | \_long | bool | true if long, false if short | | \_currentBlock | uint256 | current block number | ### Return Values | Name | Type | Description | | --------------- | ------ | ---------------------------------------------------------- | | deltaGroup | uint64 | difference between new and current group acc borrowing fee | | deltaPair | uint64 | difference between new and current pair acc borrowing fee | | beforeTradeOpen | bool | true if pair group was set before trade was opened | ## \_setPairPendingAccFees ```solidity theme={null} function _setPairPendingAccFees(uint8 _collateralIndex, uint16 _pairIndex, uint256 _currentBlock) internal returns (uint64 accFeeLong, uint64 accFeeShort) ``` ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_pairIndex | uint16 | index of the pair | | \_currentBlock | uint256 | current block number | ### Return Values | Name | Type | Description | | ----------- | ------ | --------------------------------------------------------- | | accFeeLong | uint64 | new pair acc borrowing fee on long side (1e10 precision) | | accFeeShort | uint64 | new pair acc borrowing fee on short side (1e10 precision) | ## \_setGroupPendingAccFees ```solidity theme={null} function _setGroupPendingAccFees(uint8 _collateralIndex, uint16 _groupIndex, uint256 _currentBlock) internal returns (uint64 accFeeLong, uint64 accFeeShort) ``` ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_groupIndex | uint16 | index of the borrowing group | | \_currentBlock | uint256 | current block number | ### Return Values | Name | Type | Description | | ----------- | ------ | ---------------------------------------------------------- | | accFeeLong | uint64 | new group acc borrowing fee on long side (1e10 precision) | | accFeeShort | uint64 | new group acc borrowing fee on short side (1e10 precision) | # ChainlinkClientUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/chainlinkclientutils \_Chainlink client refactored into library and all unused functions removed Uses price aggregator facet of multi collat diamond for storage. Copy of [https://github.com/smartcontractkit/chainlink/blob/contracts-v0.5.1/contracts/src/v0.8/ChainlinkClient.sol](https://github.com/smartcontractkit/chainlink/blob/contracts-v0.5.1/contracts/src/v0.8/ChainlinkClient.sol) with only `requestCount` changed to unset so as to be inherited by a proxy implementation.\_ ## ChainlinkRequested ```solidity theme={null} event ChainlinkRequested(bytes32 id) ``` ## ChainlinkFulfilled ```solidity theme={null} event ChainlinkFulfilled(bytes32 id) ``` ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IPriceAggregator.PriceAggregatorStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## buildChainlinkRequest ```solidity theme={null} function buildChainlinkRequest(bytes32 specId, address callbackAddr, bytes4 callbackFunctionSignature) internal pure returns (struct Chainlink.Request) ``` Creates a request that can hold additional parameters ### Parameters | Name | Type | Description | | ------------------------- | ------- | ------------------------------------------------------------- | | specId | bytes32 | The Job Specification ID that the request will be created for | | callbackAddr | address | address to operate the callback on | | callbackFunctionSignature | bytes4 | function signature to use for the callback | ### Return Values | Name | Type | Description | | ---- | ------------------------ | ------------------------------------ | | \[0] | struct Chainlink.Request | A Chainlink Request struct in memory | ## sendChainlinkRequestTo ```solidity theme={null} function sendChainlinkRequestTo(address oracleAddress, struct Chainlink.Request req, uint256 payment) internal returns (bytes32 requestId) ``` Creates a Chainlink request to the specified oracle address *Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to send LINK which creates a request on the target oracle contract. Emits ChainlinkRequested event.* ### Parameters | Name | Type | Description | | ------------- | ------------------------ | ------------------------------------------ | | oracleAddress | address | The address of the oracle for the request | | req | struct Chainlink.Request | The initialized Chainlink Request | | payment | uint256 | The amount of LINK to send for the request | ### Return Values | Name | Type | Description | | --------- | ------- | -------------- | | requestId | bytes32 | The request ID | ## setChainlinkToken ```solidity theme={null} function setChainlinkToken(address _linkErc677) internal ``` Sets the LINK token address ### Parameters | Name | Type | Description | | ------------ | ------- | -------------------------------------- | | \_linkErc677 | address | The address of the LINK token contract | ## validateChainlinkCallback ```solidity theme={null} function validateChainlinkCallback(bytes32 requestId) internal ``` Ensures that the fulfillment is valid for this contract *Use if the contract developer prefers methods instead of modifiers for validation* ### Parameters | Name | Type | Description | | --------- | ------- | ------------------------------ | | requestId | bytes32 | The request ID for fulfillment | ## recordChainlinkFulfillment ```solidity theme={null} modifier recordChainlinkFulfillment(bytes32 requestId) ``` *Reverts if the sender is not the oracle of the request. Emits ChainlinkFulfilled event.* ### Parameters | Name | Type | Description | | --------- | ------- | ------------------------------ | | requestId | bytes32 | The request ID for fulfillment | # ChainUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/chainutils *Chain helpers internal library* ## ARBITRUM\_MAINNET ```solidity theme={null} uint256 ARBITRUM_MAINNET ``` ## ARBITRUM\_SEPOLIA ```solidity theme={null} uint256 ARBITRUM_SEPOLIA ``` ## POLYGON\_MAINNET ```solidity theme={null} uint256 POLYGON_MAINNET ``` ## TESTNET ```solidity theme={null} uint256 TESTNET ``` ## Overflow ```solidity theme={null} error Overflow() ``` ## getBlockNumber ```solidity theme={null} function getBlockNumber() internal view returns (uint256) ``` *Returns the current block number (l2 block for arbitrum)* ## getUint48BlockNumber ```solidity theme={null} function getUint48BlockNumber(uint256 blockNumber) internal pure returns (uint48) ``` *Returns blockNumber converted to uint48* ### Parameters | Name | Type | Description | | ----------- | ------- | ----------------------- | | blockNumber | uint256 | block number to convert | ## getWrappedNativeToken ```solidity theme={null} function getWrappedNativeToken() internal view returns (address) ``` *Returns the wrapped native token address for the current chain* ## isWrappedNativeToken ```solidity theme={null} function isWrappedNativeToken(address _token) internal view returns (bool) ``` *Returns whether a token is the wrapped native token for the current chain* ### Parameters | Name | Type | Description | | ------- | ------- | ---------------------- | | \_token | address | token address to check | # CollateralUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/collateralutils *Collaterals decimal precision internal library* ## CollateralConfig ```solidity theme={null} struct CollateralConfig { uint128 precision; uint128 precisionDelta; } ``` ## getCollateralConfig ```solidity theme={null} function getCollateralConfig(address _token) internal view returns (struct CollateralUtils.CollateralConfig _meta) ``` \_Calculates `precision` (10^decimals) and `precisionDelta` (precision difference between 18 decimals and `token` decimals) of a given IERC20 `token` Notice: not compatible with tokens with more than 18 decimals\_ ### Parameters | Name | Type | Description | | ------- | ------- | ------------------------ | | \_token | address | collateral token address | # ConstantsUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/constantsutils *Internal library for important constants commonly used in many places* ## P\_10 ```solidity theme={null} uint256 P_10 ``` ## MAX\_PNL\_P ```solidity theme={null} uint256 MAX_PNL_P ``` ## SL\_LIQ\_BUFFER\_P ```solidity theme={null} uint256 SL_LIQ_BUFFER_P ``` ## LEGACY\_LIQ\_THRESHOLD\_P ```solidity theme={null} uint256 LEGACY_LIQ_THRESHOLD_P ``` ## MIN\_LIQ\_THRESHOLD\_P ```solidity theme={null} uint256 MIN_LIQ_THRESHOLD_P ``` ## MAX\_OPEN\_NEGATIVE\_PNL\_P ```solidity theme={null} uint256 MAX_OPEN_NEGATIVE_PNL_P ``` ## MAX\_LIQ\_SPREAD\_P ```solidity theme={null} uint256 MAX_LIQ_SPREAD_P ``` ## DEFAULT\_MAX\_CLOSING\_SLIPPAGE\_P ```solidity theme={null} uint16 DEFAULT_MAX_CLOSING_SLIPPAGE_P ``` ## getMarketOrderTypes ```solidity theme={null} function getMarketOrderTypes() internal pure returns (enum ITradingStorage.PendingOrderType[5]) ``` ## getPendingOpenOrderType ```solidity theme={null} function getPendingOpenOrderType(enum ITradingStorage.TradeType _tradeType) internal pure returns (enum ITradingStorage.PendingOrderType) ``` *Returns pending order type (market open/limit open/stop open) for a trade type (trade/limit/stop)* ### Parameters | Name | Type | Description | | ----------- | ------------------------------ | -------------- | | \_tradeType | enum ITradingStorage.TradeType | the trade type | ## isOrderTypeMarket ```solidity theme={null} function isOrderTypeMarket(enum ITradingStorage.PendingOrderType _orderType) internal pure returns (bool) ``` *Returns true if order type is market* ### Parameters | Name | Type | Description | | ----------- | ------------------------------------- | ----------- | | \_orderType | enum ITradingStorage.PendingOrderType | order type | # DiamondUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/diamondutils *Diamond standard internal library to access storage* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot for diamond data (facets, selectors, etc.)* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IDiamondStorage.DiamondStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* # FeeTiersUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/feetiersutils \_GNSFeeTiers facet internal library This is a library to apply fee tiers to trading fees based on a trailing point system.\_ ## initializeFeeTiers ```solidity theme={null} function initializeFeeTiers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers, uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) internal ``` *Check IFeeTiersUtils interface for documentation* ## setGroupVolumeMultipliers ```solidity theme={null} function setGroupVolumeMultipliers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers) internal ``` *Check IFeeTiersUtils interface for documentation* ## setFeeTiers ```solidity theme={null} function setFeeTiers(uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) internal ``` *Check IFeeTiersUtils interface for documentation* ## setTradersFeeTiersEnrollment ```solidity theme={null} function setTradersFeeTiersEnrollment(address[] _traders, struct IFeeTiers.TraderEnrollment[] _values) internal ``` *Check IFeeTiersUtils interface for documentation* ## addTradersUnclaimedPoints ```solidity theme={null} function addTradersUnclaimedPoints(address[] _traders, enum IFeeTiers.CreditType[] _creditTypes, uint224[] _points) internal ``` *Check IFeeTiersUtils interface for documentation* ## updateTraderPoints ```solidity theme={null} function updateTraderPoints(address _trader, uint256 _volumeUsd, uint256 _groupIndex) internal ``` *Check IFeeTiersUtils interface for documentation* ## calculateFeeAmount ```solidity theme={null} function calculateFeeAmount(address _trader, uint256 _normalFeeAmountCollateral) internal view returns (uint256) ``` *Check IFeeTiersUtils interface for documentation* ## getFeeTiersCount ```solidity theme={null} function getFeeTiersCount() internal view returns (uint256) ``` *Check IFeeTiersUtils interface for documentation* ## getFeeTier ```solidity theme={null} function getFeeTier(uint256 _feeTierIndex) internal view returns (struct IFeeTiers.FeeTier) ``` *Check IFeeTiersUtils interface for documentation* ## getGroupVolumeMultiplier ```solidity theme={null} function getGroupVolumeMultiplier(uint256 _groupIndex) internal view returns (uint256) ``` *Check IFeeTiersUtils interface for documentation* ## getFeeTiersTraderInfo ```solidity theme={null} function getFeeTiersTraderInfo(address _trader) internal view returns (struct IFeeTiers.TraderInfo) ``` *Check IFeeTiersUtils interface for documentation* ## getTraderFeeTiersEnrollment ```solidity theme={null} function getTraderFeeTiersEnrollment(address _trader) internal view returns (struct IFeeTiers.TraderEnrollment) ``` *Check IFeeTiersUtils interface for documentation* ## getTraderUnclaimedPoints ```solidity theme={null} function getTraderUnclaimedPoints(address _trader) internal view returns (uint224) ``` *Check IFeeTiersUtils interface for documentation* ## getFeeTiersTraderDailyInfo ```solidity theme={null} function getFeeTiersTraderDailyInfo(address _trader, uint32 _day) internal view returns (struct IFeeTiers.TraderDailyInfo) ``` *Check IFeeTiersUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IFeeTiers.FeeTiersStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_checkFeeTierUpdateValid ```solidity theme={null} function _checkFeeTierUpdateValid(uint256 _index, struct IFeeTiers.FeeTier _feeTier, struct IFeeTiers.FeeTier[8] _feeTiers) internal view ``` *Checks validity of a single fee tier update (feeMultiplier: descending, pointsThreshold: ascending, no gap)* ### Parameters | Name | Type | Description | | ---------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------- | | \_index | uint256 | index of the fee tier that was updated | | \_feeTier | [IFeeTiers.FeeTier](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | fee tier new value | | \_feeTiers | [IFeeTiers.FeeTier\[8\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | all fee tiers | ## \_getCurrentDay ```solidity theme={null} function _getCurrentDay() internal view returns (uint32) ``` *Get current day (index of mapping traderDailyInfo)* ## \_claimUnclaimedPoints ```solidity theme={null} function _claimUnclaimedPoints(address _trader) internal ``` *Claims unclaimed points for a trader and adds them to the daily points for the current day. In the event that it's the first points update for the trader, backdates points to yesterday so the tier discount becomes immediate.* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | # LiquidityPoolUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/liquiditypoolutils *Library to abstract liquidity pool operations such as fetching observations, calculating TWAP, etc. Currently supports Uniswap V3 and Algebra V1.9 liquidity pools* ## getLiquidityPoolInfo ```solidity theme={null} function getLiquidityPoolInfo(struct IPriceAggregator.LiquidityPoolInput _input) internal view returns (struct IPriceAggregator.LiquidityPoolInfo) ``` *Returns a `LiquidityPoolInfo` struct for LiquidityPoolInput `_input`* ### Parameters | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | | \_input | [IPriceAggregator.LiquidityPoolInput](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | LiquidityPoolInput struct with pool address and type | ## getTimeWeightedAveragePrice ```solidity theme={null} function getTimeWeightedAveragePrice(struct IPriceAggregator.LiquidityPoolInfo _poolInfo, uint32 _twapInterval, uint256 _precisionDelta) internal view returns (uint256) ``` *Calculates the time-weighted average price of a liquidity pool over a given interval* ### Parameters | Name | Type | Description | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | \_poolInfo | [IPriceAggregator.LiquidityPoolInfo](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinfo) | Liquidity pool info | | \_twapInterval | uint32 | TWAP interval in seconds | | \_precisionDelta | uint256 | precision delta of collateral | ## \_getPoolTickCumulatives ```solidity theme={null} function _getPoolTickCumulatives(struct IPriceAggregator.LiquidityPoolInfo _poolInfo, uint32 _twapInterval) internal view returns (int56[]) ``` *Fetches tickCumulatives data from the pool. Calls the appropriate oracle function based on the pool type* ### Parameters | Name | Type | Description | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------- | | \_poolInfo | [IPriceAggregator.LiquidityPoolInfo](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinfo) | Liquidity pool info | | \_twapInterval | uint32 | TWAP interval | ## \_tickCumulativesToTokenPrice ```solidity theme={null} function _tickCumulativesToTokenPrice(int56[] _tickCumulatives, uint32 _twapInterval, uint256 _precisionDelta, bool _isGnsToken0InLp) internal pure returns (uint256) ``` *Returns TWAP price (1e10 precision) from tickCumulatives data* ### Parameters | Name | Type | Description | | ----------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | \_tickCumulatives | int56\[] | array of tickCumulatives | | \_twapInterval | uint32 | TWAP interval | | \_precisionDelta | uint256 | precision delta of collateral | | \_isGnsToken0InLp | bool | true if GNS is token0 in LP Inspired from [https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/OracleLibrary.sol](https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/OracleLibrary.sol) | # OtcUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/otcutils *OTC facet internal library* ## initializeOtc ```solidity theme={null} function initializeOtc(struct IOtc.OtcConfig _config) internal ``` *Check IOtcUtils interface for documentation* ## updateOtcConfig ```solidity theme={null} function updateOtcConfig(struct IOtc.OtcConfig _config) internal ``` *Check IOtcUtils interface for documentation* ## addOtcCollateralBalance ```solidity theme={null} function addOtcCollateralBalance(uint8 _collateralIndex, uint256 _collateralAmount) internal ``` *Check IOtcUtils interface for documentation* ## sellGnsForCollateral ```solidity theme={null} function sellGnsForCollateral(uint8 _collateralIndex, uint256 _collateralAmount) internal ``` *Check IOtcUtils interface for documentation* ## getOtcConfig ```solidity theme={null} function getOtcConfig() internal view returns (struct IOtc.OtcConfig) ``` *Check IOtcUtils interface for documentation* ## getOtcBalance ```solidity theme={null} function getOtcBalance(uint8 _collateralIndex) internal view returns (uint256) ``` *Check IOtcUtils interface for documentation* ## getOtcRate ```solidity theme={null} function getOtcRate(uint8 _collateralIndex) internal view returns (uint256) ``` *Check IOtcUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IOtc.OtcStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## \_calculateGnsAmount ```solidity theme={null} function _calculateGnsAmount(uint8 _collateralIndex, uint256 _collateralAmount, uint256 _gnsPriceCollateral) internal view returns (uint256) ``` *Calculate GNS amount for given collateral amount* ### Parameters | Name | Type | Description | | -------------------- | ------- | ------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_collateralAmount | uint256 | amount of collateral (collateral precision) | | \_gnsPriceCollateral | uint256 | price of GNS in collateral (1e10) | ## \_calculateGnsDistribution ```solidity theme={null} function _calculateGnsDistribution(uint256 _gnsAmount) internal view returns (uint256 treasuryAmountGns, uint256 stakingAmountGns, uint256 burnAmountGns) ``` *Calculate GNS distribution for treasury, GNS staking and burn* ### Parameters | Name | Type | Description | | ----------- | ------- | ----------------------------------------- | | \_gnsAmount | uint256 | amount of GNS tokens to distribute (1e18) | ## \_distributeTreasuryGns ```solidity theme={null} function _distributeTreasuryGns(uint256 _gnsAmount) internal ``` *Distributes treasury rewards in GNS tokens* ### Parameters | Name | Type | Description | | ----------- | ------- | ----------------------------------------- | | \_gnsAmount | uint256 | amount of GNS tokens to distribute (1e18) | ## \_distributeStakingGns ```solidity theme={null} function _distributeStakingGns(uint256 _gnsAmount) internal ``` *Distributes staking rewards in GNS tokens* ### Parameters | Name | Type | Description | | ----------- | ------- | ----------------------------------------- | | \_gnsAmount | uint256 | amount of GNS tokens to distribute (1e18) | ## \_burnGns ```solidity theme={null} function _burnGns(uint256 _gnsAmount) internal ``` *Burns GNS tokens* ### Parameters | Name | Type | Description | | ----------- | ------- | ----------------------------------- | | \_gnsAmount | uint256 | amount of GNS tokens to burn (1e18) | # PackingUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/packingutils *External library used to pack and unpack values* ## pack ```solidity theme={null} function pack(uint256[] _values, uint256[] _bitLengths) external pure returns (uint256 packed) ``` *Packs values array into a single uint256* ### Parameters | Name | Type | Description | | ------------ | ---------- | ---------------------------------------- | | \_values | uint256\[] | values to pack | | \_bitLengths | uint256\[] | corresponding bit lengths for each value | ## unpack ```solidity theme={null} function unpack(uint256 _packed, uint256[] _bitLengths) external pure returns (uint256[] values) ``` *Unpacks a single uint256 into an array of values* ### Parameters | Name | Type | Description | | ------------ | ---------- | ---------------------------------------- | | \_packed | uint256 | packed value | | \_bitLengths | uint256\[] | corresponding bit lengths for each value | ## unpack256To64 ```solidity theme={null} function unpack256To64(uint256 _packed) external pure returns (uint64 a, uint64 b, uint64 c, uint64 d) ``` *Unpacks a single uint256 into 4 uint64 values* ### Parameters | Name | Type | Description | | -------- | ------- | ------------ | | \_packed | uint256 | packed value | ### Return Values | Name | Type | Description | | ---- | ------ | ---------------- | | a | uint64 | returned value 1 | | b | uint64 | returned value 2 | | c | uint64 | returned value 3 | | d | uint64 | returned value 4 | ## unpackTriggerOrder ```solidity theme={null} function unpackTriggerOrder(uint256 _packed) external pure returns (uint8 orderType, address trader, uint32 index) ``` *Unpacks trigger order calldata into 3 values* ### Parameters | Name | Type | Description | | -------- | ------- | ------------ | | \_packed | uint256 | packed value | ### Return Values | Name | Type | Description | | --------- | ------- | -------------- | | orderType | uint8 | order type | | trader | address | trader address | | index | uint32 | trade index | # PairsStorageUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/pairsstorageutils *GNSPairsStorage facet internal library* ## initializeGroupLiquidationParams ```solidity theme={null} function initializeGroupLiquidationParams(struct IPairsStorage.GroupLiquidationParams[] _groupLiquidationParams) internal ``` *Check IPairsStorageUtils interface for documentation* ## initializeNewFees ```solidity theme={null} function initializeNewFees(struct IPairsStorage.GlobalTradeFeeParams _tradeFeeParams) internal ``` *Check IPairsStorageUtils interface for documentation* ## addPairs ```solidity theme={null} function addPairs(struct IPairsStorage.Pair[] _pairs) internal ``` *Check IPairsStorageUtils interface for documentation* ## updatePairs ```solidity theme={null} function updatePairs(uint256[] _pairIndices, struct IPairsStorage.Pair[] _pairs) internal ``` *Check IPairsStorageUtils interface for documentation* ## addGroups ```solidity theme={null} function addGroups(struct IPairsStorage.Group[] _groups) internal ``` *Check IPairsStorageUtils interface for documentation* ## updateGroups ```solidity theme={null} function updateGroups(uint256[] _ids, struct IPairsStorage.Group[] _groups) internal ``` *Check IPairsStorageUtils interface for documentation* ## addFees ```solidity theme={null} function addFees(struct IPairsStorage.FeeGroup[] _fees) internal ``` *Check IPairsStorageUtils interface for documentation* ## updateFees ```solidity theme={null} function updateFees(uint256[] _ids, struct IPairsStorage.FeeGroup[] _fees) internal ``` *Check IPairsStorageUtils interface for documentation* ## setPairCustomMaxLeverages ```solidity theme={null} function setPairCustomMaxLeverages(uint256[] _indices, uint256[] _values) internal ``` *Check IPairsStorageUtils interface for documentation* ## setGroupLiquidationParams ```solidity theme={null} function setGroupLiquidationParams(uint256 _groupIndex, struct IPairsStorage.GroupLiquidationParams _params) internal ``` *Check IPairsStorageUtils interface for documentation* ## setGlobalTradeFeeParams ```solidity theme={null} function setGlobalTradeFeeParams(struct IPairsStorage.GlobalTradeFeeParams _feeParams) internal ``` *Check IPairsStorageUtils interface for documentation* ## pairJob ```solidity theme={null} function pairJob(uint256 _pairIndex) internal view returns (string, string) ``` *Check IPairsStorageUtils interface for documentation* ## isPairListed ```solidity theme={null} function isPairListed(string _from, string _to) internal view returns (bool) ``` *Check IPairsStorageUtils interface for documentation* ## isPairIndexListed ```solidity theme={null} function isPairIndexListed(uint256 _pairIndex) internal view returns (bool) ``` *Check IPairsStorageUtils interface for documentation* ## pairs ```solidity theme={null} function pairs(uint256 _index) internal view returns (struct IPairsStorage.Pair) ``` *Check IPairsStorageUtils interface for documentation* ## pairsCount ```solidity theme={null} function pairsCount() internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairSpreadP ```solidity theme={null} function pairSpreadP(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairMinLeverage ```solidity theme={null} function pairMinLeverage(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairTotalPositionSizeFeeP ```solidity theme={null} function pairTotalPositionSizeFeeP(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairTotalLiqCollateralFeeP ```solidity theme={null} function pairTotalLiqCollateralFeeP(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairOraclePositionSizeFeeP ```solidity theme={null} function pairOraclePositionSizeFeeP(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairMinPositionSizeUsd ```solidity theme={null} function pairMinPositionSizeUsd(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## getGlobalTradeFeeParams ```solidity theme={null} function getGlobalTradeFeeParams() internal view returns (struct IPairsStorage.GlobalTradeFeeParams) ``` *Check IPairsStorageUtils interface for documentation* ## pairMinFeeUsd ```solidity theme={null} function pairMinFeeUsd(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairFeeIndex ```solidity theme={null} function pairFeeIndex(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## groups ```solidity theme={null} function groups(uint256 _index) internal view returns (struct IPairsStorage.Group) ``` *Check IPairsStorageUtils interface for documentation* ## groupsCount ```solidity theme={null} function groupsCount() internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## fees ```solidity theme={null} function fees(uint256 _index) internal view returns (struct IPairsStorage.FeeGroup) ``` *Check IPairsStorageUtils interface for documentation* ## feesCount ```solidity theme={null} function feesCount() internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairMaxLeverage ```solidity theme={null} function pairMaxLeverage(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## pairCustomMaxLeverage ```solidity theme={null} function pairCustomMaxLeverage(uint256 _pairIndex) internal view returns (uint256) ``` *Check IPairsStorageUtils interface for documentation* ## getAllPairsRestrictedMaxLeverage ```solidity theme={null} function getAllPairsRestrictedMaxLeverage() internal view returns (uint256[]) ``` *Check IPairsStorageUtils interface for documentation* ## getGroupLiquidationParams ```solidity theme={null} function getGroupLiquidationParams(uint256 _groupIndex) internal view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Check IPairsStorageUtils interface for documentation* ## getPairLiquidationParams ```solidity theme={null} function getPairLiquidationParams(uint256 _pairIndex) internal view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Check IPairsStorageUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IPairsStorage.PairsStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## groupListed ```solidity theme={null} modifier groupListed(uint256 _groupIndex) ``` Reverts if group is not listed ### Parameters | Name | Type | Description | | ------------ | ------- | -------------------- | | \_groupIndex | uint256 | group index to check | ## feeListed ```solidity theme={null} modifier feeListed(uint256 _feeIndex) ``` Reverts if fee is not listed ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------ | | \_feeIndex | uint256 | fee index to check | ## groupOk ```solidity theme={null} modifier groupOk(struct IPairsStorage.Group _group) ``` Reverts if group is not valid ### Parameters | Name | Type | Description | | ------- | -------------------------- | -------------- | | \_group | struct IPairsStorage.Group | group to check | ## feeOk ```solidity theme={null} modifier feeOk(struct IPairsStorage.FeeGroup _fee) ``` *Reverts if fee is not valid* ### Parameters | Name | Type | Description | | ----- | ----------------------------- | ------------ | | \_fee | struct IPairsStorage.FeeGroup | fee to check | ## \_addPair ```solidity theme={null} function _addPair(struct IPairsStorage.Pair _pair) internal ``` *Adds a new trading pair* ### Parameters | Name | Type | Description | | ------ | -------------------------------------------------------------------------------------------------- | ----------- | | \_pair | [IPairsStorage.Pair](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | pair to add | ## \_updatePair ```solidity theme={null} function _updatePair(uint256 _pairIndex, struct IPairsStorage.Pair _pair) internal ``` *Updates an existing trading pair* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | ----------------------- | | \_pairIndex | uint256 | index of pair to update | | \_pair | [IPairsStorage.Pair](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | new pair value | ## \_addGroup ```solidity theme={null} function _addGroup(struct IPairsStorage.Group _group) internal ``` *Adds a new pair group* ### Parameters | Name | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------- | ------------ | | \_group | [IPairsStorage.Group](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | group to add | ## \_updateGroup ```solidity theme={null} function _updateGroup(uint256 _id, struct IPairsStorage.Group _group) internal ``` *Updates an existing pair group* ### Parameters | Name | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------- | ------------------------ | | \_id | uint256 | index of group to update | | \_group | [IPairsStorage.Group](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | new group value | ## \_addFee ```solidity theme={null} function _addFee(struct IPairsStorage.FeeGroup _fee) internal ``` *Adds a new pair fee group* ### Parameters | Name | Type | Description | | ----- | ---------------------------------------------------------------------------------------------------------- | ----------- | | \_fee | [IPairsStorage.FeeGroup](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | fee to add | ## \_updateFee ```solidity theme={null} function _updateFee(uint256 _id, struct IPairsStorage.FeeGroup _fee) internal ``` *Updates an existing pair fee group* ### Parameters | Name | Type | Description | | ----- | ---------------------------------------------------------------------------------------------------------- | ---------------------- | | \_id | uint256 | index of fee to update | | \_fee | [IPairsStorage.FeeGroup](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | new fee value | # PriceAggregatorUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/priceaggregatorutils *GNSPriceAggregator facet external library* ## initializePriceAggregator ```solidity theme={null} function initializePriceAggregator(address _linkErc677, contract IChainlinkFeed _linkUsdPriceFeed, uint24 _twapInterval, uint8 _minAnswers, address[] _oracles, bytes32[2] _jobIds, uint8[] _collateralIndices, struct IPriceAggregator.LiquidityPoolInput[] _gnsCollateralLiquidityPools, contract IChainlinkFeed[] _collateralUsdPriceFeeds) external ``` *Check IPriceAggregatorUtils interface for documentation* ## updateLinkUsdPriceFeed ```solidity theme={null} function updateLinkUsdPriceFeed(contract IChainlinkFeed _value) public ``` *Check IPriceAggregatorUtils interface for documentation* ## updateCollateralUsdPriceFeed ```solidity theme={null} function updateCollateralUsdPriceFeed(uint8 _collateralIndex, contract IChainlinkFeed _value) public ``` *Check IPriceAggregatorUtils interface for documentation* ## updateCollateralGnsLiquidityPool ```solidity theme={null} function updateCollateralGnsLiquidityPool(uint8 _collateralIndex, struct IPriceAggregator.LiquidityPoolInput _liquidityPoolInput) public ``` *Check IPriceAggregatorUtils interface for documentation* ## updateTwapInterval ```solidity theme={null} function updateTwapInterval(uint24 _twapInterval) public ``` *Check IPriceAggregatorUtils interface for documentation* ## updateMinAnswers ```solidity theme={null} function updateMinAnswers(uint8 _value) public ``` *Check IPriceAggregatorUtils interface for documentation* ## addOracle ```solidity theme={null} function addOracle(address _a) public ``` *Check IPriceAggregatorUtils interface for documentation* ## replaceOracle ```solidity theme={null} function replaceOracle(uint256 _index, address _a) external ``` *Check IPriceAggregatorUtils interface for documentation* ## removeOracle ```solidity theme={null} function removeOracle(uint256 _index) external ``` *Check IPriceAggregatorUtils interface for documentation* ## setMarketJobId ```solidity theme={null} function setMarketJobId(bytes32 _jobId) public ``` *Check IPriceAggregatorUtils interface for documentation* ## setLimitJobId ```solidity theme={null} function setLimitJobId(bytes32 _jobId) public ``` *Check IPriceAggregatorUtils interface for documentation* ## getPrice ```solidity theme={null} function getPrice(uint8 _collateralIndex, uint16 _pairIndex, struct ITradingStorage.Id _tradeId, struct ITradingStorage.Id _orderId, enum ITradingStorage.PendingOrderType _orderType, uint256 _positionSizeCollateral, uint256 _fromBlock) external ``` *Check IPriceAggregatorUtils interface for documentation* ## fulfill ```solidity theme={null} function fulfill(bytes32 _requestId, uint256 _priceData) external ``` *Check IPriceAggregatorUtils interface for documentation* ## claimBackLink ```solidity theme={null} function claimBackLink() external ``` *Check IPriceAggregatorUtils interface for documentation* ## getLinkFee ```solidity theme={null} function getLinkFee(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _positionSizeCollateral) public view returns (uint256) ``` *Check IPriceAggregatorUtils interface for documentation* ## getCollateralPriceUsd ```solidity theme={null} function getCollateralPriceUsd(uint8 _collateralIndex) public view returns (uint256) ``` *Check IPriceAggregatorUtils interface for documentation* ## getUsdNormalizedValue ```solidity theme={null} function getUsdNormalizedValue(uint8 _collateralIndex, uint256 _collateralValue) public view returns (uint256) ``` *Check IPriceAggregatorUtils interface for documentation* ## getCollateralFromUsdNormalizedValue ```solidity theme={null} function getCollateralFromUsdNormalizedValue(uint8 _collateralIndex, uint256 _normalizedValue) external view returns (uint256) ``` *Check IPriceAggregatorUtils interface for documentation* ## getGnsPriceUsd ```solidity theme={null} function getGnsPriceUsd(uint8 _collateralIndex) external view returns (uint256) ``` *Check IPriceAggregatorUtils interface for documentation* ## getGnsPriceUsd ```solidity theme={null} function getGnsPriceUsd(uint8 _collateralIndex, uint256 _gnsPriceCollateral) public view returns (uint256) ``` *Check IPriceAggregatorUtils interface for documentation* ## getGnsPriceCollateralAddress ```solidity theme={null} function getGnsPriceCollateralAddress(address _collateral) external view returns (uint256 _price) ``` *Check IPriceAggregatorUtils interface for documentation* ## getGnsPriceCollateralIndex ```solidity theme={null} function getGnsPriceCollateralIndex(uint8 _collateralIndex) public view returns (uint256 _price) ``` *Check IPriceAggregatorUtils interface for documentation* ## getLinkUsdPriceFeed ```solidity theme={null} function getLinkUsdPriceFeed() external view returns (contract IChainlinkFeed) ``` *Check IPriceAggregatorUtils interface for documentation* ## getTwapInterval ```solidity theme={null} function getTwapInterval() external view returns (uint24) ``` *Check IPriceAggregatorUtils interface for documentation* ## getMinAnswers ```solidity theme={null} function getMinAnswers() external view returns (uint8) ``` *Check IPriceAggregatorUtils interface for documentation* ## getMarketJobId ```solidity theme={null} function getMarketJobId() external view returns (bytes32) ``` *Check IPriceAggregatorUtils interface for documentation* ## getLimitJobId ```solidity theme={null} function getLimitJobId() external view returns (bytes32) ``` *Check IPriceAggregatorUtils interface for documentation* ## getOracle ```solidity theme={null} function getOracle(uint256 _index) external view returns (address) ``` *Check IPriceAggregatorUtils interface for documentation* ## getOracles ```solidity theme={null} function getOracles() external view returns (address[]) ``` *Check IPriceAggregatorUtils interface for documentation* ## getCollateralGnsLiquidityPool ```solidity theme={null} function getCollateralGnsLiquidityPool(uint8 _collateralIndex) external view returns (struct IPriceAggregator.LiquidityPoolInfo) ``` *Check IPriceAggregatorUtils interface for documentation* ## getCollateralUsdPriceFeed ```solidity theme={null} function getCollateralUsdPriceFeed(uint8 _collateralIndex) external view returns (contract IChainlinkFeed) ``` *Check IPriceAggregatorUtils interface for documentation* ## getPriceAggregatorOrder ```solidity theme={null} function getPriceAggregatorOrder(bytes32 _requestId) external view returns (struct IPriceAggregator.Order) ``` *Check IPriceAggregatorUtils interface for documentation* ## getPriceAggregatorOrderAnswers ```solidity theme={null} function getPriceAggregatorOrderAnswers(struct ITradingStorage.Id _orderId) external view returns (struct IPriceAggregator.OrderAnswer[]) ``` *Check IPriceAggregatorUtils interface for documentation* ## getChainlinkToken ```solidity theme={null} function getChainlinkToken() public view returns (address) ``` *Check IPriceAggregatorUtils interface for documentation* ## getRequestCount ```solidity theme={null} function getRequestCount() external view returns (uint256) ``` *Check IPriceAggregatorUtils interface for documentation* ## getPendingRequest ```solidity theme={null} function getPendingRequest(bytes32 _id) external view returns (address) ``` *Check IPriceAggregatorUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IPriceAggregator.PriceAggregatorStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## validCollateralIndex ```solidity theme={null} modifier validCollateralIndex(uint8 _collateralIndex) ``` *Reverts if collateral index is not valid* ## \_median ```solidity theme={null} function _median(struct IPriceAggregator.OrderAnswer[] _array) internal pure returns (uint64) ``` *returns median price of array (1 price only)* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------------------------- | --------------- | | \_array | [IPriceAggregator.OrderAnswer\[\]](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#orderanswer) | array of values | ## \_medianLookbacks ```solidity theme={null} function _medianLookbacks(struct IPriceAggregator.OrderAnswer[] _array) internal pure returns (uint64 open, uint64 high, uint64 low) ``` *returns median prices of array (open, high, low)* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------------------------- | --------------- | | \_array | [IPriceAggregator.OrderAnswer\[\]](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#orderanswer) | array of values | ## \_swap ```solidity theme={null} function _swap(uint256[] _array, uint256 _i, uint256 _j) internal pure ``` *swaps two elements in array* ### Parameters | Name | Type | Description | | ------- | ---------- | ----------------------- | | \_array | uint256\[] | array of values | | \_i | uint256 | index of first element | | \_j | uint256 | index of second element | ## \_sort ```solidity theme={null} function _sort(uint256[] _array, uint256 begin, uint256 end) internal pure ``` *sorts array of uint256 values* ### Parameters | Name | Type | Description | | ------- | ---------- | --------------- | | \_array | uint256\[] | array of values | | begin | uint256 | start index | | end | uint256 | end index | ## \_getCollateralPrecisionDelta ```solidity theme={null} function _getCollateralPrecisionDelta(uint8 _collateralIndex) internal view returns (uint256) ``` *Returns precision delta of collateral as uint256* ### Parameters | Name | Type | Description | | ----------------- | ----- | ------------------- | | \_collateralIndex | uint8 | index of collateral | # PriceImpactUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/priceimpactutils \_GNSPriceImpact facet internal library This is a library to help manage a price impact decay algorithm . When a trade is placed, OI is added to the window corresponding to time of open. When a trade is removed, OI is removed from the window corresponding to time of open. When calculating price impact, only the most recent X windows are taken into account.\_ ## validWindowsDuration ```solidity theme={null} modifier validWindowsDuration(uint48 _windowsDuration) ``` *Validates new windowsDuration value* ## initializePriceImpact ```solidity theme={null} function initializePriceImpact(uint48 _windowsDuration, uint48 _windowsCount) internal ``` *Check IPriceImpactUtils interface for documentation* ## initializeNegPnlCumulVolMultiplier ```solidity theme={null} function initializeNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) internal ``` *Check IPriceImpactUtils interface for documentation* ## initializePairFactors ```solidity theme={null} function initializePairFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors, uint32[] _protectionCloseFactorBlocks, uint40[] _cumulativeFactors) internal ``` *Check IPriceImpactUtils interface for documentation* ## setPriceImpactWindowsCount ```solidity theme={null} function setPriceImpactWindowsCount(uint48 _newWindowsCount) internal ``` *Check IPriceImpactUtils interface for documentation* ## setPriceImpactWindowsDuration ```solidity theme={null} function setPriceImpactWindowsDuration(uint48 _newWindowsDuration, uint256 _pairsCount) internal ``` *Check IPriceImpactUtils interface for documentation* ## setNegPnlCumulVolMultiplier ```solidity theme={null} function setNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) internal ``` *Check IPriceImpactUtils interface for documentation* ## setProtectionCloseFactorWhitelist ```solidity theme={null} function setProtectionCloseFactorWhitelist(address[] _traders, bool[] _whitelisted) internal ``` *Check IPriceImpactUtils interface for documentation* ## setPairDepths ```solidity theme={null} function setPairDepths(uint256[] _indices, uint128[] _depthsAboveUsd, uint128[] _depthsBelowUsd) internal ``` *Check IPriceImpactUtils interface for documentation* ## setProtectionCloseFactors ```solidity theme={null} function setProtectionCloseFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors) internal ``` *Check IPriceImpactUtils interface for documentation* ## setProtectionCloseFactorBlocks ```solidity theme={null} function setProtectionCloseFactorBlocks(uint16[] _pairIndices, uint32[] _protectionCloseFactorBlocks) internal ``` *Check IPriceImpactUtils interface for documentation* ## setCumulativeFactors ```solidity theme={null} function setCumulativeFactors(uint16[] _pairIndices, uint40[] _cumulativeFactors) internal ``` *Check IPriceImpactUtils interface for documentation* ## setExemptOnOpen ```solidity theme={null} function setExemptOnOpen(uint16[] _pairIndices, bool[] _exemptOnOpen) internal ``` *Check IPriceImpactUtils interface for documentation* ## setExemptAfterProtectionCloseFactor ```solidity theme={null} function setExemptAfterProtectionCloseFactor(uint16[] _pairIndices, bool[] _exemptAfterProtectionCloseFactor) internal ``` *Check IPriceImpactUtils interface for documentation* ## addPriceImpactOpenInterest ```solidity theme={null} function addPriceImpactOpenInterest(address _trader, uint32 _index, uint256 _oiDeltaCollateral, bool _open, bool _isPnlPositive) internal ``` *Check IPriceImpactUtils interface for documentation* ## getPriceImpactOi ```solidity theme={null} function getPriceImpactOi(uint256 _pairIndex, bool _long) internal view returns (uint256 activeOi) ``` *Check IPriceImpactUtils interface for documentation* ## getTradePriceImpact ```solidity theme={null} function getTradePriceImpact(address _trader, uint256 _marketPrice, uint256 _pairIndex, bool _long, uint256 _tradeOpenInterestUsd, bool _isPnlPositive, bool _open, uint256 _lastPosIncreaseBlock, enum ITradingStorage.ContractsVersion _contractsVersion) internal view returns (uint256 priceImpactP, uint256 priceAfterImpact) ``` *Check IPriceImpactUtils interface for documentation* ## getPairDepth ```solidity theme={null} function getPairDepth(uint256 _pairIndex) internal view returns (struct IPriceImpact.PairDepth) ``` *Check IPriceImpactUtils interface for documentation* ## getOiWindowsSettings ```solidity theme={null} function getOiWindowsSettings() internal view returns (struct IPriceImpact.OiWindowsSettings) ``` *Check IPriceImpactUtils interface for documentation* ## getOiWindow ```solidity theme={null} function getOiWindow(uint48 _windowsDuration, uint256 _pairIndex, uint256 _windowId) internal view returns (struct IPriceImpact.PairOi) ``` *Check IPriceImpactUtils interface for documentation* ## getOiWindows ```solidity theme={null} function getOiWindows(uint48 _windowsDuration, uint256 _pairIndex, uint256[] _windowIds) internal view returns (struct IPriceImpact.PairOi[]) ``` *Check IPriceImpactUtils interface for documentation* ## getPairDepths ```solidity theme={null} function getPairDepths(uint256[] _indices) internal view returns (struct IPriceImpact.PairDepth[]) ``` *Check IPriceImpactUtils interface for documentation* ## getPairFactors ```solidity theme={null} function getPairFactors(uint256[] _indices) internal view returns (struct IPriceImpact.PairFactors[] pairFactors) ``` *Check IPriceImpactUtils interface for documentation* ## getNegPnlCumulVolMultiplier ```solidity theme={null} function getNegPnlCumulVolMultiplier() internal view returns (uint40) ``` *Check IPriceImpactUtils interface for documentation* ## getProtectionCloseFactorWhitelist ```solidity theme={null} function getProtectionCloseFactorWhitelist(address _trader) internal view returns (bool) ``` *Check IPriceImpactUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IPriceImpact.PriceImpactStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## \_transferPriceImpactOiForPairs ```solidity theme={null} function _transferPriceImpactOiForPairs(uint256 _pairsCount, mapping(uint256 => mapping(uint256 => struct IPriceImpact.PairOi)) _prevPairOiWindows, mapping(uint256 => mapping(uint256 => struct IPriceImpact.PairOi)) _newPairOiWindows, struct IPriceImpact.OiWindowsSettings _settings, uint48 _newWindowsDuration) internal ``` \_Transfers total long / short OI from last '\_settings.windowsCount' windows of `_prevPairOiWindows` to current window of `_newPairOiWindows` for `_pairsCount` pairs. Emits a \{PriceImpactOiTransferredPairs} event.\_ ### Parameters | Name | Type | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | \_pairsCount | uint256 | number of pairs | | \_prevPairOiWindows | mapping(uint256 => mapping(uint256 => struct IPriceImpact.PairOi)) | previous pair OI windows (previous windowsDuration mapping) | | \_newPairOiWindows | mapping(uint256 => mapping(uint256 => struct IPriceImpact.PairOi)) | new pair OI windows (new windowsDuration mapping) | | \_settings | [IPriceImpact.OiWindowsSettings](/developer/technical-reference/contracts/interfaces/types/ipriceimpact#oiwindowssettings) | current OI windows settings | | \_newWindowsDuration | uint48 | new windows duration | ## \_transferPriceImpactOiForPair ```solidity theme={null} function _transferPriceImpactOiForPair(uint256 _pairIndex, uint256 _prevCurrentWindowId, uint256 _prevEarliestWindowId, mapping(uint256 => struct IPriceImpact.PairOi) _prevPairOiWindows, struct IPriceImpact.PairOi _newPairOiWindow) internal ``` \_Transfers total long / short OI from `prevEarliestWindowId` to `prevCurrentWindowId` windows of `_prevPairOiWindows` to `_newPairOiWindow` window. Emits a \{PriceImpactOiTransferredPair} event.\_ ### Parameters | Name | Type | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | \_pairIndex | uint256 | index of the pair | | \_prevCurrentWindowId | uint256 | previous current window ID | | \_prevEarliestWindowId | uint256 | previous earliest active window ID | | \_prevPairOiWindows | mapping(uint256 => struct IPriceImpact.PairOi) | previous pair OI windows (previous windowsDuration mapping) | | \_newPairOiWindow | [IPriceImpact.PairOi](/developer/technical-reference/contracts/interfaces/types/ipriceimpact#pairoi) | new pair OI window (new windowsDuration mapping) | ## \_getWindowId ```solidity theme={null} function _getWindowId(uint48 _timestamp, struct IPriceImpact.OiWindowsSettings _settings) internal pure returns (uint256) ``` *Returns window id at `_timestamp` given `_settings`.* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------- | | \_timestamp | uint48 | timestamp | | \_settings | [IPriceImpact.OiWindowsSettings](/developer/technical-reference/contracts/interfaces/types/ipriceimpact#oiwindowssettings) | OI windows settings | ## \_getCurrentWindowId ```solidity theme={null} function _getCurrentWindowId(struct IPriceImpact.OiWindowsSettings _settings) internal view returns (uint256) ``` *Returns window id at current timestamp given `_settings`.* ### Parameters | Name | Type | Description | | ---------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------- | | \_settings | [IPriceImpact.OiWindowsSettings](/developer/technical-reference/contracts/interfaces/types/ipriceimpact#oiwindowssettings) | OI windows settings | ## \_getEarliestActiveWindowId ```solidity theme={null} function _getEarliestActiveWindowId(uint256 _currentWindowId, uint48 _windowsCount) internal pure returns (uint256) ``` *Returns earliest active window id given `_currentWindowId` and `_windowsCount`.* ### Parameters | Name | Type | Description | | ----------------- | ------- | -------------------- | | \_currentWindowId | uint256 | current window id | | \_windowsCount | uint48 | active windows count | ## \_isWindowPotentiallyActive ```solidity theme={null} function _isWindowPotentiallyActive(uint256 _windowId, uint256 _currentWindowId) internal pure returns (bool) ``` \_Returns whether '*windowId' can be potentially active id given `_currentWindowId`* ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------- | | \_windowId | uint256 | window id | | \_currentWindowId | uint256 | current window id | ## \_getTradePriceImpact ```solidity theme={null} function _getTradePriceImpact(uint256 _marketPrice, bool _long, uint256 _startOpenInterestUsd, uint256 _tradeOpenInterestUsd, uint256 _onePercentDepthUsd, bool _open, uint256 _protectionCloseFactor, uint256 _cumulativeFactor, enum ITradingStorage.ContractsVersion _contractsVersion) internal pure returns (uint256 priceImpactP, uint256 priceAfterImpact) ``` *Returns trade price impact % and opening price after impact.* ### Parameters | Name | Type | Description | | ----------------------- | ------------------------------------- | -------------------------------------------------------------------- | | \_marketPrice | uint256 | market price (1e10 precision) | | \_long | bool | true for long, false for short | | \_startOpenInterestUsd | uint256 | existing open interest of pair on trade side in USD (1e18 precision) | | \_tradeOpenInterestUsd | uint256 | open interest of trade in USD (1e18 precision) | | \_onePercentDepthUsd | uint256 | one percent depth of pair in USD on trade side | | \_open | bool | true for open, false for close | | \_protectionCloseFactor | uint256 | protection close factor (1e10 precision) | | \_cumulativeFactor | uint256 | cumulative factor (1e10 precision) | | \_contractsVersion | enum ITradingStorage.ContractsVersion | trade contracts version | # ReferralsUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/referralsutils *GNSReferrals facet internal library* ## initializeReferrals ```solidity theme={null} function initializeReferrals(uint256 _allyFeeP, uint256 _startReferrerFeeP, uint256 _targetVolumeUsd) internal ``` *Check IReferralsUtils interface for documentation* ## updateAllyFeeP ```solidity theme={null} function updateAllyFeeP(uint256 _value) internal ``` *Check IReferralsUtils interface for documentation* ## updateStartReferrerFeeP ```solidity theme={null} function updateStartReferrerFeeP(uint256 _value) internal ``` *Check IReferralsUtils interface for documentation* ## updateReferralsTargetVolumeUsd ```solidity theme={null} function updateReferralsTargetVolumeUsd(uint256 _value) internal ``` *Check IReferralsUtils interface for documentation* ## whitelistAllies ```solidity theme={null} function whitelistAllies(address[] _allies) internal ``` *Check IReferralsUtils interface for documentation* ## unwhitelistAllies ```solidity theme={null} function unwhitelistAllies(address[] _allies) internal ``` *Check IReferralsUtils interface for documentation* ## whitelistReferrers ```solidity theme={null} function whitelistReferrers(address[] _referrers, address[] _allies) internal ``` *Check IReferralsUtils interface for documentation* ## unwhitelistReferrers ```solidity theme={null} function unwhitelistReferrers(address[] _referrers) internal ``` *Check IReferralsUtils interface for documentation* ## registerPotentialReferrer ```solidity theme={null} function registerPotentialReferrer(address _trader, address _referrer) internal ``` *Check IReferralsUtils interface for documentation* ## distributeReferralReward ```solidity theme={null} function distributeReferralReward(address _trader, uint256 _volumeUsd, uint256 _referrerFeeUsd, uint256 _gnsPriceUsd) internal ``` *Check IReferralsUtils interface for documentation* ## claimAllyRewards ```solidity theme={null} function claimAllyRewards() internal ``` *Check IReferralsUtils interface for documentation* ## claimReferrerRewards ```solidity theme={null} function claimReferrerRewards() internal ``` *Check IReferralsUtils interface for documentation* ## getReferrerFeeProgressP ```solidity theme={null} function getReferrerFeeProgressP(address _referrer) internal view returns (uint256 progressP) ``` *Check IReferralsUtils interface for documentation* ## getTraderLastReferrer ```solidity theme={null} function getTraderLastReferrer(address _trader) internal view returns (address) ``` *Check IReferralsUtils interface for documentation* ## getTraderActiveReferrer ```solidity theme={null} function getTraderActiveReferrer(address _trader) internal view returns (address) ``` *Check IReferralsUtils interface for documentation* ## getReferrersReferred ```solidity theme={null} function getReferrersReferred(address _ally) internal view returns (address[]) ``` *Check IReferralsUtils interface for documentation* ## getTradersReferred ```solidity theme={null} function getTradersReferred(address _referrer) internal view returns (address[]) ``` *Check IReferralsUtils interface for documentation* ## getReferralsAllyFeeP ```solidity theme={null} function getReferralsAllyFeeP() internal view returns (uint256) ``` *Check IReferralsUtils interface for documentation* ## getReferralsStartReferrerFeeP ```solidity theme={null} function getReferralsStartReferrerFeeP() internal view returns (uint256) ``` *Check IReferralsUtils interface for documentation* ## getReferralsTargetVolumeUsd ```solidity theme={null} function getReferralsTargetVolumeUsd() internal view returns (uint256) ``` *Check IReferralsUtils interface for documentation* ## getAllyDetails ```solidity theme={null} function getAllyDetails(address _ally) internal view returns (struct IReferrals.AllyDetails) ``` *Check IReferralsUtils interface for documentation* ## getReferrerDetails ```solidity theme={null} function getReferrerDetails(address _referrer) internal view returns (struct IReferrals.ReferrerDetails) ``` *Check IReferralsUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct IReferrals.ReferralsStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_whitelistAlly ```solidity theme={null} function _whitelistAlly(address _ally) internal ``` *Whitelists new ally* ### Parameters | Name | Type | Description | | ------ | ------- | --------------- | | \_ally | address | address of ally | ## \_unwhitelistAlly ```solidity theme={null} function _unwhitelistAlly(address _ally) internal ``` *Unwhitelists ally* ### Parameters | Name | Type | Description | | ------ | ------- | --------------- | | \_ally | address | address of ally | ## \_whitelistReferrer ```solidity theme={null} function _whitelistReferrer(address _referrer, address _ally) internal ``` *Whitelists new referrer* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------- | | \_referrer | address | address of referrer | | \_ally | address | address of ally | ## \_unwhitelistReferrer ```solidity theme={null} function _unwhitelistReferrer(address _referrer) internal ``` *Unwhitelists referrer* ### Parameters | Name | Type | Description | | ---------- | ------- | ------------------- | | \_referrer | address | address of referrer | # StorageUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/storageutils \_Internal library to manage storage slots of GNSMultiCollatDiamond contract diamond storage structs. BE EXTREMELY CAREFUL, DO NOT EDIT THIS WITHOUT A GOOD REASON\_ ## GLOBAL\_ADDRESSES\_SLOT ```solidity theme={null} uint256 GLOBAL_ADDRESSES_SLOT ``` ## GLOBAL\_PAIRS\_STORAGE\_SLOT ```solidity theme={null} uint256 GLOBAL_PAIRS_STORAGE_SLOT ``` ## GLOBAL\_REFERRALS\_SLOT ```solidity theme={null} uint256 GLOBAL_REFERRALS_SLOT ``` ## GLOBAL\_FEE\_TIERS\_SLOT ```solidity theme={null} uint256 GLOBAL_FEE_TIERS_SLOT ``` ## GLOBAL\_PRICE\_IMPACT\_SLOT ```solidity theme={null} uint256 GLOBAL_PRICE_IMPACT_SLOT ``` ## GLOBAL\_DIAMOND\_SLOT ```solidity theme={null} uint256 GLOBAL_DIAMOND_SLOT ``` ## GLOBAL\_TRADING\_STORAGE\_SLOT ```solidity theme={null} uint256 GLOBAL_TRADING_STORAGE_SLOT ``` ## GLOBAL\_TRIGGER\_REWARDS\_SLOT ```solidity theme={null} uint256 GLOBAL_TRIGGER_REWARDS_SLOT ``` ## GLOBAL\_TRADING\_SLOT ```solidity theme={null} uint256 GLOBAL_TRADING_SLOT ``` ## GLOBAL\_TRADING\_CALLBACKS\_SLOT ```solidity theme={null} uint256 GLOBAL_TRADING_CALLBACKS_SLOT ``` ## GLOBAL\_BORROWING\_FEES\_SLOT ```solidity theme={null} uint256 GLOBAL_BORROWING_FEES_SLOT ``` ## GLOBAL\_PRICE\_AGGREGATOR\_SLOT ```solidity theme={null} uint256 GLOBAL_PRICE_AGGREGATOR_SLOT ``` ## GLOBAL\_OTC\_SLOT ```solidity theme={null} uint256 GLOBAL_OTC_SLOT ``` # TradingCallbacksUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/tradingcallbacksutils *GNSTradingCallbacks facet internal library* ## tradingActivated ```solidity theme={null} modifier tradingActivated() ``` *Modifier to only allow trading action when trading is activated (= revert if not activated)* ## tradingActivatedOrCloseOnly ```solidity theme={null} modifier tradingActivatedOrCloseOnly() ``` *Modifier to only allow trading action when trading is activated or close only (= revert if paused)* ## initializeCallbacks ```solidity theme={null} function initializeCallbacks(uint8 _vaultClosingFeeP) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## updateVaultClosingFeeP ```solidity theme={null} function updateVaultClosingFeeP(uint8 _valueP) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## updateTreasuryAddress ```solidity theme={null} function updateTreasuryAddress(address _treasury) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## claimPendingGovFees ```solidity theme={null} function claimPendingGovFees() internal ``` *Check ITradingCallbacksUtils interface for documentation* ## openTradeMarketCallback ```solidity theme={null} function openTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## closeTradeMarketCallback ```solidity theme={null} function closeTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## executeTriggerOpenOrderCallback ```solidity theme={null} function executeTriggerOpenOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## executeTriggerCloseOrderCallback ```solidity theme={null} function executeTriggerCloseOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## updateLeverageCallback ```solidity theme={null} function updateLeverageCallback(struct ITradingCallbacks.AggregatorAnswer _a) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## increasePositionSizeMarketCallback ```solidity theme={null} function increasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## decreasePositionSizeMarketCallback ```solidity theme={null} function decreasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) internal ``` *Check ITradingCallbacksUtils interface for documentation* ## getVaultClosingFeeP ```solidity theme={null} function getVaultClosingFeeP() internal view returns (uint8) ``` *Check ITradingCallbacksUtils interface for documentation* ## getPendingGovFeesCollateral ```solidity theme={null} function getPendingGovFeesCollateral(uint8 _collateralIndex) internal view returns (uint256) ``` *Check ITradingCallbacksUtils interface for documentation* ## validateTriggerOpenOrderCallback ```solidity theme={null} function validateTriggerOpenOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) internal view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v) ``` *Check ITradingCallbacksUtils interface for documentation* ## validateTriggerCloseOrderCallback ```solidity theme={null} function validateTriggerCloseOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) internal view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v) ``` *Check ITradingCallbacksUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct ITradingCallbacks.TradingCallbacksStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## \_registerTrade ```solidity theme={null} function _registerTrade(struct ITradingStorage.Trade _trade, struct ITradingStorage.PendingOrder _pendingOrder) internal returns (struct ITradingStorage.Trade) ``` *Registers a trade in storage, and handles all fees and rewards* ### Parameters | Name | Type | Description | | -------------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | Trade to register | | \_pendingOrder | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | Corresponding pending order | ### Return Values | Name | Type | Description | | ---- | -------------------------------------------------------------------------------------------------------- | ---------------------- | | \[0] | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | Final registered trade | ## \_unregisterTrade ```solidity theme={null} function _unregisterTrade(struct ITradingStorage.Trade _trade, int256 _profitP, enum ITradingStorage.PendingOrderType _orderType, uint256 _oraclePrice, uint256 _liqPrice) internal returns (uint256 tradeValueCollateral) ``` *Unregisters a trade from storage, and handles all fees and rewards* ### Parameters | Name | Type | Description | | ------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | Trade to unregister | | \_profitP | int256 | Profit percentage (1e10) | | \_orderType | enum ITradingStorage.PendingOrderType | pending order type | | \_oraclePrice | uint256 | oracle price without closing spread/impact (1e10) | | \_liqPrice | uint256 | trade liquidation price (1e10) | ### Return Values | Name | Type | Description | | -------------------- | ------- | ---------------------------------------------------------------------------- | | tradeValueCollateral | uint256 | Amount of collateral sent to trader, collateral + pnl (collateral precision) | ## \_openTradePrep ```solidity theme={null} function _openTradePrep(struct ITradingStorage.Trade _trade, uint256 _executionPrice, uint256 _oraclePrice, uint256 _spreadP, uint256 _maxSlippageP) internal view returns (uint256 priceImpactP, uint256 priceAfterImpact, enum ITradingCallbacks.CancelReason cancelReason) ``` *Makes pre-trade checks: price impact, if trade should be cancelled based on parameters like: PnL, leverage, slippage, etc.* ### Parameters | Name | Type | Description | | ---------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------- | | \_trade | [ITradingStorage](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade).Trade | trade input | | \_executionPrice | uint256 | execution price (1e10 precision) | | \_oraclePrice | uint256 | oracle price (1e10 precision) | | \_spreadP | uint256 | spread % (1e10 precision) | | \_maxSlippageP | uint256 | max slippage % (1e3 precision) | ## \_getPendingOrder ```solidity theme={null} function _getPendingOrder(struct ITradingStorage.Id _orderId) internal view returns (struct ITradingStorage.PendingOrder) ``` *Returns pending order from storage* ### Parameters | Name | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | ----------- | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | Order ID | ### Return Values | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------------- | ------------- | | \[0] | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | Pending order | ## \_getCollateralPriceUsd ```solidity theme={null} function _getCollateralPriceUsd(uint8 _collateralIndex) internal view returns (uint256) ``` *Returns collateral price in USD* ### Parameters | Name | Type | Description | | ----------------- | ----- | ---------------- | | \_collateralIndex | uint8 | Collateral index | ### Return Values | Name | Type | Description | | ---- | ------- | ----------------------- | | \[0] | uint256 | Collateral price in USD | ## \_getTrade ```solidity theme={null} function _getTrade(address _trader, uint32 _index) internal view returns (struct ITradingStorage.Trade) ``` *Returns trade from storage* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | Trader address | | \_index | uint32 | Trade index | ### Return Values | Name | Type | Description | | ---- | -------------------------------------------------------------------------------------------------------- | ----------- | | \[0] | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | Trade | ## \_getTradeInfo ```solidity theme={null} function _getTradeInfo(address _trader, uint32 _index) internal view returns (struct ITradingStorage.TradeInfo) ``` *Returns trade info from storage* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | Trader address | | \_index | uint32 | Trade index | ### Return Values | Name | Type | Description | | ---- | ---------------------------------------------------------------------------------------------------------------- | ----------- | | \[0] | [ITradingStorage.TradeInfo](/developer/technical-reference/contracts/interfaces/types/itradingstorage#tradeinfo) | TradeInfo | # TradingCommonUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/tradingcommonutils *External library for helper functions commonly used in many places* ## getPnlPercent ```solidity theme={null} function getPnlPercent(uint64 _openPrice, uint64 _currentPrice, bool _long, uint24 _leverage) public pure returns (int256 p) ``` *Returns the current percent profit of a trade (1e10 precision)* ### Parameters | Name | Type | Description | | -------------- | ------ | ------------------------------------ | | \_openPrice | uint64 | trade open price (1e10 precision) | | \_currentPrice | uint64 | trade current price (1e10 precision) | | \_long | bool | true for long, false for short | | \_leverage | uint24 | trade leverage (1e3 precision) | ## getPositionSizeCollateral ```solidity theme={null} function getPositionSizeCollateral(uint120 _collateralAmount, uint24 _leverage) public pure returns (uint256) ``` *Returns position size of trade in collateral tokens (avoids overflow from uint120 collateralAmount)* ### Parameters | Name | Type | Description | | ------------------ | ------- | ----------------------- | | \_collateralAmount | uint120 | collateral of trade | | \_leverage | uint24 | leverage of trade (1e3) | ## getMarketExecutionPrice ```solidity theme={null} function getMarketExecutionPrice(uint256 _price, uint256 _spreadP, bool _long, bool _open, enum ITradingStorage.ContractsVersion _contractsVersion) public pure returns (uint256) ``` *Calculates market execution price for a trade (1e10 precision)* ### Parameters | Name | Type | Description | | ------------------ | ------------------------------------- | ---------------------------- | | \_price | uint256 | price of the asset (1e10) | | \_spreadP | uint256 | spread percentage (1e10) | | \_long | bool | true if long, false if short | | \_open | bool | | | \_contractsVersion | enum ITradingStorage.ContractsVersion | | ## convertCollateralToUsd ```solidity theme={null} function convertCollateralToUsd(uint256 _collateralAmount, uint128 _collateralPrecisionDelta, uint256 _collateralPriceUsd) public pure returns (uint256) ``` *Converts collateral value to USD (1e18 precision)* ### Parameters | Name | Type | Description | | -------------------------- | ------- | ------------------------------------------------- | | \_collateralAmount | uint256 | amount of collateral (collateral precision) | | \_collateralPrecisionDelta | uint128 | precision delta of collateral (10^18/10^decimals) | | \_collateralPriceUsd | uint256 | price of collateral in USD (1e8) | ## convertCollateralToGns ```solidity theme={null} function convertCollateralToGns(uint256 _collateralAmount, uint128 _collateralPrecisionDelta, uint256 _gnsPriceCollateral) internal pure returns (uint256) ``` *Converts collateral value to GNS (1e18 precision)* ### Parameters | Name | Type | Description | | -------------------------- | ------- | ------------------------------------------------- | | \_collateralAmount | uint256 | amount of collateral (collateral precision) | | \_collateralPrecisionDelta | uint128 | precision delta of collateral (10^18/10^decimals) | | \_gnsPriceCollateral | uint256 | price of GNS in collateral (1e10) | ## getTradeValuePure ```solidity theme={null} function getTradeValuePure(uint256 _collateral, int256 _percentProfit, uint256 _feesCollateral, uint128 _collateralPrecisionDelta) public pure returns (uint256) ``` *Calculates trade value (useful when closing a trade) Important: does not calculate if trade can be liquidated or not, has to be done by calling function* ### Parameters | Name | Type | Description | | -------------------------- | ------- | ----------------------------------------------------------------------- | | \_collateral | uint256 | amount of collateral (collateral precision) | | \_percentProfit | int256 | profit percentage (1e10) | | \_feesCollateral | uint256 | borrowing fee + closing fee in collateral tokens (collateral precision) | | \_collateralPrecisionDelta | uint128 | precision delta of collateral (10^18/10^decimals) | ## getLiqPnlThresholdP ```solidity theme={null} function getLiqPnlThresholdP(struct IPairsStorage.GroupLiquidationParams _params, uint256 _leverage) public pure returns (uint256) ``` *Pure function that returns the liquidation pnl % threshold for a trade (1e10)* ### Parameters | Name | Type | Description | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | | \_params | [IPairsStorage.GroupLiquidationParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | trade liquidation params | | \_leverage | uint256 | trade leverage (1e3 precision) | ## getMinPositionSizeCollateral ```solidity theme={null} function getMinPositionSizeCollateral(uint8 _collateralIndex, uint256 _pairIndex) public view returns (uint256) ``` *Returns minimum position size in collateral tokens for a pair (collateral precision)* ### Parameters | Name | Type | Description | | ----------------- | ------- | ---------------- | | \_collateralIndex | uint8 | collateral index | | \_pairIndex | uint256 | pair index | ## getPositionSizeCollateralBasis ```solidity theme={null} function getPositionSizeCollateralBasis(uint8 _collateralIndex, uint256 _pairIndex, uint256 _positionSizeCollateral) public view returns (uint256) ``` *Returns position size to use when charging fees* ### Parameters | Name | Type | Description | | ------------------------ | ------- | --------------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_pairIndex | uint256 | pair index | | \_positionSizeCollateral | uint256 | trade position size in collateral tokens (collateral precision) | ## isWithinExposureLimits ```solidity theme={null} function isWithinExposureLimits(uint8 _collateralIndex, uint16 _pairIndex, bool _long, uint256 _positionSizeCollateralDelta) external view returns (bool) ``` *Checks if total position size is not higher than maximum allowed open interest for a pair* ### Parameters | Name | Type | Description | | ----------------------------- | ------- | --------------------------------------------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_pairIndex | uint16 | index of pair | | \_long | bool | true if long, false if short | | \_positionSizeCollateralDelta | uint256 | position size delta in collateral tokens (collateral precision) | ## getTradeBorrowingFeeCollateral ```solidity theme={null} function getTradeBorrowingFeeCollateral(struct ITradingStorage.Trade _trade) public view returns (uint256) ``` *Convenient wrapper to return trade borrowing fee in collateral tokens (collateral precision)* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------- | ----------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade input | ## getTradeLiquidationPrice ```solidity theme={null} function getTradeLiquidationPrice(struct ITradingStorage.Trade _trade, bool _useBorrowingFees) public view returns (uint256) ``` *Convenient wrapper to return trade liquidation price (1e10)* ### Parameters | Name | Type | Description | | ------------------ | -------------------------------------------------------------------------------------------------------- | ----------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade input | | \_useBorrowingFees | bool | | ## getTradeValueCollateral ```solidity theme={null} function getTradeValueCollateral(struct ITradingStorage.Trade _trade, int256 _percentProfit, uint256 _closingFeesCollateral, uint128 _collateralPrecisionDelta) public view returns (uint256 valueCollateral, uint256 borrowingFeesCollateral) ``` *Returns trade value and borrowing fee in collateral tokens* ### Parameters | Name | Type | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade data | | \_percentProfit | int256 | profit percentage (1e10) | | \_closingFeesCollateral | uint256 | closing fees in collateral tokens (collateral precision) | | \_collateralPrecisionDelta | uint128 | precision delta of collateral (10^18/10^decimals) | ## getTradeOpeningPriceImpact ```solidity theme={null} function getTradeOpeningPriceImpact(struct ITradingCommonUtils.TradePriceImpactInput _input, enum ITradingStorage.ContractsVersion _contractsVersion) external view returns (uint256 priceImpactP, uint256 priceAfterImpact) ``` *Returns price impact % (1e10), price after spread and impact (1e10)* ### Parameters | Name | Type | Description | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | | \_input | [ITradingCommonUtils.TradePriceImpactInput](/developer/technical-reference/contracts/interfaces/libraries/itradingcommonutils#tradepriceimpactinput) | input data | | \_contractsVersion | enum ITradingStorage.ContractsVersion | contracts version | ## getTradeClosingPriceImpact ```solidity theme={null} function getTradeClosingPriceImpact(struct ITradingCommonUtils.TradePriceImpactInput _input) external view returns (uint256 priceImpactP, uint256 priceAfterImpact, uint256 tradeValueCollateralNoFactor) ``` *Returns price impact % (1e10), price after spread and impact (1e10), and trade value used to know if pnl is positive (collateral precision)* ### Parameters | Name | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | \_input | [ITradingCommonUtils.TradePriceImpactInput](/developer/technical-reference/contracts/interfaces/libraries/itradingcommonutils#tradepriceimpactinput) | input data | ## getTradeLiqPnlThresholdP ```solidity theme={null} function getTradeLiqPnlThresholdP(struct ITradingStorage.Trade _trade) public view returns (uint256) ``` *Returns a trade's liquidation threshold % (1e10)* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------- | ------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | ## getTotalTradeFeesCollateral ```solidity theme={null} function getTotalTradeFeesCollateral(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _positionSizeCollateral) public view returns (uint256) ``` *Returns all fees for a trade in collateral tokens* ### Parameters | Name | Type | Description | | ------------------------ | ------- | --------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_trader | address | address of trader | | \_pairIndex | uint16 | index of pair | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | ## getTradeFeesCollateral ```solidity theme={null} function getTradeFeesCollateral(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _collateralAmount, uint256 _positionSizeCollateral, enum ITradingStorage.PendingOrderType _orderType) public view returns (struct IPairsStorage.TradeFees tradeFees) ``` *Returns all fees for a trade in collateral tokens* ### Parameters | Name | Type | Description | | ------------------------ | ------------------------------------- | --------------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_trader | address | address of trader | | \_pairIndex | uint16 | index of pair | | \_collateralAmount | uint256 | trade collateral amount (collateral precision) | | \_positionSizeCollateral | uint256 | trade position size in collateral tokens (collateral precision) | | \_orderType | enum ITradingStorage.PendingOrderType | corresponding order type | ## getMinGovFeeCollateral ```solidity theme={null} function getMinGovFeeCollateral(uint8 _collateralIndex, address _trader, uint16 _pairIndex) public view returns (uint256) ``` ## revertIfTradeHasPendingMarketOrder ```solidity theme={null} function revertIfTradeHasPendingMarketOrder(address _user, uint32 _index) public view ``` *Reverts if user initiated any kind of pending market order on his trade* ### Parameters | Name | Type | Description | | ------- | ------- | ----------- | | \_user | address | trade user | | \_index | uint32 | trade index | ## getGToken ```solidity theme={null} function getGToken(uint8 _collateralIndex) public view returns (contract IGToken) ``` *Returns gToken contract for a collateral index* ### Parameters | Name | Type | Description | | ----------------- | ----- | ---------------- | | \_collateralIndex | uint8 | collateral index | ## transferCollateralFrom ```solidity theme={null} function transferCollateralFrom(uint8 _collateralIndex, address _from, uint256 _amountCollateral) public ``` *Transfers collateral from trader* ### Parameters | Name | Type | Description | | ------------------ | ------- | ------------------------------------------------------ | | \_collateralIndex | uint8 | index of the collateral | | \_from | address | sending address | | \_amountCollateral | uint256 | amount of collateral to receive (collateral precision) | ## transferCollateralTo ```solidity theme={null} function transferCollateralTo(uint8 _collateralIndex, address _to, uint256 _amountCollateral) internal ``` *Transfers collateral to trader* ### Parameters | Name | Type | Description | | ------------------ | ------- | ------------------------------------------------------- | | \_collateralIndex | uint8 | index of the collateral | | \_to | address | receiving address | | \_amountCollateral | uint256 | amount of collateral to transfer (collateral precision) | ## transferGnsTo ```solidity theme={null} function transferGnsTo(address _to, uint256 _amountGns) internal ``` *Transfers GNS to address* ### Parameters | Name | Type | Description | | ----------- | ------- | -------------------------------- | | \_to | address | receiving address | | \_amountGns | uint256 | amount of GNS to transfer (1e18) | ## transferGnsFrom ```solidity theme={null} function transferGnsFrom(address _from, uint256 _amountGns) internal ``` *Transfers GNS from address* ### Parameters | Name | Type | Description | | ----------- | ------- | ------------------------------- | | \_from | address | sending address | | \_amountGns | uint256 | amount of GNS to receive (1e18) | ## sendCollateralToVault ```solidity theme={null} function sendCollateralToVault(uint8 _collateralIndex, uint256 _amountCollateral, address _trader) public ``` *Sends collateral to gToken vault for negative pnl* ### Parameters | Name | Type | Description | | ------------------ | ------- | ------------------------------------------------------------ | | \_collateralIndex | uint8 | collateral index | | \_amountCollateral | uint256 | amount of collateral to send to vault (collateral precision) | | \_trader | address | trader address | ## handleTradePnl ```solidity theme={null} function handleTradePnl(struct ITradingStorage.Trade _trade, int256 _collateralSentToTrader, int256 _availableCollateralInDiamond, uint256 _borrowingFeeCollateral) external returns (uint256 traderDebt) ``` *Handles pnl transfers when (fully or partially) closing a trade* ### Parameters | Name | Type | Description | | ------------------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_collateralSentToTrader | int256 | total amount to send to trader (collateral precision) | | \_availableCollateralInDiamond | int256 | part of \_collateralSentToTrader available in diamond balance (collateral precision) | | \_borrowingFeeCollateral | uint256 | | ## updateFeeTierPoints ```solidity theme={null} function updateFeeTierPoints(uint8 _collateralIndex, address _trader, uint256 _pairIndex, uint256 _positionSizeCollateral) public ``` *Updates a trader's fee tiers points based on his trade size* ### Parameters | Name | Type | Description | | ------------------------ | ------- | --------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_trader | address | address of trader | | \_pairIndex | uint256 | index of pair | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | ## distributeVaultFeeCollateral ```solidity theme={null} function distributeVaultFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _valueCollateral) public ``` *Distributes fee to gToken vault* ### Parameters | Name | Type | Description | | ----------------- | ------- | ----------------------------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_trader | address | address of trader | | \_valueCollateral | uint256 | fee in collateral tokens (collateral precision) | ## distributeExactGovFeeCollateral ```solidity theme={null} function distributeExactGovFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _govFeeCollateral) public ``` *Distributes gov fees exact amount* ### Parameters | Name | Type | Description | | ------------------ | ------- | --------------------------------------------------------- | | \_collateralIndex | uint8 | index of collateral | | \_trader | address | address of trader | | \_govFeeCollateral | uint256 | position size in collateral tokens (collateral precision) | ## distributeGnsOtcFeeCollateral ```solidity theme={null} function distributeGnsOtcFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _amountCollateral) public ``` *Increases OTC balance to be distributed once OTC is executed* ### Parameters | Name | Type | Description | | ------------------ | ------- | ---------------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_trader | address | trader address | | \_amountCollateral | uint256 | amount of collateral tokens to distribute (collateral precision) | ## distributeTriggerFeeGns ```solidity theme={null} function distributeTriggerFeeGns(address _trader, uint8 _collateralIndex, uint256 _triggerFeeCollateral, uint256 _gnsPriceCollateral, uint128 _collateralPrecisionDelta) public ``` *Distributes trigger fee in GNS tokens* ### Parameters | Name | Type | Description | | -------------------------- | ------- | ------------------------------------------------------- | | \_trader | address | address of trader | | \_collateralIndex | uint8 | index of collateral | | \_triggerFeeCollateral | uint256 | trigger fee in collateral tokens (collateral precision) | | \_gnsPriceCollateral | uint256 | gns/collateral price (1e10 precision) | | \_collateralPrecisionDelta | uint128 | collateral precision delta (10^18/10^decimals) | ## processFees ```solidity theme={null} function processFees(struct ITradingStorage.Trade _trade, uint256 _positionSizeCollateral, enum ITradingStorage.PendingOrderType _orderType) external returns (uint256) ``` *Distributes opening fees for trade and returns the trade fees charged in collateral tokens* ### Parameters | Name | Type | Description | | ------------------------ | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | | \_orderType | enum ITradingStorage.PendingOrderType | trade order type | ## distributeReferralFeeCollateral ```solidity theme={null} function distributeReferralFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _positionSizeCollateral, uint256 _referralFeeCollateral, uint256 _gnsPriceCollateral) public ``` *Distributes referral rewards and returns the amount charged in collateral tokens* ### Parameters | Name | Type | Description | | ------------------------ | ------- | --------------------------------------------------------- | | \_collateralIndex | uint8 | collateral index | | \_trader | address | address of trader | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | | \_referralFeeCollateral | uint256 | referral fee in collateral tokens (collateral precision) | | \_gnsPriceCollateral | uint256 | gns/collateral price (1e10 precision) | ## updateOi ```solidity theme={null} function updateOi(struct ITradingStorage.Trade _trade, uint256 _positionSizeCollateral, bool _open, bool _isPnlPositive) public ``` \_Update protocol open interest (any amount) CAREFUL: this will reset the trade's borrowing fees to 0 when *open = true* ### Parameters | Name | Type | Description | | ------------------------ | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | | \_open | bool | whether it corresponds to a trade opening or closing | | \_isPnlPositive | bool | whether it corresponds to a positive pnl trade (only relevant when \_open = false) | ## updateOiTrade ```solidity theme={null} function updateOiTrade(struct ITradingStorage.Trade _trade, bool _open, bool _isPnlPositive) external ``` \_Update protocol open interest (trade position size) CAREFUL: this will reset the trade's borrowing fees to 0 when *open = true* ### Parameters | Name | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_open | bool | whether it corresponds to a trade opening or closing | | \_isPnlPositive | bool | whether it corresponds to a positive pnl trade (only relevant when \_open = false) | ## handleOiDelta ```solidity theme={null} function handleOiDelta(struct ITradingStorage.Trade _trade, uint256 _newPositionSizeCollateral, bool _isPnlPositive) external ``` *Handles OI delta for an existing trade (for trade updates)* ### Parameters | Name | Type | Description | | --------------------------- | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_newPositionSizeCollateral | uint256 | new position size in collateral tokens (collateral precision) | | \_isPnlPositive | bool | whether it corresponds to a positive pnl trade (only relevant when closing) | ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* # TradingInteractionsUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/tradinginteractionsutils *GNSTradingInteractions facet internal library* ## tradingActivated ```solidity theme={null} modifier tradingActivated() ``` *Modifier to only allow trading action when trading is activated (= revert if not activated)* ## tradingActivatedOrCloseOnly ```solidity theme={null} modifier tradingActivatedOrCloseOnly() ``` *Modifier to only allow trading action when trading is activated or close only (= revert if paused)* ## notDelegatedAction ```solidity theme={null} modifier notDelegatedAction() ``` *Modifier to prevent calling function from delegated action* ## initializeTrading ```solidity theme={null} function initializeTrading(uint16 _marketOrdersTimeoutBlocks, address[] _usersByPassTriggerLink) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## updateMarketOrdersTimeoutBlocks ```solidity theme={null} function updateMarketOrdersTimeoutBlocks(uint16 _valueBlocks) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## updateByPassTriggerLink ```solidity theme={null} function updateByPassTriggerLink(address[] _users, bool[] _shouldByPass) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## setTradingDelegate ```solidity theme={null} function setTradingDelegate(address _delegate) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## removeTradingDelegate ```solidity theme={null} function removeTradingDelegate() internal ``` *Check ITradingInteractionsUtils interface for documentation* ## delegatedTradingAction ```solidity theme={null} function delegatedTradingAction(address _trader, bytes _callData) internal returns (bytes) ``` *Check ITradingInteractionsUtils interface for documentation* ## openTrade ```solidity theme={null} function openTrade(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## openTradeNative ```solidity theme={null} function openTradeNative(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## updateMaxClosingSlippageP ```solidity theme={null} function updateMaxClosingSlippageP(uint32 _index, uint16 _maxClosingSlippageP) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## closeTradeMarket ```solidity theme={null} function closeTradeMarket(uint32 _index, uint64 _expectedPrice) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## updateOpenOrder ```solidity theme={null} function updateOpenOrder(uint32 _index, uint64 _openPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## cancelOpenOrder ```solidity theme={null} function cancelOpenOrder(uint32 _index) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## updateTp ```solidity theme={null} function updateTp(uint32 _index, uint64 _newTp) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## updateSl ```solidity theme={null} function updateSl(uint32 _index, uint64 _newSl) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## updateLeverage ```solidity theme={null} function updateLeverage(uint32 _index, uint24 _newLeverage) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## increasePositionSize ```solidity theme={null} function increasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice, uint16 _maxSlippageP) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## decreasePositionSize ```solidity theme={null} function decreasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## triggerOrder ```solidity theme={null} function triggerOrder(uint256 _packed) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## cancelOrderAfterTimeout ```solidity theme={null} function cancelOrderAfterTimeout(uint32 _orderIndex) internal ``` *Check ITradingInteractionsUtils interface for documentation* ## getWrappedNativeToken ```solidity theme={null} function getWrappedNativeToken() internal view returns (address) ``` *Check ITradingInteractionsUtils interface for documentation* ## isWrappedNativeToken ```solidity theme={null} function isWrappedNativeToken(address _token) internal view returns (bool) ``` *Check ITradingInteractionsUtils interface for documentation* ## getTradingDelegate ```solidity theme={null} function getTradingDelegate(address _trader) internal view returns (address) ``` *Check ITradingInteractionsUtils interface for documentation* ## getMarketOrdersTimeoutBlocks ```solidity theme={null} function getMarketOrdersTimeoutBlocks() internal view returns (uint16) ``` *Check ITradingInteractionsUtils interface for documentation* ## getByPassTriggerLink ```solidity theme={null} function getByPassTriggerLink(address _user) internal view returns (bool) ``` *Check ITradingInteractionsUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct ITradingInteractions.TradingInteractionsStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## \_openTrade ```solidity theme={null} function _openTrade(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer, bool _isNative) internal ``` *Internal function for openTrade and openTradeNative* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade data | | \_maxSlippageP | uint16 | max slippage percentage (1e3 precision) | | \_referrer | address | referrer address | | \_isNative | bool | if true we skip the collateral transfer from user to contract | ## \_checkNoPendingTrigger ```solidity theme={null} function _checkNoPendingTrigger(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType) internal view ``` *Revert if there is an active pending order for the trade* ### Parameters | Name | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------- | ----------- | | \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | trade id | | \_orderType | enum ITradingStorage.PendingOrderType | order type | ## \_getPriceTriggerOrder ```solidity theme={null} function _getPriceTriggerOrder(struct ITradingStorage.Trade _trade, struct ITradingStorage.Id _orderId, enum ITradingStorage.PendingOrderType _orderType, uint256 _positionSizeCollateral) internal ``` *Initiate price aggregator request for trigger order* ### Parameters | Name | Type | Description | | ------------------------ | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade | | \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | order id | | \_orderType | enum ITradingStorage.PendingOrderType | order type | | \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) | ## \_wrapNativeToken ```solidity theme={null} function _wrapNativeToken(uint8 _collateralIndex) internal returns (uint120) ``` *Receives native token and sends back wrapped token to user* ### Parameters | Name | Type | Description | | ----------------- | ----- | ----------------------- | | \_collateralIndex | uint8 | index of the collateral | ## \_msgSender ```solidity theme={null} function _msgSender() internal view returns (address) ``` *Returns the caller of the transaction (overriden by trader address if delegatedAction is called)* # TradingStorageUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/tradingstorageutils *GNSTradingStorage facet external library* ## initializeTradingStorage ```solidity theme={null} function initializeTradingStorage(address _gns, address _gnsStaking, address[] _collaterals, address[] _gTokens) external ``` *Check ITradingStorageUtils interface for documentation* ## updateTradingActivated ```solidity theme={null} function updateTradingActivated(enum ITradingStorage.TradingActivated _activated) public ``` *Check ITradingStorageUtils interface for documentation* ## addCollateral ```solidity theme={null} function addCollateral(address _collateral, address _gToken) public ``` *Check ITradingStorageUtils interface for documentation* ## toggleCollateralActiveState ```solidity theme={null} function toggleCollateralActiveState(uint8 _collateralIndex) external ``` *Check ITradingStorageUtils interface for documentation* ## updateGToken ```solidity theme={null} function updateGToken(address _collateral, address _gToken) external ``` *Check ITradingStorageUtils interface for documentation* ## storeTrade ```solidity theme={null} function storeTrade(struct ITradingStorage.Trade _trade, struct ITradingStorage.TradeInfo _tradeInfo) external returns (struct ITradingStorage.Trade) ``` *Check ITradingStorageUtils interface for documentation* ## updateTradeMaxClosingSlippageP ```solidity theme={null} function updateTradeMaxClosingSlippageP(struct ITradingStorage.Id _tradeId, uint16 _maxClosingSlippageP) external ``` ## updateTradeCollateralAmount ```solidity theme={null} function updateTradeCollateralAmount(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount) external ``` *Check ITradingStorageUtils interface for documentation* ## updateTradePosition ```solidity theme={null} function updateTradePosition(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount, uint24 _leverage, uint64 _openPrice, bool _isPartialIncrease, bool _isPnlPositive) external ``` *Check ITradingStorageUtils interface for documentation* ## updateOpenOrderDetails ```solidity theme={null} function updateOpenOrderDetails(struct ITradingStorage.Id _tradeId, uint64 _openPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external ``` *Check ITradingStorageUtils interface for documentation* ## updateTradeTp ```solidity theme={null} function updateTradeTp(struct ITradingStorage.Id _tradeId, uint64 _newTp) external ``` *Check ITradingStorageUtils interface for documentation* ## updateTradeSl ```solidity theme={null} function updateTradeSl(struct ITradingStorage.Id _tradeId, uint64 _newSl) external ``` *Check ITradingStorageUtils interface for documentation* ## closeTrade ```solidity theme={null} function closeTrade(struct ITradingStorage.Id _tradeId, bool _isPnlPositive) external ``` *Check ITradingStorageUtils interface for documentation* ## storePendingOrder ```solidity theme={null} function storePendingOrder(struct ITradingStorage.PendingOrder _pendingOrder) external returns (struct ITradingStorage.PendingOrder) ``` *Check ITradingStorageUtils interface for documentation* ## closePendingOrder ```solidity theme={null} function closePendingOrder(struct ITradingStorage.Id _orderId) external ``` *Check ITradingStorageUtils interface for documentation* ## getCollateral ```solidity theme={null} function getCollateral(uint8 _index) external view returns (struct ITradingStorage.Collateral) ``` *Check ITradingStorageUtils interface for documentation* ## isCollateralActive ```solidity theme={null} function isCollateralActive(uint8 _index) public view returns (bool) ``` *Check ITradingStorageUtils interface for documentation* ## isCollateralListed ```solidity theme={null} function isCollateralListed(uint8 _index) external view returns (bool) ``` *Check ITradingStorageUtils interface for documentation* ## getCollateralsCount ```solidity theme={null} function getCollateralsCount() external view returns (uint8) ``` *Check ITradingStorageUtils interface for documentation* ## getCollaterals ```solidity theme={null} function getCollaterals() external view returns (struct ITradingStorage.Collateral[]) ``` *Check ITradingStorageUtils interface for documentation* ## getCollateralIndex ```solidity theme={null} function getCollateralIndex(address _collateral) external view returns (uint8) ``` *Check ITradingStorageUtils interface for documentation* ## getTradingActivated ```solidity theme={null} function getTradingActivated() external view returns (enum ITradingStorage.TradingActivated) ``` *Check ITradingStorageUtils interface for documentation* ## getTraderStored ```solidity theme={null} function getTraderStored(address _trader) external view returns (bool) ``` *Check ITradingStorageUtils interface for documentation* ## getTrade ```solidity theme={null} function getTrade(address _trader, uint32 _index) external view returns (struct ITradingStorage.Trade) ``` *Check ITradingStorageUtils interface for documentation* ## getTradeInfo ```solidity theme={null} function getTradeInfo(address _trader, uint32 _index) external view returns (struct ITradingStorage.TradeInfo) ``` *Check ITradingStorageUtils interface for documentation* ## getPendingOrder ```solidity theme={null} function getPendingOrder(struct ITradingStorage.Id _orderId) external view returns (struct ITradingStorage.PendingOrder) ``` *Check ITradingStorageUtils interface for documentation* ## getTradePendingOrderBlock ```solidity theme={null} function getTradePendingOrderBlock(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType) external view returns (uint256) ``` *Check ITradingStorageUtils interface for documentation* ## getCounters ```solidity theme={null} function getCounters(address _trader, enum ITradingStorage.CounterType _type) external view returns (struct ITradingStorage.Counter) ``` *Check ITradingStorageUtils interface for documentation* ## getGToken ```solidity theme={null} function getGToken(uint8 _collateralIndex) external view returns (address) ``` *Check ITradingStorageUtils interface for documentation* ## getTradeLiquidationParams ```solidity theme={null} function getTradeLiquidationParams(address _trader, uint32 _index) external view returns (struct IPairsStorage.GroupLiquidationParams) ``` *Check ITradingStorageUtils interface for documentation* ## getCurrentContractsVersion ```solidity theme={null} function getCurrentContractsVersion() external pure returns (enum ITradingStorage.ContractsVersion) ``` *Check ITradingStorageUtils interface for documentation* ## getTradersCount ```solidity theme={null} function getTradersCount() external view returns (uint256) ``` *Check ITradingStorageUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct ITradingStorage.TradingStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## \_limitTpDistance ```solidity theme={null} function _limitTpDistance(uint64 _openPrice, uint24 _leverage, uint64 _tp, bool _long) public pure returns (uint64) ``` \_Limits take profit price distance for long/short based on '\_openPrice', '\_tp, '\_leverage' and sets an automatic TP if '*tp' is zero.* ### Parameters | Name | Type | Description | | ----------- | ------ | ---------------------------------------- | | \_openPrice | uint64 | trade open price (1e10 precision) | | \_leverage | uint24 | trade leverage (1e3 precision) | | \_tp | uint64 | trade take profit price (1e10 precision) | | \_long | bool | trade direction | ## \_limitSlDistance ```solidity theme={null} function _limitSlDistance(uint64 _openPrice, uint24 _leverage, uint64 _sl, bool _long, uint256 _liqPnlThresholdP) public pure returns (uint64) ``` \_Limits stop loss price distance for long/short based on '\_openPrice', '\_sl, '*leverage'.* ### Parameters | Name | Type | Description | | ------------------ | ------- | ------------------------------------------- | | \_openPrice | uint64 | trade open price (1e10 precision) | | \_leverage | uint24 | trade leverage (1e3 precision) | | \_sl | uint64 | trade stop loss price (1e10 precision) | | \_long | bool | trade direction | | \_liqPnlThresholdP | uint256 | liquidation pnl threshold percentage (1e10) | ## \_limitTradeSlDistance ```solidity theme={null} function _limitTradeSlDistance(struct ITradingStorage.Trade _trade, uint64 _newSl) public view returns (uint64) ``` *Limits trade stop loss price distance* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------- | ------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_newSl | uint64 | | ## \_validateTrade ```solidity theme={null} function _validateTrade(struct ITradingStorage.Trade _trade) internal view ``` *Validation for trade struct (used by storeTrade and storePendingOrder for market open orders)* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------- | ------------------------ | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct to validate | # TriggerRewardsUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/triggerrewardsutils *GNSTriggerRewards facet internal library* ## initializeTriggerRewards ```solidity theme={null} function initializeTriggerRewards(uint16 _timeoutBlocks) internal ``` *Check ITriggerRewardsUtils interface for documentation* ## updateTriggerTimeoutBlocks ```solidity theme={null} function updateTriggerTimeoutBlocks(uint16 _timeoutBlocks) internal ``` *Check ITriggerRewardsUtils interface for documentation* ## distributeTriggerReward ```solidity theme={null} function distributeTriggerReward(uint256 _rewardGns) internal ``` *Check ITriggerRewardsUtils interface for documentation* ## claimPendingTriggerRewards ```solidity theme={null} function claimPendingTriggerRewards(address _oracle) internal ``` *Check ITriggerRewardsUtils interface for documentation* ## getTriggerTimeoutBlocks ```solidity theme={null} function getTriggerTimeoutBlocks() internal view returns (uint16) ``` *Check ITriggerRewardsUtils interface for documentation* ## hasActiveOrder ```solidity theme={null} function hasActiveOrder(uint256 _orderBlock, uint256 _currentBlock) internal view returns (bool) ``` *Check ITriggerRewardsUtils interface for documentation* ## getTriggerPendingRewardsGns ```solidity theme={null} function getTriggerPendingRewardsGns(address _oracle) internal view returns (uint256) ``` *Check ITriggerRewardsUtils interface for documentation* ## \_getSlot ```solidity theme={null} function _getSlot() internal pure returns (uint256) ``` *Returns storage slot to use when fetching storage relevant to library* ## \_getStorage ```solidity theme={null} function _getStorage() internal pure returns (struct ITriggerRewards.TriggerRewardsStorage s) ``` *Returns storage pointer for storage struct in diamond contract, at defined slot* ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* # UpdateLeverageLifecycles Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/updateleverage/updateleveragelifecycles *This is an external library for leverage update lifecycles Used by GNSTrading and GNSTradingCallbacks facets* ## requestUpdateLeverage ```solidity theme={null} function requestUpdateLeverage(struct IUpdateLeverage.UpdateLeverageInput _input) external ``` *Initiate update leverage order, done in 2 steps because need to cancel if liquidation price reached* ### Parameters | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | | \_input | [IUpdateLeverage.UpdateLeverageInput](/developer/technical-reference/contracts/interfaces/types/iupdateleverage#updateleverageinput) | request decrease leverage input | ## executeUpdateLeverage ```solidity theme={null} function executeUpdateLeverage(struct ITradingStorage.PendingOrder _order, struct ITradingCallbacks.AggregatorAnswer _answer) external ``` *Execute update leverage callback* ### Parameters | Name | Type | Description | | -------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | | \_order | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | pending order struct | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | price aggregator request answer | ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## \_getNewCollateralAmount ```solidity theme={null} function _getNewCollateralAmount(uint256 _existingCollateralAmount, uint256 _existingLeverage, uint256 _newLeverage) internal pure returns (uint120) ``` *Returns new trade collateral amount based on new leverage (collateral precision)* ### Parameters | Name | Type | Description | | -------------------------- | ------- | ------------------------------------------------------- | | \_existingCollateralAmount | uint256 | existing trade collateral amount (collateral precision) | | \_existingLeverage | uint256 | existing trade leverage (1e3) | | \_newLeverage | uint256 | new trade leverage (1e3) | ## \_validateRequest ```solidity theme={null} function _validateRequest(struct IUpdateLeverage.UpdateLeverageInput _input) internal view returns (struct ITradingStorage.Trade trade, bool isIncrease, uint256 collateralDelta) ``` *Fetches trade, does validation for update leverage request, and returns useful data* ### Parameters | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | | \_input | [IUpdateLeverage.UpdateLeverageInput](/developer/technical-reference/contracts/interfaces/types/iupdateleverage#updateleverageinput) | request input struct | ## \_initiateRequest ```solidity theme={null} function _initiateRequest(struct ITradingStorage.Trade _trade, uint24 _newLeverage, uint256 _collateralDelta) internal returns (struct ITradingStorage.Id orderId) ``` *Stores pending update leverage order and makes price aggregator request* ### Parameters | Name | Type | Description | | ----------------- | -------------------------------------------------------------------------------------------------------- | --------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_newLeverage | uint24 | new leverage (1e3) | | \_collateralDelta | uint256 | trade collateral delta (collateral precision) | ## \_prepareCallbackValues ```solidity theme={null} function _prepareCallbackValues(struct ITradingStorage.Trade _existingTrade, struct ITradingStorage.Trade _pendingTrade, bool _isIncrease) internal view returns (struct IUpdateLeverage.UpdateLeverageValues values) ``` *Calculates values for callback* ### Parameters | Name | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade struct | | \_pendingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | pending trade struct | | \_isIncrease | bool | true if increase leverage, false if decrease leverage | ## \_validateCallback ```solidity theme={null} function _validateCallback(struct ITradingStorage.Trade _existingTrade, struct IUpdateLeverage.UpdateLeverageValues _values, struct ITradingCallbacks.AggregatorAnswer _answer) internal view returns (enum ITradingCallbacks.CancelReason) ``` *Validates callback, and returns corresponding cancel reason* ### Parameters | Name | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade struct | | \_values | [IUpdateLeverage.UpdateLeverageValues](/developer/technical-reference/contracts/interfaces/types/iupdateleverage#updateleveragevalues) | pre-calculated useful values | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | price aggregator answer | ## \_handleCallback ```solidity theme={null} function _handleCallback(struct ITradingStorage.Trade _trade, struct ITradingStorage.Trade _pendingTrade, struct IUpdateLeverage.UpdateLeverageValues _values, enum ITradingCallbacks.CancelReason _cancelReason, bool _isIncrease) internal ``` *Handles trade update, removes gov fee OI, and transfers collateral delta (for both successful and failed requests)* ### Parameters | Name | Type | Description | | -------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_pendingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | pending trade struct | | \_values | [IUpdateLeverage.UpdateLeverageValues](/developer/technical-reference/contracts/interfaces/types/iupdateleverage#updateleveragevalues) | pre-calculated useful values | | \_cancelReason | enum ITradingCallbacks.CancelReason | cancel reason | | \_isIncrease | bool | true if increase leverage, false if decrease leverage | # DecreasePositionSizeUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/updatepositionsize/decreasepositionsizeutils *This is an internal utils library for position size decreases Used by UpdatePositionSizeLifecycles internal library* ## validateRequest ```solidity theme={null} function validateRequest(struct ITradingStorage.Trade _trade, struct IUpdatePositionSize.DecreasePositionSizeInput _input) internal view returns (uint256 positionSizeCollateralDelta) ``` \_Validates decrease position size request Possible inputs: collateral delta > 0 and leverage delta = 0 (decrease collateral by collateral delta) collateral delta = 0 and leverage delta > 0 (decrease leverage by leverage delta) @param \_trade trade of request @param *input input values* ## prepareCallbackValues ```solidity theme={null} function prepareCallbackValues(struct ITradingStorage.Trade _existingTrade, struct ITradingStorage.Trade _partialTrade, struct ITradingCallbacks.AggregatorAnswer _answer) internal view returns (struct IUpdatePositionSize.DecreasePositionSizeValues values) ``` *Calculates values for callback* ### Parameters | Name | Type | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade data | | \_partialTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | partial trade data | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | price aggregator answer | ## validateCallback ```solidity theme={null} function validateCallback(struct ITradingStorage.Trade _existingTrade, struct ITradingStorage.PendingOrder _pendingOrder, struct IUpdatePositionSize.DecreasePositionSizeValues _values, struct ITradingCallbacks.AggregatorAnswer _answer) internal view returns (enum ITradingCallbacks.CancelReason) ``` *Validates callback, and returns corresponding cancel reason* ### Parameters | Name | Type | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | | | \_pendingOrder | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | | | \_values | [IUpdatePositionSize.DecreasePositionSizeValues](/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize#decreasepositionsizevalues) | pre-calculated useful values | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | | ## updateTradeSuccess ```solidity theme={null} function updateTradeSuccess(struct ITradingStorage.Trade _existingTrade, struct IUpdatePositionSize.DecreasePositionSizeValues _values) internal ``` *Updates trade (for successful request)* ### Parameters | Name | Type | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade data | | \_values | [IUpdatePositionSize.DecreasePositionSizeValues](/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize#decreasepositionsizevalues) | pre-calculated useful values | ## handleCanceled ```solidity theme={null} function handleCanceled(struct ITradingStorage.Trade _existingTrade, enum ITradingCallbacks.CancelReason _cancelReason) internal ``` *Handles callback canceled case (for failed request)* ### Parameters | Name | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------------- | --------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade to update | | \_cancelReason | enum ITradingCallbacks.CancelReason | cancel reason | ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* # IncreasePositionSizeUtils Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/updatepositionsize/increasepositionsizeutils *This is an internal utils library for position size increases Used by UpdatePositionSizeLifecycles internal library* ## validateRequest ```solidity theme={null} function validateRequest(struct ITradingStorage.Trade _trade, struct IUpdatePositionSize.IncreasePositionSizeInput _input) internal view returns (uint256 positionSizeCollateralDelta) ``` \_Validates increase position request. Possible inputs: collateral delta > 0 and leverage delta > 0 (increase position size by collateral delta \* leverage delta) collateral delta = 0 and leverage delta > 0 (increase trade leverage by leverage delta)\_ ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade of request | | \_input | [IUpdatePositionSize.IncreasePositionSizeInput](/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize#increasepositionsizeinput) | input values | ## prepareCallbackValues ```solidity theme={null} function prepareCallbackValues(struct ITradingStorage.Trade _existingTrade, struct ITradingStorage.Trade _partialTrade, struct ITradingCallbacks.AggregatorAnswer _answer) internal view returns (struct IUpdatePositionSize.IncreasePositionSizeValues values) ``` *Calculates values for callback* ### Parameters | Name | Type | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade data | | \_partialTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | partial trade data | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | price aggregator answer | ## validateCallback ```solidity theme={null} function validateCallback(struct ITradingStorage.Trade _existingTrade, struct IUpdatePositionSize.IncreasePositionSizeValues _values, struct ITradingCallbacks.AggregatorAnswer _answer, uint256 _expectedPrice, uint256 _maxSlippageP) internal view returns (enum ITradingCallbacks.CancelReason cancelReason) ``` *Validates callback, and returns corresponding cancel reason* ### Parameters | Name | Type | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade data | | \_values | [IUpdatePositionSize.IncreasePositionSizeValues](/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize#increasepositionsizevalues) | pre-calculated useful values | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | | | \_expectedPrice | uint256 | user expected price before callback (1e10) | | \_maxSlippageP | uint256 | maximum slippage percentage from expected price (1e3) | ## updateTradeSuccess ```solidity theme={null} function updateTradeSuccess(struct ITradingStorage.Trade _existingTrade, struct IUpdatePositionSize.IncreasePositionSizeValues _values) internal ``` *Updates trade (for successful request)* ### Parameters | Name | Type | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade data | | \_values | [IUpdatePositionSize.IncreasePositionSizeValues](/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize#increasepositionsizevalues) | pre-calculated useful values | ## handleCanceled ```solidity theme={null} function handleCanceled(struct ITradingStorage.Trade _existingTrade, struct ITradingStorage.Trade _partialTrade, enum ITradingCallbacks.CancelReason _cancelReason) internal ``` *Handles callback canceled case (for failed request)* ### Parameters | Name | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------------- | ------------------- | | \_existingTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | existing trade data | | \_partialTrade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | partial trade data | | \_cancelReason | enum ITradingCallbacks.CancelReason | cancel reason | ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* # UpdatePositionSizeLifecycles Source: https://docs.gains.trade/developer/technical-reference/contracts/libraries/updatepositionsize/updatepositionsizelifecycles *This is an external library for position size updates lifecycles Used by GNSTrading and GNSTradingCallbacks facets* ## requestIncreasePositionSize ```solidity theme={null} function requestIncreasePositionSize(struct IUpdatePositionSize.IncreasePositionSizeInput _input) external ``` *Initiate increase position size order, done in 2 steps because position size changes* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | \_input | [IUpdatePositionSize.IncreasePositionSizeInput](/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize#increasepositionsizeinput) | request increase position size input struct | ## requestDecreasePositionSize ```solidity theme={null} function requestDecreasePositionSize(struct IUpdatePositionSize.DecreasePositionSizeInput _input) external ``` *Initiate decrease position size order, done in 2 steps because position size changes* ### Parameters | Name | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | \_input | [IUpdatePositionSize.DecreasePositionSizeInput](/developer/technical-reference/contracts/interfaces/types/iupdatepositionsize#decreasepositionsizeinput) | request decrease position size input struct | ## executeIncreasePositionSizeMarket ```solidity theme={null} function executeIncreasePositionSizeMarket(struct ITradingStorage.PendingOrder _order, struct ITradingCallbacks.AggregatorAnswer _answer) external ``` *Execute increase position size market callback* ### Parameters | Name | Type | Description | | -------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | | \_order | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | corresponding pending order | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | price aggregator answer | ## executeDecreasePositionSizeMarket ```solidity theme={null} function executeDecreasePositionSizeMarket(struct ITradingStorage.PendingOrder _order, struct ITradingCallbacks.AggregatorAnswer _answer) external ``` *Execute decrease position size market callback* ### Parameters | Name | Type | Description | | -------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | | \_order | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | corresponding pending order | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | price aggregator answer | ## \_getMultiCollatDiamond ```solidity theme={null} function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond) ``` *Returns current address as multi-collateral diamond interface to call other facets functions.* ## \_baseValidateRequest ```solidity theme={null} function _baseValidateRequest(address _trader, uint32 _index) internal view returns (struct ITradingStorage.Trade trade) ``` *Basic validation for increase/decrease position size request* ### Parameters | Name | Type | Description | | -------- | ------- | -------------- | | \_trader | address | trader address | | \_index | uint32 | trade index | ## \_initiateRequest ```solidity theme={null} function _initiateRequest(struct ITradingStorage.Trade _trade, bool _isIncrease, uint120 _collateralAmount, uint24 _leverage, uint256 _positionSizeCollateralDelta, uint64 _expectedPrice, uint16 _maxSlippageP) internal returns (struct ITradingStorage.Id orderId) ``` *Creates pending order, makes price aggregator request, and returns corresponding pending order id* ### Parameters | Name | Type | Description | | ----------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade to update | | \_isIncrease | bool | whether is increase or decrease position size order | | \_collateralAmount | uint120 | partial trade collateral amount (collateral precision) | | \_leverage | uint24 | partial trade leverage (1e3) | | \_positionSizeCollateralDelta | uint256 | position size delta in collateral tokens (collateral precision) | | \_expectedPrice | uint64 | reference price for max slippage check (1e10), only useful for increase position size | | \_maxSlippageP | uint16 | max slippage % (1e3), only useful for increase position size | ## \_validateBaseFulfillment ```solidity theme={null} function _validateBaseFulfillment(struct ITradingStorage.Trade _trade, struct ITradingCallbacks.AggregatorAnswer _answer) internal pure returns (enum ITradingCallbacks.CancelReason) ``` *Basic validation for callbacks, returns corresponding cancel reason* ### Parameters | Name | Type | Description | | -------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | | \_trade | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | trade struct | | \_answer | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | price aggegator answer | # EpochBasedTokenClaim Source: https://docs.gains.trade/developer/technical-reference/contracts/misc/epochbasedtokenclaim *Contract to claim rewards based on epoch and merkle tree (used for Arbitrum STIP trading incentives)* ## rewardToken ```solidity theme={null} contract IERC20 rewardToken ``` ## manager ```solidity theme={null} address manager ``` ## epochRoots ```solidity theme={null} mapping(uint256 => bytes32) epochRoots ``` ## epochCids ```solidity theme={null} mapping(uint256 => string) epochCids ``` ## epochTraderClaimed ```solidity theme={null} mapping(uint256 => mapping(address => bool)) epochTraderClaimed ``` ## ManagerUpdated ```solidity theme={null} event ManagerUpdated(address newManager) ``` ## TokensWithdrawn ```solidity theme={null} event TokensWithdrawn() ``` ## EpochMerkleRootSet ```solidity theme={null} event EpochMerkleRootSet(uint256 epoch, bytes32 root, uint256 totalRewards, string cid) ``` ## TokensClaimed ```solidity theme={null} event TokensClaimed(uint256 epoch, address user, uint256 rewardAmount) ``` ## TokensClaimed ```solidity theme={null} event TokensClaimed(uint256[] epochs, address user, uint256 rewardAmount) ``` ## AddressZero ```solidity theme={null} error AddressZero() ``` ## NotManager ```solidity theme={null} error NotManager() ``` ## RootAlreadySet ```solidity theme={null} error RootAlreadySet() ``` ## RootZero ```solidity theme={null} error RootZero() ``` ## RewardsZero ```solidity theme={null} error RewardsZero() ``` ## CidZero ```solidity theme={null} error CidZero() ``` ## InvalidEpochs ```solidity theme={null} error InvalidEpochs() ``` ## ArrayLengthMismatch ```solidity theme={null} error ArrayLengthMismatch() ``` ## EpochNotSet ```solidity theme={null} error EpochNotSet() ``` ## NotEnoughBalance ```solidity theme={null} error NotEnoughBalance() ``` ## AlreadyClaimed ```solidity theme={null} error AlreadyClaimed() ``` ## InvalidProof ```solidity theme={null} error InvalidProof() ``` ## constructor ```solidity theme={null} constructor(contract IERC20 _rewardToken, address _owner, address _manager) public ``` ## onlyManager ```solidity theme={null} modifier onlyManager() ``` ## setManager ```solidity theme={null} function setManager(address _manager) external ``` *Sets manager address to `_manager`. Only callable by `owner()` (multisig)* ## setRoot ```solidity theme={null} function setRoot(uint256 _epoch, bytes32 _root, uint256 _totalRewards, string _cid) external ``` \_Sets Merkle Tree `_root` and '*cid' for an `_epoch` and transfers `_totalRewards` from the `owner()` (multisig) to this contract. Only callable by `manager`.* ## withdrawTokens ```solidity theme={null} function withdrawTokens() external ``` *Prevents stuck tokens in case of misconfiguration; Only `owner()` (multisig) can claim the tokens back* ## claimRewards ```solidity theme={null} function claimRewards(uint256 _epoch, uint256 _rewardAmount, bytes32[] _proof) external ``` *Claims trader rewards for a specific `_epoch`* ## claimMultipleRewards ```solidity theme={null} function claimMultipleRewards(uint256[] _epochs, uint256[] _rewardAmounts, bytes32[][] _proofs) external ``` *Claims trader rewards for multiple `_epochs`* ## \_hashLeaf ```solidity theme={null} function _hashLeaf(address _user, uint256 _amount) internal pure returns (bytes32) ``` *Returns a hashed leaf of `_user` + `_amount`* ## \_validateClaim ```solidity theme={null} function _validateClaim(uint256 _epoch, address _trader, uint256 _rewardAmount, bytes32[] _proof) internal view ``` \_Validates that: 1. The `_epoch` merkle tree root is set 2. There are enough token rewards in the contract 3. Rewards for leaf are unclaimed 4. The `leaf` and `_proof` validate against `epochRoot`\_ # GNSCompensationHandler Source: https://docs.gains.trade/developer/technical-reference/contracts/misc/gnscompensationhandler *Compensation contract that gives GNS to dev fund renouncing dai revenue and allows users to redeem NFTs that are now deprecated for GNS* ## gns ```solidity theme={null} contract IERC20 gns ``` ## staking ```solidity theme={null} contract IGNSStaking staking ``` ## nfts ```solidity theme={null} contract IERC721[5] nfts ``` ## devFundUnlockScheduled ```solidity theme={null} bool devFundUnlockScheduled ``` ## ClaimInput ```solidity theme={null} struct ClaimInput { uint256 nftType; uint256[] ids; } ``` ## NftsConverted ```solidity theme={null} event NftsConverted(address user, struct GNSCompensationHandler.ClaimInput[] input, uint256 claimAmount, uint256 penaltyAmount, bool locked) ``` ## DevFundUnlockScheduled ```solidity theme={null} event DevFundUnlockScheduled() ``` ## constructor ```solidity theme={null} constructor(contract IERC20 _gns, contract IGNSStaking _staking, contract IERC721[5] _nfts) public ``` ## retireNfts ```solidity theme={null} function retireNfts(struct GNSCompensationHandler.ClaimInput[] _inputArr, bool _lock) external ``` ## scheduleDevFundUnlock ```solidity theme={null} function scheduleDevFundUnlock() external ``` # GTokenLockedDepositNftDesign Source: https://docs.gains.trade/developer/technical-reference/contracts/misc/gtokenlockeddepositnftdesign *Design contract for GTokenLockedDepositNft, useful for OpenSea and other NFT marketplaces* ## buildTokenURI ```solidity theme={null} function buildTokenURI(uint256 tokenId, struct IGToken.LockedDeposit lockedDeposit, string gTokenSymbol, string assetSymbol, uint8 numberInputDecimals, uint8 numberOutputDecimals) external pure returns (string) ``` ## numberToRoundedString ```solidity theme={null} function numberToRoundedString(uint256 number, uint8 inputDecimals, uint8 outputDecimals) public pure returns (string) ``` # GTokenRateProvider Source: https://docs.gains.trade/developer/technical-reference/contracts/misc/gtokenrateprovider *Balancer rate provider to return the value of a gToken in terms of its collaterals token* ## gToken ```solidity theme={null} contract IGToken gToken ``` ## constructor ```solidity theme={null} constructor(contract IGToken _gToken) public ``` ## getRate ```solidity theme={null} function getRate() external view returns (uint256) ``` *Fetches the price rate of a gToken* ### Return Values | Name | Type | Description | | ---- | ------- | ---------------------------------------------------------- | | \[0] | uint256 | the value of gToken in collateral token, in 1e18 precision | # ManagerTimelock Source: https://docs.gains.trade/developer/technical-reference/contracts/misc/managertimelock *3-day timelock* ## constructor ```solidity theme={null} constructor(uint256 minDelay, address[] proposers, address[] executors, address admin) public ``` # OwnerTimelock Source: https://docs.gains.trade/developer/technical-reference/contracts/misc/ownertimelock *2-week timelock* ## constructor ```solidity theme={null} constructor(uint256 minDelay, address[] proposers, address[] executors, address admin) public ``` # VotingDelegator Source: https://docs.gains.trade/developer/technical-reference/contracts/misc/votingdelegator *Abstract contract that handles delegating governance votes of an asset when possible. Compatible with any token that extends OpenZeppelin ERC20Votes/ERC20VotesUpgradeable or implements `delegate(address)`* ## Delegated ```solidity theme={null} event Delegated(address asset, address delegatee, bool success) ``` ## \_tryDelegate ```solidity theme={null} function _tryDelegate(address _asset, address _delegatee) internal ``` \_Calls `delegate(address)` on `_asset`. Does not revert if function is not supported by `_asset`. Emits \{Delegated} with `_asset`, `_delegatee` and `success` flag\_ # GainsNetworkToken Source: https://docs.gains.trade/developer/technical-reference/contracts/tokens/gainsnetworktoken *GNS token contract, simple ERC20 token with access control and minting/burning* ## MINTER\_ROLE ```solidity theme={null} bytes32 MINTER_ROLE ``` ## BURNER\_ROLE ```solidity theme={null} bytes32 BURNER_ROLE ``` ## initialized ```solidity theme={null} bool initialized ``` ## constructor ```solidity theme={null} constructor(address admin) public ``` ## setupRoles ```solidity theme={null} function setupRoles(address diamond, address vault, address compensationHandler) external ``` ## mint ```solidity theme={null} function mint(address to, uint256 amount) external ``` ## burn ```solidity theme={null} function burn(address from, uint256 amount) external ``` # GTokenLockedDepositNft Source: https://docs.gains.trade/developer/technical-reference/contracts/tokens/gtokenlockeddepositnft *Receipt NFT for a gToken locked deposits* ## gToken ```solidity theme={null} address gToken ``` ## design ```solidity theme={null} contract IGTokenLockedDepositNftDesign design ``` ## designDecimals ```solidity theme={null} uint8 designDecimals ``` ## constructor ```solidity theme={null} constructor(string name, string symbol, address _gToken, contract IGTokenLockedDepositNftDesign _design, uint8 _designDecimals) public ``` ## onlyGToken ```solidity theme={null} modifier onlyGToken() ``` ## onlyGTokenManager ```solidity theme={null} modifier onlyGTokenManager() ``` ## updateDesign ```solidity theme={null} function updateDesign(contract IGTokenLockedDepositNftDesign newValue) external ``` ## updateDesignDecimals ```solidity theme={null} function updateDesignDecimals(uint8 newValue) external ``` ## mint ```solidity theme={null} function mint(address to, uint256 tokenId) external ``` ## burn ```solidity theme={null} function burn(uint256 tokenId) external ``` ## tokenURI ```solidity theme={null} function tokenURI(uint256 tokenId) public view returns (string) ``` *See \{IERC721Metadata-tokenURI}.* # SDK Source: https://docs.gains.trade/developer/technical-reference/sdk Gains' SDK technical reference The [@gainsnetwork/sdk](https://www.npmjs.com/package/@gainsnetwork/sdk) is a TypeScript library for building on Gains: fetching trades and trading variables, computing borrowing/funding fees, liquidation prices, and PnL with the same logic as the contracts. * Source code: [github.com/GainsNetwork-org/sdk](https://github.com/GainsNetwork-org/sdk) * Types used by the SDK: [Client types](/developer/technical-reference/sdk/client-types) For end-to-end examples, see the [integration guides](/developer/integrators/guides). ## Trading fee helpers Use these helpers to derive v9 fee-floor values from normalized SDK trading variables: ```typescript theme={null} getPairMinFeeUsd(pairIndex, { fees, pairs }); getMinCollateral(pairIndex, { fees, pairs, collateralPriceUsd }); ``` `getPairMinFeeUsd` mirrors the contracts' `pairMinFeeUsd` getter after SDK normalization. `getMinCollateral` returns the minimum opening collateral in collateral tokens using the v9 rule `collateral >= 5 * minFeeUsd`. For direct `Fee` objects, use `getMinTradeFeeUsd(fee)`, `getMinOpeningCollateralUsd(fee)`, or `getMinOpeningCollateral(fee, collateralPriceUsd)`. # Client Types Source: https://docs.gains.trade/developer/technical-reference/sdk/client-types Typescript types used within SDK ```typescript theme={null} type TradeContainer = { trade: Trade; tradeInfo: TradeInfo; liquidationParams: LiquidationParams; initialAccFees: InitialAccFees; receivedAt?: number; }; ``` ```typescript theme={null} type Trade = { user: string; index: number; pairIndex: PairIndex; leverage: number; long: boolean; isOpen: boolean; collateralIndex: number; tradeType: TradeType; collateralAmount: number; openPrice: number; sl: number; tp: number; }; ``` ```typescript theme={null} type TradeInfo = { createdBlock: number; tpLastUpdatedBlock: number; slLastUpdatedBlock: number; maxSlippageP: number; lastOiUpdateTs: number; collateralPriceUsd: number; contractsVersion: number; lastPosIncreaseBlock: number; }; ``` ```typescript theme={null} type InitialAccFees = { accPairFee: number; accGroupFee: number; block: number; }; ``` ```typescript theme={null} type TradeInfo = { createdBlock: number; tpLastUpdatedBlock: number; slLastUpdatedBlock: number; maxSlippageP: number; lastOiUpdateTs: number; collateralPriceUsd: number; contractsVersion: number; lastPosIncreaseBlock: number; }; ``` ```typescript theme={null} type LiquidationParams = { maxLiqSpreadP: number; startLiqThresholdP: number; endLiqThresholdP: number; startLeverage: number; endLeverage: number; }; ``` ```typescript theme={null} type TradingGroup = { maxLeverage: number; minLeverage: number; name: string; }; ``` ```typescript theme={null} type Fee = { totalPositionSizeFeeP: number; totalLiqCollateralFeeP: number; oraclePositionSizeFeeP: number; // Position size in USD used as the minimum trading fee basis. // In v9 this is a fee floor input, not the minimum opening collateral. minPositionSizeUsd: number; }; ``` `minPositionSizeUsd` is used to derive the minimum trading fee: ```typescript theme={null} minFeeUsd = minPositionSizeUsd * totalPositionSizeFeeP; minOpeningCollateralUsd = 5 * minFeeUsd; ``` Use the SDK helpers `getPairMinFeeUsd(pairIndex, context)` and `getMinCollateral(pairIndex, context)` when you need the v9 opening constraint. ```typescript theme={null} type PairDepth = { onePercentDepthAboveUsd: number; onePercentDepthBelowUsd: number; }; ``` ```typescript theme={null} type PairParamsBorrowingFees = { pairs: BorrowingFeePair[]; groups: BorrowingFeeGroup[]; }; ``` ```typescript theme={null} type Pair = { name: string; description: string; from: string; to: string; feeIndex: number; groupIndex: number; pairIndex: PairIndex; spreadP: number; }; ``` ```typescript theme={null} type TradeHistoryRecord = { action: string; address: string; long: number; collateralPriceUsd: number; collateralIndex: number; date: string; leverage: number; pair: string; pnl_net: number; price: number; size: number; tx: string; collateralDelta: number | null; leverageDelta: number | null; marketPrice: number | null; }; ``` ```typescript theme={null} type MarketOrder = { trader: string; pairIndex: PairIndex; index: number; block: number; open: boolean; }; ``` ```typescript theme={null} type ChartBar = { close: number; high: number; isBarClosed: boolean; isLastBar: boolean; low: number; open: number; time: number; }; ``` ```typescript theme={null} type LeaderboardTrader = { address: string; tradesCount: number; winrate: number; pnl: number; volume: number; score: number; totalPnlUsd: number; }; ``` ```typescript theme={null} type OpenTradeParams = [ address: string, pairIndex: PairIndex, x1: number, x2: number, wei: number, price: string, buy: boolean, leverage: number, takeProfit: string, stopLoss: string ]; ``` ```typescript theme={null} type OiWindowsSettings = { startTs: number; windowsDuration: number; windowsCount: number; }; ``` ```typescript theme={null} type PairOi = { oiLongUsd: number; oiShortUsd: number; }; ``` ```typescript theme={null} type OiWindows = { [key: string]: PairOi; }; ``` ```typescript theme={null} type CollateralConfig = { collateral: string; isActive: boolean; precision: number; precisionDelta: number; decimals?: number; }; ``` ```typescript theme={null} type FeeTiers = { tiers: FeeTier[]; multipliers: number[]; currentDay: number; }; ``` ```typescript theme={null} type TraderFeeTiers = { traderInfo: TraderInfo; inboundPoints: number; outboundPoints: number; lastDayUpdatedPoints: number; expiredPoints: number[]; }; ``` ```typescript theme={null} type PairFactor = { cumulativeFactor: number; protectionCloseFactor: number; protectionCloseFactorBlocks: number; }; ``` ```typescript theme={null} type OpenInterest = { long: number; short: number; max: number; }; ``` ```typescript theme={null} type PendingOrder = { trade: Trade; user: string; index: string; isOpen: boolean; orderType: PendingOrderType; createdBlock: string; maxSlippageP: string; }; ``` ```typescript theme={null} type PairGroup = { groupIndex: number; block: number; initialAccFeeLong: number; initialAccFeeShort: number; prevGroupAccFeeLong: number; prevGroupAccFeeShort: number; pairAccFeeLong: number; pairAccFeeShort: number; }; ``` ```typescript theme={null} type BorrowingFeePair = BorrowingOi & { feePerBlock: number; accFeeLong: number; accFeeShort: number; accLastUpdatedBlock: number; feeExponent: number; oi: OpenInterest; groups: PairGroup[]; }; ``` ```typescript theme={null} type BorrowingFeeGroup = { feePerBlock: number; accFeeLong: number; accFeeShort: number; accLastUpdatedBlock: number; feeExponent: number; oi: OpenInterest; }; ``` ```typescript theme={null} enum TradeType { TRADE = 0, LIMIT = 1, STOP = 2 } ``` ```typescript theme={null} enum PositionType { LONG = "LONG", SHORT = "SHORT" } ``` ```typescript theme={null} enum PendingOrderType { MARKET_OPEN = 0, MARKET_CLOSE = 1, LIMIT_OPEN = 2, STOP_OPEN = 3, TP_CLOSE = 4, SL_CLOSE = 5, LIQ_CLOSE = 6 } ``` ```typescript theme={null} enum CounterType { TRADE = 0, PENDING_ORDER = 1 } ``` ```typescript theme={null} enum PairIndex { BTCUSD = 0, ETHUSD = 1, LINKUSD = 2, DOGEUSD = 3, MATICUSD = 4, ADAUSD = 5, SUSHIUSD = 6, AAVEUSD = 7, ALGOUSD = 8, BATUSD = 9, COMPUSD = 10, DOTUSD = 11, EOSUSD = 12, LTCUSD = 13, MANAUSD = 14, OMGUSD = 15, SNXUSD = 16, UNIUSD = 17, XLMUSD = 18, XRPUSD = 19, ZECUSD = 20, EURUSD = 21, USDJPY = 22, GBPUSD = 23, USDCHF = 24, AUDUSD = 25, USDCAD = 26, NZDUSD = 27, EURCHF = 28, EURJPY = 29, EURGBP = 30, LUNAUSD = 31, YFIUSD = 32, SOLUSD = 33, XTZUSD = 34, BCHUSD = 35, BNTUSD = 36, CRVUSD = 37, DASHUSD = 38, ETCUSD = 39, ICPUSD = 40, MKRUSD = 41, NEOUSD = 42, THETAUSD = 43, TRXUSD = 44, ZRXUSD = 45, SANDUSD = 46, BNBUSD = 47, AXSUSD = 48, GRTUSD = 49, HBARUSD = 50, XMRUSD = 51, ENJUSD = 52, FTMUSD = 53, FTTUSD = 54, APEUSD = 55, CHZUSD = 56, SHIBUSD = 57, AAPLUSD = 58, FBUSD = 59, GOOGLUSD = 60, AMZNUSD = 61, MSFTUSD = 62, TSLAUSD = 63, SNAPUSD = 64, NVDAUSD = 65, VUSD = 66, MAUSD = 67, PFEUSD = 68, KOUSD = 69, DISUSD = 70, GMEUSD = 71, NKEUSD = 72, AMDUSD = 73, PYPLUSD = 74, ABNBUSD = 75, BAUSD = 76, SBUXUSD = 77, WMTUSD = 78, INTCUSD = 79, MCDUSD = 80, METAUSD = 81, GOOGLUSD2 = 82, GMEUSD2 = 83, AMZNUSD2 = 84, TSLAUSD2 = 85, SPYUSD = 86, QQQUSD = 87, IWMUSD = 88, DIAUSD = 89, XAUUSD = 90, XAGUSD = 91, USDCNH = 92, USDSGD = 93, EURSEK = 94, USDKRW = 95, EURNOK = 96, USDINR = 97, USDMXN = 98, USDTWD = 99, USDZAR = 100, USDBRL = 101, AVAXUSD = 102, ATOMUSD = 103, NEARUSD = 104, QNTUSD = 105, IOTAUSD = 106, TONUSD = 107, RPLUSD = 108, ARBUSD = 109, EURAUD = 110, EURNZD = 111, EURCAD = 112, GBPAUD = 113, GBPNZD = 114, GBPCAD = 115, GBPCHF = 116, GBPJPY = 117, AUDNZD = 118, AUDCAD = 119, AUDCHF = 120, AUDJPY = 121, NZDCAD = 122, NZDCHF = 123, NZDJPY = 124, CADCHF = 125, CADJPY = 126, CHFJPY = 127, LDOUSD = 128, INJUSD = 129, RUNEUSD = 130, CAKEUSD = 131, FXSUSD = 132, TWTUSD = 133, PEPEUSD = 134, DYDXUSD = 135, GMXUSD = 136, FILUSD = 137, APTUSD = 138, IMXUSD = 139, VETUSD = 140, OPUSD = 141, RNDRUSD = 142, EGLDUSD = 143, TIAUSD = 144, STXUSD = 145, FLOWUSD = 146, KAVAUSD = 147, GALAUSD = 148, MINAUSD = 149, ORDIUSD = 150, ILVUSD = 151, KLAYUSD = 152, SUIUSD = 153, BLURUSD = 154, FETUSD = 155, CFXUSD = 156, BEAMUSD = 157, ARUSD = 158, SEIUSD = 159, BTTUSD = 160, ROSEUSD = 161, WOOUSD = 162, AGIXUSD = 163, ZILUSD = 164, GMTUSD = 165, ASTRUSD = 166, ONEINCHUSD = 167, FLOKIUSD = 168, QTUMUSD = 169, OCEANUSD = 170, WLDUSD = 171, MASKUSD = 172, CELOUSD = 173, LRCUSD = 174, ENSUSD = 175, MEMEUSD = 176, ANKRUSD = 177, IOTXUSD = 178, ICXUSD = 179, KSMUSD = 180, RVNUSD = 181, ANTUSD = 182, WAVESUSD = 183, SKLUSD = 184, SUPERUSD = 185, BALUSD = 186, WTIUSD = 187, XPTUSD = 188, XPDUSD = 189, HGUSD = 190, JUPUSD = 191, MANTAUSD = 192, BONKUSD = 193, PENDLEUSD = 194, OSMOUSD = 195, ALTUSD = 196, UMAUSD = 197, MAGICUSD = 198, API3USD = 199, STRKUSD = 200, DYMUSD = 201, NTRNUSD = 202, PYTHUSD = 203, SCUSD = 204, WIFUSD = 205, PIXELUSD = 206, JTOUSD = 207, MAVIAUSD = 208, MYROUSD = 209, STGUSD = 210, BOMEUSD = 211, ETHFIUSD = 212, METISUSD = 213, AEVOUSD = 214, ONDOUSD = 215, MNTUSD = 216, KASUSD = 217, RONINUSD = 218, ENAUSD = 219, WUSD = 220, ZEUSUSD = 221, TNSRUSD = 222, TAOUSD = 223, OMNIUSD = 224, PRCLUSD = 225, MERLUSD = 226, SAFEUSD = 227, SAGAUSD = 228, LLUSD = 229, MSNUSD = 230, REZUSD = 231, NOTUSD = 232, IOUSD = 233, BRETTUSD = 234, ATHUSD = 235, ZROUSD = 236, ZKUSD = 237, LISTAUSD = 238, BLASTUSD = 239, RATSUSD = 240, BNXUSD = 241, PEOPLEUSD = 242, TURBOUSD = 243, SATSUSD = 244, POPCATUSD = 245, MOGUSD = 246, OMUSD = 247, COREUSD = 248, JASMYUSD = 249, DARUSD = 250, MEWUSD = 251, DEGENUSD = 252, SLERFUSD = 253, UXLINKUSD = 254, AVAILUSD = 255, BANANAUSD = 256 } ``` # Commodities Source: https://docs.gains.trade/gtrade-leveraged-trading/asset-classes/commodities Leverage trading on commodity prices. ### Introduction Gains currently offers trading on 5 active commodities. XAU/USD (Gold), XAG/USD (Silver), and HG/USD (Copper) have leverage ranges of 2x-250x. WTI/USD (Crude Oil) and XPT/USD (Platinum) have leverage ranges of 2x-150x. See the [Pair List](/gtrade-leveraged-trading/pair-list) for the full list of available pairs. ### Market Times Just like forex markets, the commodities market is not always open. Times are referenced in ET (New York time). | Day of the week | Market open / close | | --------------- | --------------------------------- | | Monday | Open apart from 5:00 PM - 6:10 PM | | Tuesday | Open apart from 5:00 PM - 6:10 PM | | Wednesday | Open apart from 5:00 PM - 6:10 PM | | Thursday | Open apart from 5:00 PM - 6:10 PM | | Friday | Open until 5:00 PM | | Saturday | Closed all day | | Sunday | Open from 6:10 PM | The following **holidays** may close markets or shorten trading sessions. Times are referenced in ET (New York time): * April 2, 2026: Maundy Thursday (closes early at 1pm) * April 3, 2026: Good Friday * May 25, 2026: Memorial Day * June 19, 2026: Juneteenth National Independence Day * July 2, 2026: Day Before Independence Day (closes early at 1pm) * July 3, 2026: Independence Day * September 7, 2026: Labor Day * November 26, 2026: Thanksgiving Day * November 27, 2026: Black Friday (closes early at 1pm) * December 24, 2026: Christmas Eve (closes early at 12:45pm) * December 25, 2026: Christmas Day * December 31, 2026: New Year's Eve (closes early at 4pm) * January 1, 2027: New Year's Day * January 18, 2027: Martin Luther King, Jr. Day (closes at 1pm, reopens at 6pm) * February 15, 2027: Presidents' Day (closes at 2:30pm, reopens at 6pm) * March 26, 2027: Good Friday * May 31, 2027: Memorial Day ### Gaps Commodity prices can change while markets are closed, creating gaps where the market opens at a different price than the previous close. Because of this, stop losses are not guaranteed for commodities. Positions held while markets are closed can be liquidated by a gap against the position, or can reopen with more profit than expected if the gap moves in your favor. Consider this risk when using high leverage. ### Reduced Leverage/Increased Spread The max leverage is temporarily reduced and spread is temporarily increased during: * **Major USD news events**, from 3 hours before to 10 minutes after the event. * **Market closing**, usually starting 1 hour before the market closes. For tier 2 commodities on Fridays, this can start up to 6 hours before the weekly close. # Cryptocurrencies Source: https://docs.gains.trade/gtrade-leveraged-trading/asset-classes/cryptocurrencies Leverage trading on crypto pair prices. ### Introduction Gains currently offers trading on the price of over 220 crypto pairs at leverage ranges of 1.1x to 500x. See the [Pair List](/gtrade-leveraged-trading/pair-list) for the full list of available pairs. ### Market Times Crypto markets are open 24/7, which means you can trade whenever you want. However, when the stock market is closed, there is generally less volume on cryptos as well, and therefore less volatility. ### Guaranteed execution Crypto markets never close, so they do not have weekend or session gaps. For pairs with 0% dynamic spread, guaranteed stop losses can trigger at the exact price you set. Guaranteed stop losses for BTC and ETH may not appear immediately during high network congestion. Manually closing the order voids the guaranteed stop loss and counts as a market close at the triggered price. # Forex Source: https://docs.gains.trade/gtrade-leveraged-trading/asset-classes/forex Leverage trading on forex pair prices. ### Introduction Gains currently offers trading on 9 active forex pairs, with leverage ranges from 10x to 1000x depending on the pair category. See the [Pair List](/gtrade-leveraged-trading/pair-list) for the full list of available pairs. ### Market Times Unlike crypto markets, forex markets are not always open. Times are referenced in ET (New York time), and DST changes can shift the Sunday open and Friday close by 1 hour. | Day of the week | Market open / close | | --------------- | ----------------------------------------------------- | | Monday | Open all day | | Tuesday | Open all day | | Wednesday | Open all day | | Thursday | Open all day | | Friday | Open until 4:00 PM during DST, or 5:00 PM outside DST | | Saturday | Closed all day | | Sunday | Open from 4:00 PM during DST, or 5:00 PM outside DST | The following **holidays** may close markets or shorten trading sessions. Times are referenced in ET (New York time): * April 3, 2026: Good Friday * May 25, 2026: Memorial Day * June 19, 2026: Juneteenth National Independence Day * July 2, 2026: Day Before Independence Day (closes early at 1pm) * July 3, 2026: Independence Day * September 7, 2026: Labor Day * November 26, 2026: Thanksgiving Day * November 27, 2026: Black Friday (closes early at 1pm) * December 24, 2026: Christmas Eve (closes early at 12:45pm) * December 25, 2026: Christmas Day * December 31, 2026: New Year's Eve (closes early at 4pm) * January 1, 2027: New Year's Day * January 18, 2027: Martin Luther King, Jr. Day * March 26, 2027: Good Friday * May 31, 2027: Memorial Day ### Gaps Forex prices can change while markets are closed, creating gaps where the market opens at a different price than the previous close. Because of this, stop losses are not guaranteed for forex. Positions held while markets are closed can be liquidated by a gap against the position, or can reopen with more profit than expected if the gap moves in your favor. Consider this risk when using high leverage. ### Reduced Leverage/Increased Spread The max leverage is temporarily reduced and spread is temporarily increased during: * **Major news events**, from 3 hours before to 10 minutes after the event. * **Market closing**, starting 1 hour before the market closes. * **Low-liquidity sessions**, which vary by forex category and DST. Major forex pairs enter low liquidity from 3:45 PM to 7:00 PM during DST, or 4:45 PM to 8:00 PM outside DST. Minor and exotic forex pairs enter low liquidity from 2:45 PM to 9:00 PM during DST, or 3:45 PM to 10:00 PM outside DST. # Indices Source: https://docs.gains.trade/gtrade-leveraged-trading/asset-classes/indices Leverage trading on index prices. ### Introduction Gains currently offers trading on 7 active indices, at leverage ranges of 1.1x-100x. Indices are available on Arbitrum, Base, and Solana. Please refer to the [Pair List](/gtrade-leveraged-trading/pair-list) page to see a full list of the pairs currently offered. ### Market Times As with all RWA markets, the indices market is not always open. Times are referenced in ET (New York time). Positions remain open when the market is closed, but it is not possible to open, close, or otherwise edit positions during this time. [Please see more info below](#gaps). | Day of the week | Market open / close | | --------------- | ------------------- | | Monday | 9:35 AM - 4:00 PM | | Tuesday | 9:35 AM - 4:00 PM | | Wednesday | 9:35 AM - 4:00 PM | | Thursday | 9:35 AM - 4:00 PM | | Friday | 9:35 AM - 4:00 PM | | Saturday | Closed all day | | Sunday | Closed all day | The following **holidays** may close markets or shorten trading sessions. Times are referenced in ET (New York time): * April 3, 2026: Good Friday * May 25, 2026: Memorial Day * June 19, 2026: Juneteenth National Independence Day * July 2, 2026: Day Before Independence Day (closes early at 1pm) * July 3, 2026: Independence Day * September 7, 2026: Labor Day * November 26, 2026: Thanksgiving Day * November 27, 2026: Black Friday (closes early at 1pm) * December 24, 2026: Christmas Eve (closes early at 12:15pm) * December 25, 2026: Christmas Day * December 31, 2026: New Year's Eve (closes early at 4pm) * January 1, 2027: New Year's Day * January 18, 2027: Martin Luther King, Jr. Day * February 15, 2027: Presidents' Day * March 26, 2027: Good Friday * May 31, 2027: Memorial Day ### Gaps Index prices can change while markets are closed, creating gaps where the market opens at a different price than the previous close. Because of this, stop losses are not guaranteed for indices. Positions held while markets are closed can be liquidated by a gap against the position, or can reopen with more profit than expected if the gap moves in your favor. Consider this risk when using high leverage. ### Reduced Leverage/Increased Spread The max leverage is temporarily reduced and spread is temporarily increased during: * **Major USD news events**, from 3 hours before to 10 minutes after the event. * **Market closing**, starting 1 hour and 30 minutes before the market closes. *Exact timing and parameters may vary. Please note that this applies when opening new trades, and does not impact already open trades.* ### Access *Please note that index trading is not accessible to users located in the United States or other OFAC-sanctioned regions. Access is automatically restricted based on IP and other geolocation methods.* # Stocks Source: https://docs.gains.trade/gtrade-leveraged-trading/asset-classes/stocks Leverage trading on stock prices. ### Introduction Gains offers trading on the prices of an ever-growing number of stocks, at leverage ranges of 1.1x to 50x. Stocks are available on Arbitrum, Base, and Solana. Please refer to the [Pair List](/gtrade-leveraged-trading/pair-list) page to see a full list of the pairs currently offered. ### Market Times As with all RWA markets, the stock market is not always open. Times are referenced in ET (New York time). Positions remain open when the market is closed, but it is not possible to open, close, or otherwise edit positions during this time. [Please see more info below](#gaps). | Day of the week | Market open / close | | --------------- | ------------------- | | Monday | 9:35 AM - 4:00 PM | | Tuesday | 9:35 AM - 4:00 PM | | Wednesday | 9:35 AM - 4:00 PM | | Thursday | 9:35 AM - 4:00 PM | | Friday | 9:35 AM - 4:00 PM | | Saturday | Closed all day | | Sunday | Closed all day | The following **holidays** may close markets or shorten trading sessions. Times are referenced in ET (New York time): * April 3, 2026: Good Friday * May 25, 2026: Memorial Day * June 19, 2026: Juneteenth National Independence Day * July 2, 2026: Day Before Independence Day (closes early at 1pm) * July 3, 2026: Independence Day * September 7, 2026: Labor Day * November 26, 2026: Thanksgiving Day * November 27, 2026: Black Friday (closes early at 1pm) * December 24, 2026: Christmas Eve (closes early at 1pm) * December 25, 2026: Christmas Day * January 1, 2027: New Year's Day * January 18, 2027: Martin Luther King, Jr. Day * February 15, 2027: Presidents' Day * March 26, 2027: Good Friday * May 31, 2027: Memorial Day ### Gaps Stock prices can change while markets are closed, creating gaps where the market opens at a different price than the previous close. Because of this, stop losses are not guaranteed for stocks. Positions held while markets are closed can be liquidated by a gap against the position, or can reopen with more profit than expected if the gap moves in your favor. Consider this risk when using high leverage. ### Reduced Leverage/Increased Spread The max leverage is temporarily reduced and spread is temporarily increased during: * **Major USD news events**, from 3 hours before to 10 minutes after the event. * **Market closing**, starting 1 hour and 30 minutes before the market closes. * **Earnings and dividends**, usually starting 1-2 days before depending on the event timing. *Exact timing and parameters may vary. Please note that this applies when opening new trades, and does not impact already open trades.* ### Access *Please note that stock trading is not accessible to users located in the United States or other OFAC-sanctioned regions. Access is automatically restricted based on IP and other geolocation methods.* # Fees & Spread Source: https://docs.gains.trade/gtrade-leveraged-trading/fees-and-spread Full breakdown of Gains fees, spread, price impact, holding fees (funding + borrowing), and liquidation thresholds. ## Introduction In line with industry standards, **fees are calculated on the value of the total position size** (leverage x collateral). 1. [Fees Breakdown](#fees-breakdown) 1. [Cryptocurrencies](#cryptocurrencies) 2. [Degen](#degen) 3. [Forex](#forex-major) 4. [Commodities](#commodities) 5. [Revenue Distribution](#fees-breakdown) 2. [Lifecycle of a Trade](#lifecycle-of-a-trade) 1. [Opening Fee](#opening-fee) 2. [Spread](#fixed-spread) 3. [Price Impact](#price-impact) 4. [Holding Fees](#holding-fees) 1. [Funding Fees](#funding-fee) 2. [Borrowing Fees](#borrowing-fee) 5. [Dynamic Liquidation Prices](#liquidation-prices) 6. [Closing Fee](#closing-fee) ## Fees Breakdown The "Market/Limit" fee below goes to the protocol fee distribution if the order is a market order, and to oracle bots if the order is a limit order. Additionally, the referrer rewards are always taken from the "Governance Fund" fees. Finally, while all trades are open, they accrue [holding fees](#holding-fees): a [borrowing fee](#borrowing-fee), which goes into the overcollateral layer of the corresponding gToken vault, and a [funding fee](#funding-fee), which is paid between traders and can be earned rather than paid. Gains Network earns revenue from trading fees on Gains. Fees are distributed as follows: • Governance (DAO): 76% for protocol operations and incentives\ • Vault (Liquidity Providers): 15% for underwriting trades\ • Referrals: 5%\ • Trigger Keepers: 4% The share previously allocated to the GNS buyback & burn is, for now, directed to the Governance (DAO). ### Cryptocurrencies Most cryptocurrencies have no fixed spread (0%); their cost comes from [price impact](#price-impact), which depends on liquidity, open-interest skew, and trade size. The exception is **BTC/USD and ETH/USD**, which carry a fixed spread of **0.005% per side (0.01% round trip)** — the same level as major forex — and have no liquidity-impact depth configured, so they incur effectively no size-based impact on top of it. For all other crypto pairs, price impact is minimal for the deepest markets and larger for smaller, less liquid pairs. **BTC and ETH** 1. **Opening a trade: 0.035%** 2. **Closing a trade: 0.035%** **Core** 1. **Opening a trade: 0.05%** 2. **Closing a trade: 0.05%** **Non-core** 1. **Opening a trade: 0.06%** 2. **Closing a trade: 0.06%** ### Degen Degen pairs are high-leverage variants offering a fixed 500x leverage. The available degen pairs are: * BTCDEGEN/USD * ETHDEGEN/USD * SOLDEGEN/USD * BNBDEGEN/USD * HYPEDEGEN/USD * ZECDEGEN/USD 1. **Opening a trade: 0.02%** 2. **Closing a trade: 0.02%** SOLDEGEN/USD, HYPEDEGEN/USD, and ZECDEGEN/USD have a fixed spread of 0.005% per side (0.01% round trip). All other degen pairs have a spread of 0%. ### Forex (Major) Spreads on all major forex pairs are fixed at 0.005% per side (0.01% round trip). 1. **Opening a trade: 0.012%** 2. **Closing a trade: 0.012%** ### Forex (Minor) Spreads on all minor pairs are fixed at 0.005% per side (0.01% round trip). 1. **Opening a trade: 0.016%** 2. **Closing a trade: 0.016%** ### Forex (Exotic) Spreads on all exotic forex pairs are set per pair depending on their volatility. 1. **Opening a trade: 0.02%** 2. **Closing a trade: 0.02%** ### Commodities Commodities are configured per pair rather than by a single tier, so both the fee and the fixed spread vary by asset. Currently listed: | Commodity | Opening / closing fee | Fixed spread | | ------------------ | --------------------- | ---------------------------------- | | Gold (XAU/USD) | 0.035% | none | | Silver (XAG/USD) | 0.05% | 0.025% per side (0.05% round trip) | | Copper (HG/USD) | 0.05% | 0.02% per side (0.04% round trip) | | Oil (WTI/USD) | 0.04% | 0.025% per side (0.05% round trip) | | Platinum (XPT/USD) | 0.05% | 0.02% per side (0.04% round trip) | Each fee is charged on the total position size, on both opening and closing. ### Stocks Stock fees vary by pair. Each stock sits in one of three fee groups, charged on both opening and closing: | Opening / closing fee | Example pairs | | --------------------- | ---------------- | | 0.05% | MSFT, GOOGL, MCD | | 0.04% | AAPL, NVDA, PYPL | | 0.03% | AMD, SNAP, GME | ### Indices 1. **Opening a trade: 0.05%** 2. **Closing a trade: 0.05%** ## **Lifecycle of a Trade** ### Opening Fee Let's say we use **250 USDC** at **10x** leverage to long a non-core crypto pair. The fee is applied to leveraged amount: **2,500 USDC**. 2,500 \* (0.06/100) = **1.5 USDC fee** **248.5 USDC** is the total collateral value of your newly opened trade, and therefore its total position size is **2,485 USDC**. ### **Fixed Spread** When opening a trade the Chainlink oracle returns a price for the asset. If the pair has a fixed spread, it is then applied to that price. For instance, with a 0.04% fixed spread on an oracle price of 3,003.19, the open price would be **3004.39** before consideration of the dynamic spread (see section below). That is: 3,003.19 + (3,003.19 \* 0.04 / 100) = **3004.39** Note that most crypto pairs have no fixed spread (0%), in which case only [price impact](#price-impact) applies. BTC and ETH are an exception among cryptos: they carry a fixed spread of **0.005% per side (0.01% round trip)**. See the [fees breakdown](#cryptocurrencies) for per-class spreads. Spreads vary by pair. Smaller pairs with lower liquidity usually have a higher spread. The spread is displayed next to **Price** in the trade parameters and can be confirmed in the [Pairs Storage](/what-is-gains-network/contract-addresses) contract by searching for the relevant [pair index](/gtrade-leveraged-trading/pair-list). ### Price Impact On top of any fixed spread, every trade is subject to **price impact**, which reflects the pair's real-time order-book liquidity, its current open-interest skew, and the size and direction of your trade. Price impact is dynamic: it changes block to block, and trading against the prevailing flow can make it favorable. The total applied to a trade is: **Total price impact = Fixed spread + Liquidity impact + Skew impact** This total is displayed as **Price impact** in the trade parameters, with the per-component breakdown in its tooltip, and is added to (or subtracted from) the oracle price to produce your execution price. Not every pair carries every component — it depends on what is configured on-chain for that pair: * **Most cryptocurrencies and forex** have liquidity impact (forex's is tiny because its books are very deep). Skew impact applies where a skew depth is configured. * **Stocks, commodities, and indices** are **fixed-spread only** — they have no liquidity impact or skew impact, so the fixed spread is their entire spread cost. * **BTC and ETH** carry a fixed spread of **0.005% per side (0.01% round trip)** but have no liquidity impact (no depth bands are configured) and only a negligible skew component — so apart from that flat fixed spread, their price impact is effectively 0. The trade-parameters tooltip only lists the components that actually apply to the selected pair. #### Liquidity impact Liquidity impact (previously called "dynamic spread") depends on: * the pair's **recent open interest**, accumulated over short rolling volume windows — so it builds up with activity and decays over a few minutes, * the **size of your trade**, and * the pair's **order-book depth** — the 1% depth in each direction (long: 1% depth above / short: 1% depth below), sourced from Binance and split into depth bands. Larger trades and more recent same-direction volume push your fill further along the liquidity curve, increasing impact. As recent volume ages out of the windows, it recovers. Conceptually: **Liquidity impact (%) ≈** (recent open interest \{long/short} + trade size / 2) / 1% depth \{above/below} The exact value walks the pair's depth bands, but the formula above is a close approximation. #### Skew impact Skew impact depends on the pair's current **open-interest imbalance** (long OI vs short OI). Trades that increase the imbalance (trading with the heavier side) pay more; trades that reduce it (trading against the heavier side) pay less, and can even receive a better-than-oracle price. This keeps open interest balanced without requiring a lower maximum open interest. #### Example Suppose you open a **10,000 USDC** long on a crypto pair whose "1% depth above" is **2,000,000 USDC**, with **500,000 USDC** of recent long open interest in the volume windows. The liquidity impact is approximately: **(500,000 + 10,000 / 2) / 2,000,000 ≈ 0.25%** This pair — like most cryptos, but unlike BTC and ETH — has no fixed spread, so this applies directly to the oracle price: on an oracle price of 150.00 the execution price would be about **150.38**. Any skew impact is applied on the same basis. Because impact scales with trade size relative to depth, the same notional costs very different amounts across pairs. A 10,000 USDC order on a smaller-cap pair with \~120,000 USDC of depth incurs roughly **0.06%** liquidity impact; the same order on **BTC or ETH incurs \~0% liquidity impact**, because those pairs have no liquidity-impact depth bands configured (they instead charge a flat 0.005%-per-side fixed spread, not because their books are merely deeper). And at a tiny size — say a few dollars — liquidity impact rounds to \~0% on every pair. ### Holding Fees While a trade is open it accrues **holding fees**, charged continuously on the total position size (leverage x collateral). Holding fees are the sum of two separate components: * **[Funding fees](#funding-fee)** — balance long and short exposure. You can **pay or earn** these. * **[Borrowing fees](#borrowing-fee)** — charge the dominant side for using vault liquidity. You always pay these. The interface shows the two combined as a single **Holding Rate** on the trade panel and **Holding Fees** on an open position, so the figure you see there is funding + borrowing together, not one or the other. #### Funding Fee Funding fees balance the two sides of a market. Whichever side has more open interest pays the other side: if the market is net long, longs pay shorts; if it is net short, shorts pay longs. This makes funding the one fee on Gains that can work in your favour — if you open on the lighter side of an imbalanced market, you **earn** funding for as long as you hold that position and the imbalance persists. The rate is not fixed. It accelerates the more imbalanced a market becomes and the longer that imbalance lasts, which increases the incentive to take the underweighted side and brings open interest back toward balance. It then decays as the market rebalances. Funding fees are charged per second on a trade's total position size, and apply only to positions opened under v10. #### Borrowing Fee Borrowing fees treat open trades of the dominant side as vault borrowers. The fee is determined by a pair's (or the group the pair is part of) net OI relative to the overall vault TVL, meaning pairs (or groups) with more lopsided OI will charge more than pairs with balanced OI. The fee is charged per block on a trade's total position size and is calculated as follows: `feePerBlock = baseFeePerBlock * (effectiveOi / maxOi) ^ exponent` where `effectiveOi` is calculated as follows: `effectiveOi = Math.min(Math.max(Math.abs(long - short), max * minP), max * maxP)` `effectiveOi` is calculated by finding the delta between the side that is long and the side that is short. This value is then clamped using `minP` and `maxP` to create a floor and a ceiling, ensuring that both a minimum fee is always paid, and that the fee is never excessive. `exponent` is used to maintain an exponential relationship between the borrowing fee and the current market conditions. Note that borrowing fees are only one half of what a trade pays while open — see [Holding Fees](#holding-fees) for how they combine with funding fees. ### Liquidation Prices Trades liquidation prices can **get closer** over time if you **pay borrowing fees**. ***Liquidation Price Distance =** Open Price \* (Collateral \** [*Liquidation Threshold*](#liquidation-thresholds) *- Closing Fee - Borrowing Fees) / Collateral / Leverage.* **Liquidation price =** \ If Long: Open Price - Liquidation Price Distance\ Else (Short): Open Price + Liquidation Price Distance. For example, let's say that you have opened a long on BTC/USD at 20,000 USD using 100x leverage and 50 USDC collateral, the liquidation threshold would be 67%, the closing fee would be 7 USDC (20,000\*(0.035/100) and that you have paid 1 USDC in borrowing fees: **Liquidation Price =** 20,000 - 20,000 \* (50 \* 0.67 - 7 - 1) / 50 / 100 = 19,898 USD. ### Liquidation Thresholds The liquidation threshold depends on asset class and leverage used. The values can be found in the following table, for *Cryptocurrencies, Forex (major), Forex (minor), Forex (exotic), Commodities (gold), Commodities (other)* **Cryptocurrencies** | Leverage | Liquidation Threshold % | | -------- | ----------------------- | | 2 | 89.84 | | 5 | 89.60 | | 10 | 89.20 | | 15 | 88.80 | | 20 | 88.40 | | 25 | 88.00 | | 30 | 85.46 | | 35 | 82.91 | | 40 | 80.37 | | 45 | 77.83 | | 50 | 75.29 | | 55 | 72.74 | | 60 | 70.20 | | 65 | 69.80 | | 70 | 69.40 | | 75 | 69.00 | | 80 | 68.60 | | 85 | 68.20 | | 90 | 67.80 | | 95 | 67.40 | | 100 | 67.00 | | 105 | 66.60 | | 110 | 66.20 | | 115 | 65.80 | | 120 | 65.40 | | 125 | 65.00 | | 130 | 64.60 | | 135 | 64.20 | | 140 | 63.80 | | 145 | 63.40 | | 150 | 63.00 | **Forex (major)** | Leverage | Liquidation Threshold % | | -------- | ----------------------- | | 2 | 89.98 | | 25 | 89.70 | | 50 | 89.40 | | 75 | 89.10 | | 100 | 88.80 | | 125 | 86.63 | | 150 | 84.45 | | 175 | 82.28 | | 200 | 80.10 | | 225 | 77.93 | | 250 | 75.75 | | 275 | 73.58 | | 300 | 71.40 | | 325 | 71.10 | | 350 | 70.80 | | 375 | 70.50 | | 400 | 70.20 | | 425 | 69.90 | | 450 | 69.60 | | 475 | 69.30 | | 500 | 69.00 | | 525 | 68.70 | | 550 | 68.40 | | 575 | 68.10 | | 600 | 67.80 | | 625 | 67.50 | | 650 | 67.20 | | 675 | 66.90 | | 700 | 66.60 | | 725 | 66.30 | | 750 | 66.00 | | 775 | 65.70 | | 800 | 65.40 | | 825 | 65.10 | | 850 | 64.80 | | 875 | 64.50 | | 900 | 64.20 | | 925 | 63.90 | | 950 | 63.60 | | 975 | 63.30 | | 1000 | 63.00 | **Forex (minor)** | Leverage | Liquidation Threshold % | | -------- | ----------------------- | | 2 | 89.97 | | 25 | 89.60 | | 50 | 89.20 | | 75 | 88.80 | | 100 | 85.54 | | 125 | 82.29 | | 150 | 79.03 | | 175 | 75.77 | | 200 | 72.51 | | 225 | 69.26 | | 250 | 66.00 | | 275 | 65.60 | | 300 | 65.20 | | 325 | 64.80 | | 350 | 64.40 | | 375 | 64.00 | | 400 | 63.60 | | 425 | 63.20 | | 450 | 62.80 | | 475 | 62.40 | | 500 | 62.00 | | 525 | 61.60 | | 550 | 61.20 | | 575 | 60.80 | | 600 | 60.40 | | 625 | 60.00 | | 650 | 59.60 | | 675 | 59.20 | | 700 | 58.80 | | 725 | 58.40 | | 750 | 58.00 | **Forex (exotic)** | Leverage | Liquidation Threshold % | | -------- | ----------------------- | | 2 | 89.96 | | 25 | 89.50 | | 50 | 89.00 | | 75 | 84.33 | | 100 | 79.67 | | 125 | 75.00 | | 150 | 70.33 | | 175 | 65.67 | | 200 | 61.00 | | 225 | 60.50 | | 250 | 60.00 | | 275 | 59.50 | | 300 | 59.00 | | 325 | 58.50 | | 350 | 58.00 | | 375 | 57.50 | | 400 | 57.00 | | 425 | 56.50 | | 450 | 56.00 | | 475 | 55.50 | | 500 | 55.00 | **Commodities (gold)** | Leverage | Liquidation Threshold % | | -------- | ----------------------- | | 2 | 89.90 | | 10 | 89.50 | | 20 | 89.00 | | 30 | 87.50 | | 40 | 85.00 | | 50 | 82.50 | | 60 | 80.00 | | 70 | 77.50 | | 80 | 75.00 | | 90 | 72.50 | | 100 | 70.00 | | 110 | 69.50 | | 120 | 69.00 | | 130 | 68.50 | | 140 | 68.00 | | 150 | 67.50 | | 160 | 67.00 | | 170 | 66.50 | | 180 | 66.00 | | 190 | 65.50 | | 200 | 65.00 | | 210 | 64.50 | | 220 | 64.00 | | 230 | 63.50 | | 240 | 63.00 | | 250 | 62.50 | **Commodities (other)** | Leverage | Liquidation Threshold % | | -------- | ----------------------- | | 2 | 89.84 | | 5 | 89.60 | | 10 | 89.20 | | 15 | 88.80 | | 20 | 88.40 | | 25 | 88.00 | | 30 | 84.74 | | 35 | 81.49 | | 40 | 78.23 | | 45 | 74.97 | | 50 | 71.71 | | 55 | 68.46 | | 60 | 65.20 | | 65 | 64.80 | | 70 | 64.40 | | 75 | 64.00 | | 80 | 63.60 | | 85 | 63.20 | | 90 | 62.80 | | 95 | 62.40 | | 100 | 62.00 | | 105 | 61.60 | | 110 | 61.20 | | 115 | 60.80 | | 120 | 60.40 | | 125 | 60.00 | | 130 | 59.60 | | 135 | 59.20 | | 140 | 58.80 | | 145 | 58.40 | | 150 | 58.00 | ### Closing Fee Let's say a non-core crypto pair **went up 1%** from the open price, and we close the trade at **3,033.6**. The pending profit (PnL) will be 1% of 2480 (our leveraged collateral), which is **24.85 USDC**. Now, we close the trade, and therefore pay the closing fee. Please note that the fees are always applied on the initial position size (without PnL). 2485 \* (0.06/100) = 1.491 USDC closing fee \--> 24.85 - 1.491 = **23.359 USDC PnL** Now let's also say that the trade **paid 0.5 USDC** of **borrowing fees**: 23.359 - 0.5 = **22.859 USDC final PnL** Therefore, you would receive **271.359 USDC** (248.5 USDC collateral + 22.859 PnL) to your wallet after closing your trade. # Gains Solana Source: https://docs.gains.trade/gtrade-leveraged-trading/gtrade-solana Trade supported pairs directly from a Solana wallet. Visit Gains Solana at [sol.gains.trade](https://sol.gains.trade/). For more details on the Solana UX and how to open your first trades, visit this [Medium article](https://medium.com/gains-network/gtrade-solana-your-gateway-to-effortless-trading-22d1fe30bd80) or watch this [video tutorial](https://www.youtube.com/watch?v=7tpOmlTEWbM). *Gains Solana* # How to use Practice Mode Source: https://docs.gains.trade/gtrade-leveraged-trading/how-to-use-practice-mode Try Gains risk-free with practice mode on testnet funds. Practice Mode lets you test Gains as if you were live trading, without using collateral with real value. It runs on **Arbitrum Sepolia**. You will need: 1. A Web3 wallet like Rabby or MetaMask connected to Arbitrum Sepolia 2. Testnet ETH to pay for transactions 3. Testnet DAI to use as collateral Let's set it up: 1. Open the network dropdown on gains.trade and select **Sepolia - Practice**. Your wallet should prompt you to add Arbitrum Sepolia. *Select Sepolia from the dropdown menu.* Alternatively, go to [sepolia.arbiscan.io](https://sepolia.arbiscan.io/), scroll to the bottom, and click **Add Arbitrum One Sepolia Network**. *Scroll to the bottom of the page to see the button.* 2. Get Arbitrum Sepolia ETH for gas. A website that distributes testnet tokens is called a faucet. *(Please note that Sepolia as a testnet exists on several chains, so whichever faucet you use, be sure to select Arbitrum Sepolia)* [https://faucets.chain.link/arbitrum-sepolia](https://faucets.chain.link/arbitrum-sepolia) (0.1 ETH, Requires Github login) [https://faucet.quicknode.com/arbitrum/sepolia](https://faucet.quicknode.com/arbitrum/sepolia) (0.05-0.1 ETH, requires holding 0.001 ETH on Ethereum Mainnet) [https://www.alchemy.com/faucets/arbitrum-sepolia](https://www.alchemy.com/faucets/arbitrum-sepolia) (0.1-0.5 ETH per day, requires an Alchemy account (free) and a balance of 0.001 ETH on Arbitrum Mainnet) Faucets may be unavailable at times. If you need help setting up Practice Mode, ask in Discord or Telegram. 3. Select **Sepolia - Practice** from the network dropdown on the trading page and connect your wallet. Once you are connected you can click 'Approve' in the trading panel, and then click 'Get 10,000 DAI' to get your practice DAI. *Click Approve, send the transaction, then click Get 10,000 DAI and send the transaction.* You can then use the platform as you would on mainnet. If your testnet DAI balance drops below 1,000 DAI, the button will show again so you can claim 10,000 DAI more. Follow the guide [Opening and Closing a Trade](/gtrade-leveraged-trading/opening-closing-trades). # One-Click Trading (1CT) Source: https://docs.gains.trade/gtrade-leveraged-trading/one-click-trading-1ct Reduce repeated wallet confirmations with one-click trading. ## Overview One-click trading (1CT) removes the need to interact with a wallet when submitting transactions, reducing time to trade. It does this through the use of two new mechanisms: * 1CT wallet * Trade delegation ## 1CT Wallet Gains uses a derived externally owned account (EOA) wallet for submitting trading transactions. It relies on the following sequence: 1. Trader provides a 4 digit PIN * *This pin should be remembered for future recovery* 2. Trader signs a prefixed message of the PIN using their wallet * *The wallet used to sign the message should be remembered for future recovery* 3. Gains website generates an Secp256k1 key pair using the signed message as a seed 4. Gains website encrypts and stores the key material on the local device > Key material is deterministic meaning it can be replicated. Pin + personalSign gives strong security guarantees while allowing a trader to recover material if lost. A trader can also use this to prevent storing on device between trading sessions (clear and regenerate for each session). Once a trader creates a 1CT wallet, they must grant it permissions to trade on their behalf by approving it as a delegate. ## Trade Delegation Gains smart contracts support a delegation feature, allowing EOAs to submit transactions on behalf of other EOAs. To delegate trading to another EOA, a trader must approve the address as a delegate through the trading contract. A delegation wallet only needs gas funds for submitting transactions, as collateral and PnL are tied to the trader address. * Open a trade * Open an order * Cancel an order * Update stop loss * Update take profit * Close a trade The 1CT wallet is a delegation wallet. ## Onboard Gains offers an onboarding experience for all of the above: 1. Create PIN 2. Sign message 3. Approve 1CT wallet 4. Fund 1CT wallet 5. Enable feature ## Manage Once a trader has onboarded, they may manage the feature under the accounts dropdown: * Enable/disable the feature * Fund 1CT wallet * Withdraw all funds from 1CT wallet * Export private key * Reset/wipe all 1CT data ## Use Once onboarded, a trader may enable the feature and use their normal trading workflows. At this point there is nothing different other than not having to confirm transactions in a wallet. ## Transactions Because 1CT wallet is managed by the site, transaction management is taken in-house. This provides a place to track transactions and interact if they're stuck by speeding up or canceling. ## FAQ **Is the 1CT wallet key material stored somewhere?** \ Only on your device. You can wipe it using "Reset" whenever you choose. **I wiped my device storage, is my 1CT wallet gone?**\ Yes but you can restore it by using the same PIN and wallet when re-generating. **Are trades opened against my 1CT wallet?**\ No, they are opened against your connected wallet. **Do I have to have 1CT enabled to interact with trades I opened with it?** \ No, you may toggle the feature on and off whenever you'd like. **Can I use the same 1CT wallet on multiple devices?**\ Yes, as long as you use the same PIN and wallet while generating. **Can I use the same 1CT wallet for multiple accounts?**\ Yes, you may delegate to your 1CT wallet with any connected wallet. **Can I have multiple 1CT wallets?**\ For each account you use to trade, you may have one delegate. The recommended setup is to use the same 1CT wallet for all trading accounts. **What if my transaction is stuck?**\ In the accounts dropdown, you'll find a transactions list. Here you may speed up and/or cancel a stuck transaction. **Do I have to have key material stored on device?**\ No, you can re-create your 1CT wallet and reset it at the end of each trading session. Just use the same PIN and wallet to sign. # Opening / Closing trades Source: https://docs.gains.trade/gtrade-leveraged-trading/opening-closing-trades Step-by-step guide to opening and closing trades on the Gains interface. This guide shows how to open and close trades through the [gains.trade](https://gains.trade) interface. To open and close trades on Gains you will need: 1. A Web3 wallet, such as [MetaMask](https://metamask.io/), connected to Gains. 2. The network's gas token in that wallet to pay for transaction fees (e.g. ETH on Arbitrum/Base, POL on Polygon). 3. A supported collateral in that wallet. See [Trade Collaterals](/gtrade-leveraged-trading/trade-collaterals) for availability per chain. **Interface Overview** These are the main areas of the trading interface used in this guide. **Opening a trade** **1.** Go to our [platform](https://gains.trade/decentralized-trading/). **2.** Click **Connect Wallet** in the top right. You may need to unlock your wallet or refresh the page before the interface detects it. **3.** If this is your first trade with a collateral, approve the contract to use that collateral. Click **Approve** and submit the transaction. Approve to allow the contract to use your collateral. **4.** Use **Add Pair +** to select the pair you want to trade. Favorite it if you want to save it in your trading interface. **Hide closed** hides forex and commodities markets while they are closed. **5.** Now, you can set your trade parameters: 1. **Trade type** and direction. 1. **Market:** opens immediately at the market price plus spread. 2. **Limit:** opens long below the current price or short above the current price once the threshold is reached. 3. **Stop Limit:** opens long above the current price or short below the current price once the threshold is reached. 2. **Collateral:** the maximum amount you risk if liquidated. Collateral multiplied by leverage must exceed the minimum position size, which can vary by market and network. The interface shows the current minimum for your selected pair and collateral. 3. **Leverage:** increases your exposure to price movement. 4. **Max slippage:** cancels a market order if price moves too far before the order opens. 5. **Stop loss and take profit:** optional levels that help manage risk. If no stop loss is set, the trade can be liquidated when it reaches the [liquidation threshold](/gtrade-leveraged-trading/fees-and-spread#liquidation-thresholds). Trade parameters and MetaMask confirmation. Click the order execution button, which displays the order type and direction. In this example, it says **MARKET LONG**. Your wallet opens a transaction confirmation popup. Higher gas is suggested automatically to help the trade execute quickly. After the transaction is submitted, the interface shows the number of confirmations required before the trade appears. Once 2 blocks have passed, it is displayed under **Your Open Trades**. **Order Initiated:** This is the moment that your request to execute an order reaches the network.\ **Executed:** This is the moment your trade is executed, when our Chainlink DON returns the current price. In the below example the price has just been returned. See the [FAQ](/help/faq) for more on block confirmations. First the order initiates, then it is executed. **Viewing the details of an Open Trade & Updating TP/SL** Now your trade is open, you can view its details by clicking on it under Your Open Trades. You can also see the liquidation price marked in blue on the chart, and if you have them set you will see TP/SL lines in green/red respectively. An active trade in Your Open Trades. By clicking on your trade, you can view its details. If you click on the TP/SL price you will see the prompt to update these - you can input the price desired to TP/SL and it will show you what % that would be in relation to your collateral. If you don't have a TP/SL it will show "None". The displayed Net PnL is what you will receive back to your wallet at the moment of closure registering on chain. See [Fees & Spread](/gtrade-leveraged-trading/fees-and-spread) for more details on fees. **Closing a trade** 1. Click the **X** on the right side of your trade under **Your Open Trades**. The X to the right will let you close your trade. 2. Confirm in MetaMask to send the close transaction. 3. Wait for trade closure confirmation. The final amount is sent to your wallet. Closure of the trade. # Trading interface overview Source: https://docs.gains.trade/gtrade-leveraged-trading/overview Learn how Gains powers decentralized leveraged trading across crypto, forex, commodities, stocks, and indices. *Start trading at [gains.trade](https://gains.trade/trading).* ## Summary ### Trading experience 1. **Full custody of your funds**\ No deposit or signup is required. 2. **Median spot prices**\ Orders execute against median spot prices from multiple sources. 3. **Minimal price impact on BTC and ETH**\ A flat 0.005% fixed spread per side and no size-based liquidity impact. 4. **Crypto, forex, and commodities available** 5. **High leverages available**\ Up to 500x on crypto, 1000x on forex, and 250x on commodities. 6. **Competitive fees** 7. **Transparent and decentralized**\ Trades execute on-chain. 8. **Polished user experience**\ The interface has evolved through more than 4 years of user feedback. ### Trading engine 1. **No order books or liquidity for each pair**\ gToken vaults provide shared liquidity for all listed trading pairs. 2. **Synthetic leverage (not borrowed)**\ Synthetic exposure reduces the amount of liquidity required per market. 3. **Real-time custom Chainlink decentralized oracle network (DON)**\ Orders request on-demand spot prices from a custom Chainlink DON. ## How does it work? Trades are opened with supported collateral such as \$USDC, \$DAI, \$GNS, or \$WETH, regardless of the trading pair. The leverage is synthetic and backed by [the relevant gToken vault](/liquidity-farming-pools/gtoken-vaults) and the \$GNS token. When traders have positive PnL, the vault pays it out. When traders have negative PnL, the vault receives the loss. ### Powered by Chainlink Many derivatives platforms derive execution prices from internal order books or similar models. Gains uses a custom real-time [Chainlink](https://chain.link/) node operator network to fetch the median spot price for each trading order. A detailed explanation of the decentralized oracle network is available in [Gains Farm: Using Chainlink to Power Decentralized Leveraged Trading](https://gainsnetwork-io.medium.com/gains-farm-using-chainlink-to-power-decentralized-leveraged-trading-fe954b37eb97). ### More resilient pricing The DON filters out outlier price action from any single exchange, whether caused by manipulation attempts or temporary lack of liquidity. This reduces the chance of liquidation from isolated exchange wicks. These are **your** trades. **Gains cannot open, close, or edit your open trades** unless you have approved the smart contract to do so through a stop loss or take profit, or unless the position must be liquidated. Governance can pause new trade openings during contract upgrades. This does not close existing positions, and traders still retain control over closing their trades. The trading engine is fully decentralized, and users keep custody of their funds. No signup or deposit is required to start trading. ### Concrete example Because Gains uses multiple price sources for every pair, the ETH/USD price only dipped to **\$2,980.32** during this volatile move. Compare that with the price action on a major centralized exchange: On that exchange, the wick bottomed at **\$2,977.62**. A position using that exchange price could have been liquidated even though the broader market quickly recovered. The difference between the Chainlink DON price and the centralized exchange price was 0.09% in this case, which equals **13.5% PnL** at 150x leverage. Even small price-source deviations can materially affect high-leverage strategies. On order-book venues, closing a position into thin liquidity can also push the price further down and amplify the wick. ### Exceptional user experience Start trading at gains.trade Because a single gToken vault can provide liquidity across many listed pairs, Gains can support a broad range of markets and leverage profiles. The interface has also been refined through more than 4 years of user feedback. ### Competitive trading fees Fees are distributed to the governance fund, gToken liquidity providers, \$GNS staking, referrals, and the oracle bots that execute limit orders in a decentralized manner. See [Fees & Spread](/gtrade-leveraged-trading/fees-and-spread) for details. ### Liquidity efficiency Since all trades use gToken liquidity layers (trading vault), we have a big advantage over other platforms who have to build new liquidity in their order books every time they list a new pair, and maintain high liquidity on each pair. By building big gToken vaults (with trading fees incentives), every trading pair listed on our platform benefits from bigger position sizes. This means the platform only requires \$USDC, \$DAI, \$GNS, or \$WETH liquidity for **ALL** pairs that can be traded on the platform. This is possible because Gains does not match buy and sell orders through an order book. Instead, trader PnL is calculated in the smart contracts and settled against the gToken vaults. ### Current limitations Maximum open interest is capped per pair and per group of correlated pairs. These limits help manage risk for liquidity providers. # Pair List Source: https://docs.gains.trade/gtrade-leveraged-trading/pair-list All trading pairs available on Gains, with their pairIndex, asset class, and max leverage. This is a list of Gains trading pairs, their relevant pairIndex, and the asset class. \ \ **The pairIndex:** * Is useful in the case of needing to interact with the contracts directly. * Reflects the chronological order the asset was added to Gains. * Includes pairs that are no longer listed, but kept for technical reasons. **Please note:** * Stock splits are indicated by a trailing `_1` * **Max Leverage** is the highest leverage available for the pair (currently the same on every chain it's listed on). A dash (—) means the pair is not currently listed. * Not all pairs are available for all chains and/or all collaterals * Pairs may be disabled automatically (temporarily) for reasons including, but not limited to, price feed anomalies, events that impact the underlying asset, etc | pairIndex | Pair | Asset Class | Max Leverage | Active | | --------- | -------------- | -------------- | ------------ | ------ | | 0 | BTC/USD | Crypto | 200x | ✅ | | 1 | ETH/USD | Crypto | 200x | ✅ | | 2 | LINK/USD | Crypto | 150x | ✅ | | 3 | DOGE/USD | Crypto | 150x | ✅ | | 4 | MATIC/USD | Crypto | — | ❌ | | 5 | ADA/USD | Crypto | 150x | ✅ | | 6 | SUSHI/USD | Crypto | — | ❌ | | 7 | AAVE/USD | Crypto | 150x | ✅ | | 8 | ALGO/USD | Crypto | 150x | ✅ | | 9 | BAT/USD | Crypto | 150x | ✅ | | 10 | COMP/USD | Crypto | 150x | ✅ | | 11 | DOT/USD | Crypto | 150x | ✅ | | 12 | EOS/USD | Crypto | — | ❌ | | 13 | LTC/USD | Crypto | 150x | ❌ | | 14 | MANA/USD | Crypto | 150x | ✅ | | 15 | OMG/USD | Crypto | — | ❌ | | 16 | SNX/USD | Crypto | — | ❌ | | 17 | UNI/USD | Crypto | 150x | ✅ | | 18 | XLM/USD | Crypto | 150x | ✅ | | 19 | XRP/USD | Crypto | 150x | ✅ | | 20 | ZEC/USD | Crypto | 150x | ✅ | | 21 | EUR/USD | Forex (Major) | 1000x | ✅ | | 22 | USD/JPY | Forex (Major) | 1000x | ✅ | | 23 | GBP/USD | Forex (Major) | 1000x | ✅ | | 24 | USD/CHF | Forex (Major) | — | ❌ | | 25 | AUD/USD | Forex (Major) | — | ❌ | | 26 | USD/CAD | Forex (Major) | 1000x | ✅ | | 27 | NZD/USD | Forex (Major) | — | ❌ | | 28 | EUR/CHF | Forex (Major) | — | ❌ | | 29 | EUR/JPY | Forex (Major) | — | ❌ | | 30 | EUR/GBP | Forex (Major) | — | ❌ | | 31 | LUNA/USD | Crypto | — | ❌ | | 32 | YFI/USD | Crypto | — | ❌ | | 33 | SOL/USD | Crypto | 150x | ✅ | | 34 | XTZ/USD | Crypto | 150x | ✅ | | 35 | BCH/USD | Crypto | 150x | ✅ | | 36 | BNT/USD | Crypto | — | ❌ | | 37 | CRV/USD | Crypto | 150x | ✅ | | 38 | DASH/USD | Crypto | 150x | ✅ | | 39 | ETC/USD | Crypto | 150x | ✅ | | 40 | ICP/USD | Crypto | 150x | ✅ | | 41 | MKR/USD | Crypto | — | ❌ | | 42 | NEO/USD | Crypto | — | ❌ | | 43 | THETA/USD | Crypto | 150x | ✅ | | 44 | TRX/USD | Crypto | 150x | ✅ | | 45 | ZRX/USD | Crypto | — | ❌ | | 46 | SAND/USD | Crypto | 150x | ✅ | | 47 | BNB/USD | Crypto | 150x | ✅ | | 48 | AXS/USD | Crypto | — | ❌ | | 49 | GRT/USD | Crypto | 150x | ✅ | | 50 | HBAR/USD | Crypto | 150x | ✅ | | 51 | XMR/USD | Crypto | 150x | ✅ | | 52 | ENJ/USD | Crypto | — | ❌ | | 53 | FTM/USD | Crypto | — | ❌ | | 54 | FTT/USD | Crypto | — | ❌ | | 55 | APE/USD | Crypto | 150x | ❌ | | 56 | CHZ/USD | Crypto | 150x | ✅ | | 57 | SHIB/USD | Crypto | 150x | ✅ | | 58 | AAPL/USD | Stocks | 50x | ✅ | | 59 | FB/USD | Stocks | — | ❌ | | 60 | GOOGL/USD | Stocks | — | ❌ | | 61 | AMZN/USD | Stocks | — | ❌ | | 62 | MSFT/USD | Stocks | 50x | ✅ | | 63 | TSLA/USD | Stocks | — | ❌ | | 64 | SNAP/USD | Stocks | 50x | ✅ | | 65 | NVDA/USD | Stocks | 50x | ✅ | | 66 | V/USD | Stocks | — | ❌ | | 67 | MA/USD | Stocks | — | ❌ | | 68 | PFE/USD | Stocks | — | ❌ | | 69 | KO/USD | Stocks | — | ❌ | | 70 | DIS/USD | Stocks | — | ❌ | | 71 | GME/USD | Stocks | — | ❌ | | 72 | NKE/USD | Stocks | — | ❌ | | 73 | AMD/USD | Stocks | — | ❌ | | 74 | PYPL/USD | Stocks | 50x | ✅ | | 75 | ABNB/USD | Stocks | — | ❌ | | 76 | BA/USD | Stocks | — | ❌ | | 77 | SBUX/USD | Stocks | — | ❌ | | 78 | WMT/USD | Stocks | — | ❌ | | 79 | INTC/USD | Stocks | — | ❌ | | 80 | MCD/USD | Stocks | 50x | ✅ | | 81 | META/USD | Stocks | 50x | ✅ | | 82 | GOOGL\_1/USD | Stocks | 50x | ✅ | | 83 | GME\_1/USD | Stocks | 50x | ✅ | | 84 | AMZN\_1/USD | Stocks | 50x | ✅ | | 85 | TSLA\_1/USD | Stocks | 50x | ✅ | | 86 | SPY/USD | Index | 100x | ✅ | | 87 | QQQ/USD | Index | 100x | ✅ | | 88 | IWM/USD | Index | 100x | ✅ | | 89 | DIA/USD | Index | 100x | ✅ | | 90 | XAU/USD | Commodity | 250x | ✅ | | 91 | XAG/USD | Commodity | 250x | ✅ | | 92 | USD/CNH | Forex (Exotic) | 500x | ✅ | | 93 | USD/SGD | Forex (Exotic) | 500x | ✅ | | 94 | EUR/SEK | Forex (Exotic) | — | ❌ | | 95 | USD/KRW | Forex (Exotic) | — | ❌ | | 96 | EUR/NOK | Forex (Exotic) | — | ❌ | | 97 | USD/INR | Forex (Exotic) | — | ❌ | | 98 | USD/MXN | Forex (Exotic) | — | ❌ | | 99 | USD/TWD | Forex (Exotic) | — | ❌ | | 100 | USD/ZAR | Forex (Exotic) | — | ❌ | | 101 | USD/BRL | Forex (Exotic) | — | ❌ | | 102 | AVAX/USD | Crypto | 150x | ✅ | | 103 | ATOM/USD | Crypto | 150x | ✅ | | 104 | NEAR/USD | Crypto | 150x | ✅ | | 105 | QNT/USD | Crypto | 150x | ✅ | | 106 | IOTA/USD | Crypto | — | ❌ | | 107 | TON/USD | Crypto | 150x | ✅ | | 108 | RPL/USD | Crypto | — | ❌ | | 109 | ARB/USD | Crypto | 150x | ✅ | | 110 | EUR/AUD | Forex (Minor) | 750x | ✅ | | 111 | EUR/NZD | Forex (Minor) | — | ❌ | | 112 | EUR/CAD | Forex (Minor) | — | ❌ | | 113 | GBP/AUD | Forex (Minor) | — | ❌ | | 114 | GBP/NZD | Forex (Minor) | — | ❌ | | 115 | GBP/CAD | Forex (Minor) | 750x | ✅ | | 116 | GBP/CHF | Forex (Minor) | — | ❌ | | 117 | GBP/JPY | Forex (Minor) | 750x | ✅ | | 118 | AUD/NZD | Forex (Minor) | — | ❌ | | 119 | AUD/CAD | Forex (Minor) | — | ❌ | | 120 | AUD/CHF | Forex (Minor) | — | ❌ | | 121 | AUD/JPY | Forex (Minor) | — | ❌ | | 122 | NZD/CAD | Forex (Minor) | — | ❌ | | 123 | NZD/CHF | Forex (Minor) | — | ❌ | | 124 | NZD/JPY | Forex (Minor) | — | ❌ | | 125 | CAD/CHF | Forex (Minor) | — | ❌ | | 126 | CAD/JPY | Forex (Minor) | — | ❌ | | 127 | CHF/JPY | Forex (Minor) | — | ❌ | | 128 | LDO/USD | Crypto | 150x | ✅ | | 129 | INJ/USD | Crypto | 150x | ✅ | | 130 | RUNE/USD | Crypto | — | ❌ | | 131 | CAKE/USD | Crypto | 150x | ✅ | | 132 | FXS/USD | Crypto | — | ❌ | | 133 | TWT/USD | Crypto | 150x | ✅ | | 134 | PEPE/USD | Crypto | 150x | ✅ | | 135 | DYDX/USD | Crypto | — | ❌ | | 136 | GMX/USD | Crypto | — | ❌ | | 137 | FIL/USD | Crypto | 150x | ✅ | | 138 | APT/USD | Crypto | 150x | ✅ | | 139 | IMX/USD | Crypto | 150x | ✅ | | 140 | VET/USD | Crypto | 150x | ✅ | | 141 | OP/USD | Crypto | 150x | ✅ | | 142 | RNDR/USD | Crypto | 150x | ✅ | | 143 | EGLD/USD | Crypto | 150x | ✅ | | 144 | TIA/USD | Crypto | 150x | ✅ | | 145 | STX/USD | Crypto | 150x | ✅ | | 146 | FLOW/USD | Crypto | — | ❌ | | 147 | KAVA/USD | Crypto | — | ❌ | | 148 | GALA/USD | Crypto | 150x | ✅ | | 149 | MINA/USD | Crypto | — | ❌ | | 150 | ORDI/USD | Crypto | — | ❌ | | 151 | ILV/USD | Crypto | — | ❌ | | 152 | KLAY/USD | Crypto | — | ❌ | | 153 | SUI/USD | Crypto | 150x | ✅ | | 154 | BLUR/USD | Crypto | — | ❌ | | 155 | FET/USD | Crypto | 150x | ✅ | | 156 | CFX/USD | Crypto | 150x | ✅ | | 157 | BEAM/USD | Crypto | — | ❌ | | 158 | AR/USD | Crypto | 150x | ✅ | | 159 | SEI/USD | Crypto | 150x | ✅ | | 160 | BTT/USD | Crypto | — | ❌ | | 161 | ROSE/USD | Crypto | — | ❌ | | 162 | WOO/USD | Crypto | — | ❌ | | 163 | AGIX/USD | Crypto | — | ❌ | | 164 | ZIL/USD | Crypto | — | ❌ | | 165 | GMT/USD | Crypto | — | ❌ | | 166 | ASTR/USD | Crypto | — | ❌ | | 167 | 1INCH/USD | Crypto | 150x | ✅ | | 168 | FLOKI/USD | Crypto | 150x | ✅ | | 169 | QTUM/USD | Crypto | — | ❌ | | 170 | OCEAN/USD | Crypto | — | ❌ | | 171 | WLD/USD | Crypto | 150x | ✅ | | 172 | MASK/USD | Crypto | — | ❌ | | 173 | CELO/USD | Crypto | — | ❌ | | 174 | LRC/USD | Crypto | — | ❌ | | 175 | ENS/USD | Crypto | 150x | ✅ | | 176 | MEME/USD | Crypto | — | ❌ | | 177 | ANKR/USD | Crypto | — | ❌ | | 178 | IOTX/USD | Crypto | — | ❌ | | 179 | ICX/USD | Crypto | — | ❌ | | 180 | KSM/USD | Crypto | — | ❌ | | 181 | RVN/USD | Crypto | — | ❌ | | 182 | ANT/USD | Crypto | — | ❌ | | 183 | WAVES/USD | Crypto | — | ❌ | | 184 | SKL/USD | Crypto | — | ❌ | | 185 | SUPER/USD | Crypto | — | ❌ | | 186 | BAL/USD | Crypto | — | ❌ | | 187 | WTI/USD | Commodity | 150x | ✅ | | 188 | XPT/USD | Commodity | 150x | ✅ | | 189 | XPD/USD | Commodity | — | ❌ | | 190 | HG/USD | Commodity | 250x | ✅ | | 191 | JUP/USD | Crypto | 150x | ✅ | | 192 | MANTA/USD | Crypto | — | ❌ | | 193 | BONK/USD | Crypto | 150x | ✅ | | 194 | PENDLE/USD | Crypto | 150x | ✅ | | 195 | OSMO/USD | Crypto | — | ❌ | | 196 | ALT/USD | Crypto | — | ❌ | | 197 | UMA/USD | Crypto | — | ❌ | | 198 | MAGIC/USD | Crypto | — | ❌ | | 199 | API3/USD | Crypto | — | ❌ | | 200 | STRK/USD | Crypto | 150x | ✅ | | 201 | DYM/USD | Crypto | — | ❌ | | 202 | NTRN/USD | Crypto | — | ❌ | | 203 | PYTH/USD | Crypto | 150x | ✅ | | 204 | SC/USD | Crypto | — | ❌ | | 205 | WIF/USD | Crypto | 150x | ✅ | | 206 | PIXEL/USD | Crypto | — | ❌ | | 207 | JTO/USD | Crypto | — | ❌ | | 208 | MAVIA/USD | Crypto | — | ❌ | | 209 | MYRO/USD | Crypto | — | ❌ | | 210 | STG/USD | Crypto | — | ❌ | | 211 | BOME/USD | Crypto | — | ❌ | | 212 | ETHFI/USD | Crypto | 150x | ✅ | | 213 | METIS/USD | Crypto | — | ❌ | | 214 | AEVO/USD | Crypto | — | ❌ | | 215 | ONDO/USD | Crypto | 150x | ✅ | | 216 | MNT/USD | Crypto | 150x | ✅ | | 217 | KAS/USD | Crypto | 150x | ✅ | | 218 | RONIN/USD | Crypto | — | ❌ | | 219 | ENA/USD | Crypto | 150x | ✅ | | 220 | W/USD | Crypto | — | ❌ | | 221 | ZEUS/USD | Crypto | — | ❌ | | 222 | TNSR/USD | Crypto | — | ❌ | | 223 | TAO/USD | Crypto | 150x | ✅ | | 224 | OMNI/USD | Crypto | — | ❌ | | 225 | PRCL/USD | Crypto | — | ❌ | | 226 | MERL/USD | Crypto | — | ❌ | | 227 | SAFE/USD | Crypto | — | ❌ | | 228 | SAGA/USD | Crypto | — | ❌ | | 229 | LL/USD | Crypto | — | ❌ | | 230 | MSN/USD | Crypto | — | ❌ | | 231 | REZ/USD | Crypto | — | ❌ | | 232 | NOT/USD | Crypto | — | ❌ | | 233 | IO/USD | Crypto | — | ❌ | | 234 | BRETT/USD | Crypto | — | ❌ | | 235 | ATH/USD | Crypto | — | ❌ | | 236 | ZRO/USD | Crypto | 150x | ✅ | | 237 | ZK/USD | Crypto | — | ❌ | | 238 | LISTA/USD | Crypto | — | ❌ | | 239 | BLAST/USD | Crypto | — | ❌ | | 240 | RATS/USD | Crypto | — | ❌ | | 241 | BNX/USD | Crypto | — | ❌ | | 242 | PEOPLE/USD | Crypto | — | ❌ | | 243 | TURBO/USD | Crypto | — | ❌ | | 244 | SATS/USD | Crypto | — | ❌ | | 245 | POPCAT/USD | Crypto | — | ❌ | | 246 | MOG/USD | Crypto | — | ❌ | | 247 | OM/USD | Crypto | — | ❌ | | 248 | CORE/USD | Crypto | — | ❌ | | 249 | JASMY/USD | Crypto | 150x | ✅ | | 250 | DAR/USD | Crypto | — | ❌ | | 251 | MEW/USD | Crypto | — | ❌ | | 252 | DEGEN/USD | Crypto | — | ❌ | | 253 | SLERF/USD | Crypto | — | ❌ | | 254 | UXLINK/USD | Crypto | — | ❌ | | 255 | AVAIL/USD | Crypto | — | ❌ | | 256 | BANANA/USD | Crypto | — | ❌ | | 257 | RARE/USD | Crypto | — | ❌ | | 258 | SYS/USD | Crypto | — | ❌ | | 259 | NMR/USD | Crypto | — | ❌ | | 260 | RSR/USD | Crypto | — | ❌ | | 261 | SYN/USD | Crypto | — | ❌ | | 262 | AUCTION/USD | Crypto | — | ❌ | | 263 | ALICE/USD | Crypto | — | ❌ | | 264 | SUN/USD | Crypto | 150x | ✅ | | 265 | TRB/USD | Crypto | — | ❌ | | 266 | DOGS/USD | Crypto | — | ❌ | | 267 | SSV/USD | Crypto | — | ❌ | | 268 | PONKE/USD | Crypto | — | ❌ | | 269 | POL/USD | Crypto | 150x | ✅ | | 270 | RDNT/USD | Crypto | — | ❌ | | 271 | FLUX/USD | Crypto | — | ❌ | | 272 | NEIRO/USD | Crypto | — | ❌ | | 273 | SUNDOG/USD | Crypto | — | ❌ | | 274 | CAT/USD | Crypto | — | ❌ | | 275 | BABYDOGE/USD | Crypto | — | ❌ | | 276 | REEF/USD | Crypto | — | ❌ | | 277 | CKB/USD | Crypto | — | ❌ | | 278 | CATI/USD | Crypto | — | ❌ | | 279 | LOOM/USD | Crypto | — | ❌ | | 280 | ZETA/USD | Crypto | — | ❌ | | 281 | HMSTR/USD | Crypto | — | ❌ | | 282 | EIGEN/USD | Crypto | 150x | ✅ | | 283 | POLYX/USD | Crypto | — | ❌ | | 284 | MOODENG/USD | Crypto | — | ❌ | | 285 | MOTHER/USD | Crypto | — | ❌ | | 286 | AERO/USD | Crypto | 150x | ✅ | | 287 | CVC/USD | Crypto | — | ❌ | | 288 | NEIROCTO/USD | Crypto | — | ❌ | | 289 | ARK/USD | Crypto | — | ❌ | | 290 | NPC/USD | Crypto | — | ❌ | | 291 | ORBS/USD | Crypto | — | ❌ | | 292 | APU/USD | Crypto | — | ❌ | | 293 | BSV/USD | Crypto | 150x | ✅ | | 294 | HIPPO/USD | Crypto | — | ❌ | | 295 | GOAT/USD | Crypto | — | ❌ | | 296 | DOG/USD | Crypto | — | ❌ | | 297 | HOT/USD | Crypto | — | ❌ | | 298 | STORJ/USD | Crypto | — | ❌ | | 299 | RAY/USD | Crypto | 150x | ✅ | | 300 | BTCDEGEN/USD | Crypto | 500x | ✅ | | 301 | PNUT/USD | Crypto | — | ❌ | | 302 | ACT/USD | Crypto | — | ❌ | | 303 | GRASS/USD | Crypto | — | ❌ | | 304 | ZEN/USD | Crypto | 150x | ✅ | | 305 | LUMIA/USD | Crypto | — | ❌ | | 306 | ALPH/USD | Crypto | — | ❌ | | 307 | VIRTUAL/USD | Crypto | 150x | ✅ | | 308 | SPX/USD | Crypto | — | ❌ | | 309 | ACX/USD | Crypto | — | ❌ | | 310 | CHILLGUY/USD | Crypto | — | ❌ | | 311 | CHEX/USD | Crypto | — | ❌ | | 312 | BITCOIN/USD | Crypto | — | ❌ | | 313 | ETHDEGEN/USD | Crypto | 500x | ✅ | | 314 | SOLDEGEN/USD | Crypto | 500x | ✅ | | 315 | MOVE/USD | Crypto | — | ❌ | | 316 | ME/USD | Crypto | — | ❌ | | 317 | COW/USD | Crypto | — | ❌ | | 318 | AVA/USD | Crypto | — | ❌ | | 319 | USUAL/USD | Crypto | — | ❌ | | 320 | PENGU/USD | Crypto | 150x | ✅ | | 321 | FARTCOIN/USD | Crypto | 150x | ✅ | | 322 | ZEREBRO/USD | Crypto | — | ❌ | | 323 | AI16Z/USD | Crypto | — | ❌ | | 324 | AIXBT/USD | Crypto | — | ❌ | | 325 | BIO/USD | Crypto | — | ❌ | | 326 | XRPDEGEN/USD | Crypto | — | ❌ | | 327 | BNBDEGEN/USD | Crypto | 500x | ✅ | | 328 | TRUMP/USD | Crypto | 150x | ✅ | | 329 | MELANIA/USD | Crypto | 150x | ✅ | | 330 | MODE/USD | Crypto | — | ❌ | | 331 | HYPE/USD | Crypto | 150x | ✅ | | 332 | S/USD | Crypto | 150x | ✅ | | 333 | ARC/USD | Crypto | — | ❌ | | 334 | ARKM/USD | Crypto | — | ❌ | | 335 | GRIFFAIN/USD | Crypto | — | ❌ | | 336 | SWARMS/USD | Crypto | — | ❌ | | 337 | ANIME/USD | Crypto | — | ❌ | | 338 | PLUME/USD | Crypto | — | ❌ | | 339 | VVV/USD | Crypto | 150x | ✅ | | 340 | VINE/USD | Crypto | — | ❌ | | 341 | TOSHI/USD | Crypto | — | ❌ | | 342 | BERA/USD | Crypto | — | ❌ | | 343 | LAYER/USD | Crypto | — | ❌ | | 344 | CHEEMS/USD | Crypto | — | ❌ | | 345 | SOLV/USD | Crypto | — | ❌ | | 346 | TST/USD | Crypto | — | ❌ | | 347 | IP/USD | Crypto | — | ❌ | | 348 | KAITO/USD | Crypto | — | ❌ | | 349 | ELX/USD | Crypto | — | ❌ | | 350 | PI/USD | Crypto | — | ❌ | | 351 | SHELL/USD | Crypto | — | ❌ | | 352 | BMT/USD | Crypto | — | ❌ | | 353 | BROCCOLI/USD | Crypto | — | ❌ | | 354 | TUT/USD | Crypto | — | ❌ | | 355 | GPS/USD | Crypto | — | ❌ | | 356 | RED/USD | Crypto | — | ❌ | | 357 | MUBARAK/USD | Crypto | — | ❌ | | 358 | FORM/USD | Crypto | — | ❌ | | 359 | WAL/USD | Crypto | — | ❌ | | 360 | NIL/USD | Crypto | — | ❌ | | 361 | PARTI/USD | Crypto | — | ❌ | | 362 | SIREN/USD | Crypto | — | ❌ | | 363 | BANANAS31/USD | Crypto | 150x | ✅ | | 364 | HYPER/USD | Crypto | — | ❌ | | 365 | PROMPT/USD | Crypto | — | ❌ | | 366 | RFC/USD | Crypto | — | ❌ | | 367 | WCT/USD | Crypto | — | ❌ | | 368 | BIGTIME/USD | Crypto | — | ❌ | | 369 | BABY/USD | Crypto | — | ❌ | | 370 | COOKIE/USD | Crypto | — | ❌ | | 371 | KMNO/USD | Crypto | — | ❌ | | 372 | INIT/USD | Crypto | — | ❌ | | 373 | SYRUP/USD | Crypto | 150x | ✅ | | 374 | SIGN/USD | Crypto | — | ❌ | | 375 | ZORA/USD | Crypto | — | ❌ | | 376 | COIN/USD | Stocks | 50x | ✅ | | 377 | HOOD/USD | Stocks | 50x | ✅ | | 378 | MSTR/USD | Stocks | 50x | ✅ | | 379 | NFLX/USD | Stocks | — | ❌ | | 380 | LAUNCHCOIN/USD | Crypto | — | ❌ | | 381 | NXPC/USD | Crypto | — | ❌ | | 382 | SOPH/USD | Crypto | — | ❌ | | 383 | LPT/USD | Crypto | 150x | ✅ | | 384 | BVIV/USD | Crypto | 100x | ✅ | | 385 | EVIV/USD | Crypto | 100x | ✅ | | 386 | CRCL/USD | Stocks | 50x | ✅ | | 387 | RESOLV/USD | Crypto | — | ❌ | | 388 | SQD/USD | Crypto | — | ❌ | | 389 | TAIKO/USD | Crypto | — | ❌ | | 390 | HOME/USD | Crypto | — | ❌ | | 391 | B/USD | Crypto | 150x | ✅ | | 392 | HUMA/USD | Crypto | — | ❌ | | 393 | SBET/USD | Stocks | — | ❌ | | 394 | PLTR/USD | Stocks | 50x | ✅ | | 395 | BIDU/USD | Stocks | — | ❌ | | 396 | ROKU/USD | Stocks | — | ❌ | | 397 | LMT/USD | Stocks | 50x | ✅ | | 398 | RIOT/USD | Stocks | 25x | ✅ | | 399 | MARA/USD | Stocks | 25x | ✅ | | 400 | LOKA/USD | Crypto | — | ❌ | | 401 | STO/USD | Crypto | — | ❌ | | 402 | FUN/USD | Crypto | — | ❌ | | 403 | KNC/USD | Crypto | — | ❌ | | 404 | H/USD | Crypto | 150x | ✅ | | 405 | ICNT/USD | Crypto | — | ❌ | | 406 | NEWT/USD | Crypto | — | ❌ | | 407 | PUMP/USD | Crypto | 150x | ✅ | | 408 | SAROS/USD | Crypto | — | ❌ | | 409 | SPK/USD | Crypto | — | ❌ | | 410 | ERA/USD | Crypto | — | ❌ | | 411 | BGSC/USD | Crypto | — | ❌ | | 412 | TAG/USD | Crypto | — | ❌ | | 413 | WLFI/USD | Crypto | 150x | ✅ | | 414 | ASTER/USD | Crypto | 150x | ✅ | | 415 | OKB/USD | Crypto | 150x | ✅ | | 416 | CRO/USD | Crypto | 150x | ✅ | | 417 | SKY/USD | Crypto | 150x | ✅ | | 418 | XPL/USD | Crypto | 150x | ✅ | | 419 | AVNT/USD | Crypto | — | ❌ | | 420 | APEX/USD | Crypto | — | ❌ | | 421 | ORDER/USD | Crypto | — | ❌ | | 422 | DRIFT/USD | Crypto | — | ❌ | | 423 | MYX/USD | Crypto | — | ❌ | | 424 | NOM/USD | Crypto | — | ❌ | | 425 | FLUID/USD | Crypto | 150x | ✅ | | 426 | LQTY/USD | Crypto | — | ❌ | | 427 | L3/USD | Crypto | — | ❌ | | 428 | CAMP/USD | Crypto | — | ❌ | | 429 | SOMI/USD | Crypto | — | ❌ | | 430 | HEMI/USD | Crypto | — | ❌ | | 431 | FF/USD | Crypto | — | ❌ | | 432 | USELESS/USD | Crypto | — | ❌ | | 433 | MON/USD | Crypto | 150x | ✅ | | 434 | MET/USD | Crypto | — | ❌ | | 435 | TURTLE/USD | Crypto | — | ❌ | | 436 | SPX500/USD | Index | — | ❌ | | 437 | NAS100/USD | Index | — | ❌ | | 438 | USA30/USD | Index | — | ❌ | | 439 | NFLX\_1/USD | Stocks | 50x | ✅ | | 440 | STABLE/USD | Crypto | — | ❌ | | 441 | VOOI/USD | Crypto | — | ❌ | | 442 | LIT/USD | Crypto | 150x | ✅ | | 443 | DUSK/USD | Crypto | — | ❌ | | 444 | SCRT/USD | Crypto | — | ❌ | | 445 | DCR/USD | Crypto | 150x | ✅ | | 446 | GDX/USD | Index | 100x | ✅ | | 447 | URA/USD | Index | 100x | ✅ | | 448 | WPM/USD | Stocks | 50x | ✅ | | 449 | NATGAS/USD | Commodity | — | ❌ | | 450 | BRENT/USD | Commodity | — | ❌ | | 451 | URNM/USD | Index | 100x | ✅ | | 452 | HYPEDEGEN/USD | Crypto | 500x | ✅ | | 453 | MEGA/USD | Crypto | 150x | ✅ | | 454 | SPCX/USD | Stocks | 50x | ✅ | | 455 | RE/USD | Crypto | 150x | ✅ | | 456 | O/USD | Crypto | 150x | ✅ | | 457 | BP/USD | Crypto | 150x | ✅ | | 458 | AVGO/USD | Stocks | 50x | ✅ | | 459 | SNDK/USD | Stocks | 50x | ✅ | | 460 | MU/USD | Stocks | 50x | ✅ | | 461 | MRVL/USD | Stocks | 50x | ✅ | | 462 | CHIP/USD | Crypto | 150x | ✅ | | 463 | CAP/USD | Crypto | 150x | ✅ | | 464 | SAMSUNG/USD | Stocks | 50x | ✅ | | 465 | SKHYNIX/USD | Stocks | 50x | ✅ | | 466 | ZECDEGEN/USD | Crypto | 500x | ✅ | | 467 | ANSEM/USD | Crypto | 150x | ✅ | | 468 | BOT/USD | Stocks | 50x | ✅ | | 469 | BB/USD | Stocks | 50x | ✅ | | 470 | LPTH/USD | Stocks | 50x | ✅ | | 471 | ABCL/USD | Stocks | 50x | ✅ | | 472 | IOVA/USD | Stocks | 50x | ✅ | | 473 | XDC/USD | Crypto | 150x | ✅ | | 474 | ADI/USD | Crypto | 150x | ✅ | | 475 | BRUN/USD | Stocks | 50x | ✅ | | 476 | WYFI/USD | Stocks | 50x | ✅ | | 477 | SHAZ/USD | Stocks | 50x | ✅ | | 478 | BE/USD | Stocks | 50x | ✅ | | 479 | NBIS/USD | Stocks | 50x | ✅ | | 480 | CRWV/USD | Stocks | 50x | ✅ | | 481 | IREN/USD | Stocks | 50x | ✅ | # Setting up to trade Source: https://docs.gains.trade/gtrade-leveraged-trading/setting-up-to-trade Set up your wallet, fund it, and connect to supported Gains networks. To trade, connect your wallet to one of the networks where Gains is deployed. Use these guides to set up the main supported networks: * [Polygon Network Setup](/gtrade-leveraged-trading/setting-up-to-trade/polygon-network-setup) * Lowest gas costs * Supports lower position sizes * Requires 2 block confirmation (4 seconds) * Occasional reorgs * [Arbitrum Network Setup](/gtrade-leveraged-trading/setting-up-to-trade/arbitrum-network-setup) * No block confirmations required * Fastest transactions * Slightly higher transaction cost * Higher minimum position size required Gains is also deployed on **Base** and **MegaETH**. The setup flow is the same as above: add the network to your wallet (the easiest way is via [chainlist.org](https://chainlist.org)), fund it with the network's gas token and a supported collateral (see [Trade Collaterals](/gtrade-leveraged-trading/trade-collaterals)), then connect to [gains.trade](https://gains.trade). Prefer Solana? You can trade directly from your Solana wallet on [sol.gains.trade](https://sol.gains.trade/) — see [Gains Solana](/gtrade-leveraged-trading/gtrade-solana). ### # Arbitrum Network Setup Source: https://docs.gains.trade/gtrade-leveraged-trading/setting-up-to-trade/arbitrum-network-setup Add Arbitrum to your wallet and fund it to trade on Gains. When you select Arbitrum in the trading interface, your wallet will prompt you to add the network if it is not already configured. ### What is Arbitrum One/Nitro/Nova? How does it differ from Ethereum? Arbitrum One and Arbitrum Nova are networks developed by Offchain Labs. Both run on Nitro. Gains is deployed on Arbitrum One. For more detail, see Offchain Labs' articles on [Nitro](https://medium.com/offchainlabs/arbitrum-nitro-one-small-step-for-l2-one-giant-leap-for-ethereum-bc9108047450) and [Arbitrum Nova](https://medium.com/offchainlabs/introducing-nova-arbitrum-anytrust-mainnet-is-open-for-developers-9a54692f345e). ### Arbitrum MetaMask Setup To add Arbitrum automatically to MetaMask, go to [Arbiscan](https://arbiscan.io/), scroll to the bottom, and click **Add Network**. *Scroll to the bottom to see the button to add Arbitrum.* See below for more information on RPC endpoints. After setup, you can switch between Ethereum and Arbitrum in MetaMask. ### Getting Funds to Arbitrum Arbitrum uses ETH as the native currency to pay for transactions, including to manage trades on Gains. If you don't have any assets on Arbitrum, there are a number of ways to move them there. 1. **The official bridge is** [**Arbitrum bridge**](https://bridge.arbitrum.io/)**.** This takes about 10 minutes. 2. For bridging **GNS** the bridge can be found on the [bridging page](https://gains.trade/bridge). 3. You can use a third-party bridge to bridge from other chains. **Use caution with any bridge**. Confirm links from the service's official website or communication channels before connecting your wallet. * Bungee: [https://bungee.exchange/](https://bungee.exchange/) * Synapse: [https://synapseprotocol.com/](https://synapseprotocol.com/) * Connext: [https://bridge.connext.network/](https://bridge.connext.network/) 4. Some centralized exchanges support withdrawing ETH to Arbitrum. \ Ensure you have selected Arbitrum One as the chain to withdraw to and not Ethereum. ### RPC Endpoints RPCs are what MetaMask uses to connect to the blockchain, fetch information, and send transactions. Public RPCs are the easiest way to access Arbitrum. During high usage, gas costs can rise and public RPCs can become congested. If you trade with large collateral amounts, using your own endpoint can improve reliability. The trading interface does not rely on your MetaMask RPC to display trades. It uses dedicated RPC infrastructure and streams data to the frontend. Your MetaMask RPC is mainly used to send transactions. If you use public RPCs, keep more than one available in MetaMask so you can switch quickly if one becomes slow. Public RPCs: * [https://arb1.arbitrum.io/rpc](https://arb1.arbitrum.io/rpc) * [https://arbitrum.public-rpc.com](https://arbitrum.public-rpc.com) You can get your own Arbitrum endpoint from infrastructure providers such as: * [https://moralis.io/](https://moralis.io/) * [https://chainstack.com/](https://chainstack.com/) * [https://www.alchemy.com/](https://www.alchemy.com/) * [https://www.quicknode.com/](https://www.quicknode.com/) * [https://getblock.io/](https://getblock.io/) * [https://infura.io/](https://infura.io/) # Polygon Network Setup Source: https://docs.gains.trade/gtrade-leveraged-trading/setting-up-to-trade/polygon-network-setup Add Polygon to your wallet and fund it to trade on Gains. ### Polygon MetaMask Setup To add Polygon automatically to MetaMask, go to [Polygonscan](https://polygonscan.com/), scroll to the bottom, and click **Add Network**. *Scroll to the bottom of the page to see the button.* To add it manually, see the [Polygon documentation on set up](https://wiki.polygon.technology/docs/develop/metamask/config-polygon-on-metamask/). See below for more information on RPC endpoints. After setup, you can switch between Ethereum and Polygon in MetaMask. ### Getting Funds to Polygon Polygon uses the native token MATIC to pay for transactions, including to manage trades on Gains. If you don't have any MATIC tokens yet, you can claim a small amount of MATIC for free on [matic.supply](https://matic.supply/). You can then convert other assets to MATIC on Quickswap to have more MATIC for transactions. If you don't have any other assets on Polygon, there are a number of ways to move them there. 1. Bridge funds from Ethereum using the [Polygon Bridge](https://wallet.polygon.technology/).\ This takes about 10 minutes. 2. Bridge funds using another bridging solution. 3. Most centralized exchanges support withdrawing MATIC to Polygon. \ Ensure you have selected Polygon as the chain to withdraw to and not Ethereum. ### RPC Endpoints RPCs are what MetaMask uses to connect to the blockchain, fetch information, and send transactions. Public RPCs are the easiest way to access Polygon. During high usage, gas costs can rise and public RPCs can become congested. If you trade with large collateral amounts, using your own endpoint can improve reliability. The trading interface does not rely on your MetaMask RPC to display trades. It uses dedicated RPC infrastructure and streams data to the frontend. Your MetaMask RPC is mainly used to send transactions. If you use public RPCs, keep more than one available in MetaMask so you can switch quickly if one becomes slow. Public RPCs: * [https://rpc-mainnet.matic.quiknode.pro/](https://rpc-mainnet.matic.quiknode.pro/) * [https://public-rpc.blockpi.io/http/polygon](https://public-rpc.blockpi.io/http/polygon) * [https://polygon-rpc.com/](https://polygon-rpc.com/) * [https://rpc-mainnet.matic.network](https://rpc-mainnet.matic.network) * [https://matic-mainnet.chainstacklabs.com](https://matic-mainnet.chainstacklabs.com) You can get your own Polygon endpoint from infrastructure providers such as: * [https://moralis.io/](https://moralis.io/) * [https://chainstack.com/](https://chainstack.com/) * [https://www.alchemy.com/](https://www.alchemy.com/) * [https://www.quicknode.com/](https://www.quicknode.com/) * [https://getblock.io/](https://getblock.io/) * [https://infura.io/](https://infura.io/) For instance, for a free Chainstack endpoint: 1. Go to [chainstack.com](https://chainstack.com/), sign up, and open your dashboard. 2. Click **Create project**, enter a name, leave it as a public chain, and create it. 3. Open your project, click **Add a node**, and set it to Polygon mainnet. 4. Wait a few minutes for the node to be created, then open it. 5. Copy the HTTPS endpoint and create a new MetaMask network for Polygon using it as the RPC URL. 6. You can now use that RPC endpoint for Polygon transactions. # Trade Collaterals Source: https://docs.gains.trade/gtrade-leveraged-trading/trade-collaterals Gains offers multiple collateral options Gains offers \$USDC, \$DAI, \$WETH, and \$USDm for trading, enhancing flexibility and user choice. (Please note that not all collaterals are available on every chain.) #### Collateral availability by chain | Chain | Collaterals | | -------- | --------------------- | | Arbitrum | \$USDC, \$DAI, \$WETH | | Polygon | \$USDC, \$DAI, \$WETH | | Base | \$USDC, \$BtcUSD | | MegaETH | \$USDm | Gains Solana ([sol.gains.trade](https://sol.gains.trade/)) is a separate deployment — see [Gains Solana](/gtrade-leveraged-trading/gtrade-solana). Each collateral is backed by its own gToken vault — the up-to-date list of vault contracts per chain is on [Contract Addresses](/what-is-gains-network/contract-addresses). #### Key Features: 1. **Synthetic Trading Flexibility**: Gains follows a synthetic trading architecture, allowing traders to trade using \$USDC, \$DAI, or \$WETH as collateral. This innovative approach means you're not buying or selling the underlying assets directly but are instead trading on their price movements. 2. **Fees in Collateral**: Trading fees are paid in the collateral used, streamlining transactions and aligning with your trading strategy. 3. **Risk Management**: Gains manages risk at a collateral level, as each is backed by its own gToken vault and separate liquidity. Meaning that if \$USDC open interest were to be maxed out, this would not affect the open interest for other collaterals. 4. **Collateral-based Position Sizing**: Position size is determined in the collateral type, not the traded asset nor its notional value. This approach simplifies liquidation risk management by keeping the position size constant, independent of collateral price movements, making trading strategies clearer and more predictable (more details on the next page). #### Advantages: Our model eases liquidation risk management. Unlike traditional exchanges where a position's leverage and liquidation risk fluctuate with collateral price changes, our stable model allows for better strategy planning and a stress-reduced trading experience. By offering diverse collateral options and simplifying fees and risk management, we aim to improve the trading experience, empowering traders with control and flexibility in their strategies. #### Maximum available interest (max OI) The max OI is a separate value for each vault. It is calculated as follows: `maxOi` = `(vaultExposure * vaultTvl / avgDailyAtr^atrExponent * atrMultiplier) * oiFactor / correlation * logPairCount` where: * `vaultExposure` = adjustable constant * `vaultTvl` = `tvl + 5 * overCollat + .15 * (gnsMarketCap * (tvl + 5 * overCollat) / (allVaultTvls + 5 * allVaultOverCollats))` * `avgDailyAtr` = computed from past 5 day candles * `atrExponent` = adjustable constant * `atrMultiplier` = adjustable constant * `oiFactor` = \[0,1] - a throttle on OI based on group or pair * `correlation` = \[0,1] - avg correlation of pairs in group, or just 1 if pair * `logPairCount` = `numPairsInGroup^.25` # Spotlight: WETH Source: https://docs.gains.trade/gtrade-leveraged-trading/trade-collaterals/spotlight-weth Execution differences between Gains and a traditional centralized exchange. This example uses \$ETH for readability, although Gains uses \$WETH. There is an important difference between centralized exchanges and Gains: * On many centralized exchanges, ETH collateral opens a position with fixed size in the underlying asset. Current leverage changes with both the pair price and the ETH price, so the liquidation price can also move with ETH. * On Gains, ETH collateral opens a position with a **fixed size in ETH terms**. The underlying token amount can vary, but the liquidation price remains independent from ETH price changes. Illustrative example: * Trader1 has 1 ETH as collateral on a CEX * Trader2 has 1 ETH as collateral on Gains * ETH price = \$2,000 * Both traders want to open a 10x long position on the pair TIA * TIA price = \$10 *** On the **centralized exchange**, Trader 1 opens a 10x long on TIA. His position size is 2,000 TIA (notional position size = \$20,000 at inception). This position size does not change during the life-cycle of the position. If ETH drops to \$1,900, his position size is still 2,000 TIA. On the centralized exchange, current leverage depends on both ETH and TIA prices, and the liquidation price also depends on ETH. When ETH drops to \$1,900, the trader's liquidation price moves closer. *** On **Gains**, Trader 2 opens a 10x long on TIA. His position size is 10 ETH (notional position size = \$20,000) = 2,000 TIA. The position size in ETH does not change during the lifecycle of the position, but the TIA amount is variable. To illustrate this, assume the price of ETH is now \$1,900 and TIA price remains unchanged at \$10. His 10 ETH position is now equivalent to a \$19,000 notional position, or 1,900 TIA. Conversely, if ETH increases to \$2,100 while TIA is unchanged, his 10 ETH position is equivalent to a \$21,000 notional position, or 2,100 TIA. *** In scenario 1, ETH decreases and the notional position size decreases. The trader loses less if TIA falls, but also earns less if TIA rises. In scenario 2, ETH increases and the notional position size increases. The trader earns more if TIA rises, but also loses more if TIA falls. In both scenarios, the liquidation price remains unchanged because it is independent from ETH price movement. This makes liquidation risk easier to manage. # Video tutorials Source: https://docs.gains.trade/gtrade-leveraged-trading/video-tutorials A list of YouTube videos to learn more about Gains. ### **What is \$GNS?** \$GNS is the token that powers the Gains ecosystem. It combines utility, deflationary tokenomics with real yield, and governance rights — giving holders the full package: