-
Notifications
You must be signed in to change notification settings - Fork 177
feat: add bundle flow for future sol-native flow #7984
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
limitofzero
wants to merge
12
commits into
develop
Choose a base branch
from
feat/implement-bundle-flow
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
2bcd832
feat: add bundle flow for future sol-native flow
limitofzero 700ee49
chore(i18n): extract i18n strings [automatic]
cowswap-release-sync[bot] fe98470
feat: change btn label
limitofzero be112cf
Merge branch 'feat/implement-bundle-flow' of github.com:cowprotocol/c…
limitofzero b244fa5
chore(i18n): extract i18n strings [automatic]
cowswap-release-sync[bot] 4a7678c
Merge branch 'develop' into feat/implement-bundle-flow
limitofzero 017eb40
chore(i18n): extract i18n strings [automatic]
cowswap-release-sync[bot] abd0c90
refactor: clean up comments
limitofzero 8ffa77a
Merge branch 'feat/implement-bundle-flow' of github.com:cowprotocol/c…
limitofzero 5657aeb
fix: remove rent from instruction + normalize errors
limitofzero b1c7a5b
Merge branch 'develop' into feat/implement-bundle-flow
limitofzero 12c927b
chore(i18n): extract i18n strings [automatic]
cowswap-release-sync[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
51 changes: 51 additions & 0 deletions
51
apps/cowswap-frontend/src/modules/trade/containers/SolanaWrapAndDelegateButton/index.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import { ReactNode, useState } from 'react' | ||
|
|
||
| import { usePreventDoubleExecution } from '@cowprotocol/common-hooks' | ||
| import { normalizeError } from '@cowprotocol/common-utils' | ||
| import { ButtonError, ButtonSize, HelpTooltip, TokenSymbol } from '@cowprotocol/ui' | ||
|
|
||
| import { Trans } from '@lingui/react/macro' | ||
|
|
||
| import { useDerivedTradeState } from '../../hooks/useDerivedTradeState' | ||
| import { useSolanaWrapAndDelegateCallback } from '../../hooks/useSolanaWrapAndDelegateCallback' | ||
|
|
||
| export interface SolanaWrapAndDelegateButtonProps { | ||
| isDisabled?: boolean | ||
| clickEvent?: string | ||
| } | ||
|
|
||
| export function SolanaWrapAndDelegateButton({ isDisabled, clickEvent }: SolanaWrapAndDelegateButtonProps): ReactNode { | ||
| const state = useDerivedTradeState() | ||
| const sellAmount = state?.inputCurrencyAmount ? BigInt(state.inputCurrencyAmount.quotient.toString()) : undefined | ||
| const wrapAndDelegate = useSolanaWrapAndDelegateCallback(sellAmount) | ||
| const [error, setError] = useState<string | null>(null) | ||
|
|
||
| const { callback: onClick, isExecuting } = usePreventDoubleExecution(async () => { | ||
| setError(null) | ||
|
|
||
| try { | ||
| await wrapAndDelegate?.() | ||
| } catch (err: unknown) { | ||
| const error = normalizeError(err) | ||
|
|
||
| setError(error.message) | ||
| } | ||
| }) | ||
|
|
||
| return ( | ||
| <ButtonError | ||
| id="do-trade-button" | ||
| buttonSize={ButtonSize.BIG} | ||
| onClick={onClick} | ||
| disabled={isDisabled || !wrapAndDelegate || isExecuting} | ||
| data-click-event={clickEvent} | ||
| > | ||
| <div> | ||
| <Trans> | ||
| Wrap <TokenSymbol token={state?.inputCurrency} length={6} /> and Swap | ||
| </Trans> | ||
| {error && <HelpTooltip placement="top" text={<div>{error}</div>} />} | ||
| </div> | ||
| </ButtonError> | ||
| ) | ||
| } |
41 changes: 41 additions & 0 deletions
41
apps/cowswap-frontend/src/modules/trade/hooks/useSolanaWrapAndDelegateCallback.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { useMemo } from 'react' | ||
|
|
||
| import { WRAPPED_NATIVE_CURRENCIES } from '@cowprotocol/common-const' | ||
| import { isSolanaChain, SupportedChainId } from '@cowprotocol/cow-sdk' | ||
| import { useSolanaWalletProvider, useWalletInfo } from '@cowprotocol/wallet' | ||
|
|
||
| import { useAppKitConnection } from '@reown/appkit-adapter-solana/react' | ||
| import { Nullish } from 'types' | ||
|
|
||
| import { useTransactionAdder } from 'legacy/state/enhancedTransactions/hooks' | ||
|
|
||
| import { useSolanaDelegationAllowance } from 'common/hooks/useSolanaDelegationAllowance' | ||
|
|
||
| import { solanaNativeSwapCallback } from '../services/solanaFlow/solanaNativeSwapCallback' | ||
|
|
||
| export type SolanaWrapAndDelegateCallback = () => Promise<{ hash: string } | null> | ||
|
|
||
| // Returns null on every non-Solana chain, mirroring useSolanaWrapNativeCallback/useSolanaApproveCallback. | ||
| export function useSolanaWrapAndDelegateCallback(sellAmount: Nullish<bigint>): SolanaWrapAndDelegateCallback | null { | ||
| const { chainId, account } = useWalletInfo() | ||
| const provider = useSolanaWalletProvider() | ||
| const { connection } = useAppKitConnection() | ||
| const addTransaction = useTransactionAdder() | ||
| const currentDelegation = useSolanaDelegationAllowance(WRAPPED_NATIVE_CURRENCIES[SupportedChainId.SOLANA].address) | ||
|
|
||
| return useMemo(() => { | ||
| if (!isSolanaChain(chainId) || !account || !provider || !connection || !sellAmount) { | ||
| return null | ||
| } | ||
|
|
||
| return () => | ||
| solanaNativeSwapCallback({ | ||
| account, | ||
| connection, | ||
| provider, | ||
| addTransaction, | ||
| sellAmount, | ||
| currentDelegation: currentDelegation ?? 0n, | ||
| }) | ||
| }, [chainId, account, provider, connection, sellAmount, addTransaction, currentDelegation]) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
56 changes: 56 additions & 0 deletions
56
apps/cowswap-frontend/src/modules/trade/services/solanaFlow/planDelegateStep.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| /** | ||
| * PublicKey.isOnCurve misreports every point as on-curve under jsdom, exhausting findProgramAddressSync's bumps. | ||
| * @jest-environment node | ||
| */ | ||
| import { TokenWithLogo } from '@cowprotocol/common-const' | ||
|
|
||
| import { PublicKey } from '@solana/web3.js' | ||
|
|
||
| import { planDelegateStep } from './planDelegateStep' | ||
|
|
||
| import { buildApproveInstruction } from '../solanaApprove/buildApproveInstruction' | ||
|
|
||
| // Avoids `@cowprotocol/tokens` (pulled in via balances-and-allowances), which reads `window.location` at import time. | ||
| jest.mock('@cowprotocol/balances-and-allowances', () => ({ | ||
| findSolanaSettlementStatePda: jest.fn(() => 'SETTLEMENT_PDA'), | ||
| })) | ||
|
|
||
| jest.mock('../solanaApprove/buildApproveInstruction', () => ({ | ||
| buildApproveInstruction: jest.fn(() => 'APPROVE_IX'), | ||
| })) | ||
|
|
||
| const OWNER = new PublicKey('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM') | ||
| const TOKEN = { | ||
| address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', | ||
| symbol: 'WSOL', | ||
| tags: [], | ||
| } as unknown as TokenWithLogo | ||
|
|
||
| const mockBuildApprove = buildApproveInstruction as jest.Mock | ||
|
|
||
| beforeEach(() => jest.clearAllMocks()) | ||
|
|
||
| describe('planDelegateStep', () => { | ||
| it('returns null for a non-positive amount', () => { | ||
| expect(planDelegateStep({ owner: OWNER, token: TOKEN, amount: 0n, currentDelegation: 0n })).toBeNull() | ||
| expect(mockBuildApprove).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('returns null when the existing delegation already covers the amount', () => { | ||
| expect(planDelegateStep({ owner: OWNER, token: TOKEN, amount: 500n, currentDelegation: 500n })).toBeNull() | ||
| expect(mockBuildApprove).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('builds an approve instruction when the existing delegation falls short', () => { | ||
| const step = planDelegateStep({ owner: OWNER, token: TOKEN, amount: 500n, currentDelegation: 100n }) | ||
|
|
||
| expect(step?.instructions).toEqual(['APPROVE_IX']) | ||
| expect(mockBuildApprove).toHaveBeenCalledWith(expect.objectContaining({ owner: OWNER, amount: 500n })) | ||
| }) | ||
|
|
||
| it('summarizes with the token symbol', () => { | ||
| const step = planDelegateStep({ owner: OWNER, token: TOKEN, amount: 500n, currentDelegation: 0n }) | ||
|
|
||
| expect(step?.summary).toBe('Approve WSOL') | ||
| }) | ||
| }) |
41 changes: 41 additions & 0 deletions
41
apps/cowswap-frontend/src/modules/trade/services/solanaFlow/planDelegateStep.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { findSolanaSettlementStatePda } from '@cowprotocol/balances-and-allowances' | ||
| import { getIsToken2022, TokenWithLogo } from '@cowprotocol/common-const' | ||
|
|
||
| import { t } from '@lingui/core/macro' | ||
| import { PublicKey } from '@solana/web3.js' | ||
|
|
||
| import { SolanaFlowStep } from './types' | ||
|
|
||
| import { buildApproveInstruction } from '../solanaApprove/buildApproveInstruction' | ||
|
|
||
| export interface PlanDelegateStepParams { | ||
| owner: PublicKey | ||
| token: TokenWithLogo | ||
| amount: bigint | ||
| currentDelegation: bigint | ||
| } | ||
|
|
||
| // Skips the step when the existing delegation already covers `amount`; reused as-is by both the native-SOL flow and the future SPL delegate+order flow. | ||
| export function planDelegateStep({ | ||
| owner, | ||
| token, | ||
| amount, | ||
| currentDelegation, | ||
| }: PlanDelegateStepParams): SolanaFlowStep | null { | ||
| if (amount <= 0n || currentDelegation >= amount) return null | ||
|
|
||
| const instruction = buildApproveInstruction({ | ||
| owner, | ||
| mint: new PublicKey(token.address), | ||
| isToken2022: getIsToken2022(token), | ||
| delegate: findSolanaSettlementStatePda(), | ||
| amount, | ||
| }) | ||
|
|
||
| const symbol = token.symbol ?? '' | ||
|
|
||
| return { | ||
| instructions: [instruction], | ||
| summary: t`Approve ${symbol}`, | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
apps/cowswap-frontend/src/modules/trade/services/solanaFlow/planWrapStep.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| /** | ||
| * PublicKey.isOnCurve misreports every point as on-curve under jsdom, exhausting findProgramAddressSync's bumps. | ||
| * @jest-environment node | ||
| */ | ||
| import { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID } from '@solana/spl-token' | ||
| import { PublicKey, SystemInstruction } from '@solana/web3.js' | ||
|
|
||
| import { planWrapStep } from './planWrapStep' | ||
|
|
||
| import { WSOL_MINT } from '../wrapNativeSolana/const' | ||
|
|
||
| const OWNER = new PublicKey('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM') | ||
| const ata = getAssociatedTokenAddressSync(WSOL_MINT, OWNER, false, TOKEN_PROGRAM_ID) | ||
|
|
||
| describe('planWrapStep', () => { | ||
| it('returns null for a non-positive amount', () => { | ||
| expect(planWrapStep({ owner: OWNER, sellAmount: 0n })).toBeNull() | ||
| }) | ||
|
|
||
| it('transfers exactly the sell amount, regardless of whether the WSOL account already exists', () => { | ||
| const step = planWrapStep({ owner: OWNER, sellAmount: 10_000n }) | ||
|
|
||
| const [, transfer] = step!.instructions | ||
| const decoded = SystemInstruction.decodeTransfer(transfer) | ||
| expect(decoded.lamports).toBe(10_000n) | ||
| expect(decoded.toPubkey.equals(ata)).toBe(true) | ||
| }) | ||
|
|
||
| it('summarizes the SOL amount wrapped', () => { | ||
| const step = planWrapStep({ owner: OWNER, sellAmount: 10_000n }) | ||
|
|
||
| expect(step!.summary).toBe('Wrap 0.00001 SOL') | ||
| }) | ||
| }) |
34 changes: 34 additions & 0 deletions
34
apps/cowswap-frontend/src/modules/trade/services/solanaFlow/planWrapStep.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import { NATIVE_CURRENCIES } from '@cowprotocol/common-const' | ||
| import { formatTokenAmount } from '@cowprotocol/common-utils' | ||
| import { SupportedChainId } from '@cowprotocol/cow-sdk' | ||
| import { CurrencyAmount } from '@cowprotocol/currency' | ||
|
|
||
| import { t } from '@lingui/core/macro' | ||
| import { PublicKey } from '@solana/web3.js' | ||
|
|
||
| import { SolanaFlowStep } from './types' | ||
|
|
||
| import { buildWrapSolInstructions } from '../wrapNativeSolana/buildWrapSolInstructions' | ||
|
|
||
| export interface PlanWrapStepParams { | ||
| owner: PublicKey | ||
| // Native SOL lamports that must land as WSOL — the trade's exact sell amount. | ||
| sellAmount: bigint | ||
| } | ||
|
|
||
| // `SyncNative` sets the token amount to the account's lamports minus the *current* rent-exempt | ||
| // minimum, so the rent an idempotent create instruction funds is always netted back out — | ||
| // regardless of whether the WSOL account already existed. `sellAmount` alone is therefore always | ||
| // the resulting WSOL amount; no adjustment for account creation is needed (contrast with the | ||
| // standalone wrap flow's `getSolanaWrapPreview`, which caps *total spend* at the typed amount instead). | ||
| export function planWrapStep({ owner, sellAmount }: PlanWrapStepParams): SolanaFlowStep | null { | ||
| if (sellAmount <= 0n) return null | ||
|
|
||
| const sellCurrencyAmount = CurrencyAmount.fromRawAmount(NATIVE_CURRENCIES[SupportedChainId.SOLANA], sellAmount) | ||
| const sellAmountStr = formatTokenAmount(sellCurrencyAmount) | ||
|
|
||
| return { | ||
| instructions: buildWrapSolInstructions({ owner, transferLamports: sellAmount }), | ||
| summary: t`Wrap ${sellAmountStr} SOL`, | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.