-
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 7 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
48 changes: 48 additions & 0 deletions
48
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,48 @@ | ||
| import { ReactNode, useState } from 'react' | ||
|
|
||
| import { usePreventDoubleExecution } from '@cowprotocol/common-hooks' | ||
| 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) { | ||
| setError(err instanceof Error ? err.message : String(err)) | ||
| } | ||
| }) | ||
|
|
||
| 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> | ||
| ) | ||
| } |
44 changes: 44 additions & 0 deletions
44
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,44 @@ | ||
| 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> | ||
|
|
||
| /** | ||
| * Enables trading native SOL for an SPL token, in one signed transaction. 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
58 changes: 58 additions & 0 deletions
58
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,58 @@ | ||
| /** | ||
| * Program-address derivation needs a working ed25519 curve check, and `PublicKey.isOnCurve` misreports | ||
| * every point as on-curve under jsdom — which makes `findProgramAddressSync` exhaust all 255 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' | ||
|
|
||
| // `@cowprotocol/balances-and-allowances` pulls in `@cowprotocol/tokens`, which reads `window.location` | ||
| // at import time — avoid that entirely rather than fight the node/jsdom test-environment mismatch. | ||
| 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') | ||
| }) | ||
| }) |
47 changes: 47 additions & 0 deletions
47
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,47 @@ | ||
| 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 | ||
| /** Currently delegated amount on this token's ATA, e.g. from `useSolanaDelegationAllowance`. */ | ||
| currentDelegation: bigint | ||
| } | ||
|
|
||
| /** | ||
| * Plans the delegate step for a bundled flow. Skips the step when the existing delegation already | ||
| * covers `amount` — reused as-is by both the native-SOL swap flow (delegating WSOL) and the future | ||
| * SPL delegate+create-order flow (delegating the sell token directly), so this never needs to know | ||
| * which flow it's called from. | ||
| */ | ||
| 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}`, | ||
| } | ||
| } |
62 changes: 62 additions & 0 deletions
62
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,62 @@ | ||
| /** | ||
| * Program-address derivation needs a working ed25519 curve check, and `PublicKey.isOnCurve` misreports | ||
| * every point as on-curve under jsdom — which makes `findProgramAddressSync` exhaust all 255 bumps. | ||
| * @jest-environment node | ||
| */ | ||
| import { decodeSyncNativeInstruction, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID } from '@solana/spl-token' | ||
| import { Connection, 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) | ||
|
|
||
| function createConnection({ | ||
| accountExists, | ||
| rentExemptLamports = 9_000, | ||
| }: { | ||
| accountExists: boolean | ||
| rentExemptLamports?: number | ||
| }): Connection { | ||
| return { | ||
| getAccountInfo: jest.fn().mockResolvedValue(accountExists ? {} : null), | ||
| getMinimumBalanceForRentExemption: jest.fn().mockResolvedValue(rentExemptLamports), | ||
| } as unknown as Connection | ||
| } | ||
|
|
||
| describe('planWrapStep', () => { | ||
| it('returns null for a non-positive amount', async () => { | ||
| const connection = createConnection({ accountExists: true }) | ||
|
|
||
| expect(await planWrapStep({ connection, owner: OWNER, sellAmount: 0n })).toBeNull() | ||
| }) | ||
|
|
||
| it('transfers exactly the sell amount when the WSOL account already exists', async () => { | ||
| const connection = createConnection({ accountExists: true }) | ||
|
|
||
| const step = await planWrapStep({ connection, owner: OWNER, sellAmount: 10_000n }) | ||
|
|
||
| const [, transfer] = step!.instructions | ||
| expect(SystemInstruction.decodeTransfer(transfer).lamports).toBe(10_000n) | ||
| }) | ||
|
|
||
| it('grows the transfer by the rent-exempt deposit when the WSOL account does not exist yet, so exactly the sell amount lands as WSOL', async () => { | ||
| const connection = createConnection({ accountExists: false, rentExemptLamports: 9_000 }) | ||
|
|
||
| const step = await planWrapStep({ connection, owner: OWNER, sellAmount: 10_000n }) | ||
|
|
||
| const [, transfer, syncNative] = step!.instructions | ||
| expect(SystemInstruction.decodeTransfer(transfer).lamports).toBe(19_000n) | ||
| expect(decodeSyncNativeInstruction(syncNative, TOKEN_PROGRAM_ID).keys.account.pubkey.equals(ata)).toBe(true) | ||
| }) | ||
|
|
||
| it('summarizes the SOL amount wrapped', async () => { | ||
| const connection = createConnection({ accountExists: true }) | ||
|
|
||
| const step = await planWrapStep({ connection, owner: OWNER, sellAmount: 10_000n }) | ||
|
|
||
| expect(step!.summary).toBe('Wrap 0.00001 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.