Skip to content

Commit

Permalink
Merge pull request #43 from invariant-labs/fetch-balance-of-tokens
Browse files Browse the repository at this point in the history
fix fetch balance of tokens
  • Loading branch information
p6te authored Aug 21, 2024
2 parents 4332d55 + eef403f commit f7892ac
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 73 deletions.
17 changes: 10 additions & 7 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
},
"devDependencies": {
"@rollup/plugin-inject": "^5.0.5",
"@types/node": "^22.4.2",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/react-window": "^1.8.8",
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/components/Liquidity/Liquidity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,6 @@ export const Liquidity: React.FC<ILiquidity> = ({

const [lastInput, setLastInput] = useState<'A' | 'B'>('A')

console.log('pi', poolIndex)

useEffect(() => {
if (tokenAIndex !== null && tokenBIndex !== null) {
if (lastInput === 'A') {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/store/consts/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ export const ALL_FEE_TIERS_DATA = FEE_TIERS.map((tier, index) => ({

export const addressTickerMap: { [key: string]: string } = {
WETH: 'So11111111111111111111111111111111111111112',
BTC: '3JXmQAzBPU66dkVQufSE1ChBMRAdCHp6T7ZMBKAwhmWw',
USDC: '5W3bmyYDww6p5XRZnCR6m2c75st6XyCxW1TgGS3wTq7S',
BTC: '2F5TprcNBqj2hXVr9oTssabKdf8Zbsf9xStqWjPm8yLo',
USDC: '5gFSyxjNsuQsZKn9g5L9Ky3cSUvJ6YXqWVuPzmSi8Trx',
ETH: 'So11111111111111111111111111111111111111112'
}
141 changes: 80 additions & 61 deletions frontend/src/store/sagas/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from 'typed-redux-saga'
import { createLoaderKey } from '@utils/utils'
import { closeSnackbar } from 'notistack'
import { actions, Status } from '@store/reducers/wallet'
import { actions, ITokenAccount, Status } from '@store/reducers/wallet'
import {
NetworkType,
Token as StoreToken,
Expand All @@ -21,7 +21,10 @@ import { WalletAdapter } from '@utils/web3/adapters/types'
import { BN } from '@project-serum/anchor'
import { disconnectWallet, getSolanaWallet } from '@utils/web3/wallet'
import {
AccountInfo,
ParsedAccountData,
PublicKey,
RpcResponseAndContext,
Signer,
SystemProgram,
Transaction,
Expand All @@ -31,6 +34,7 @@ import {
import { getConnection } from './connection'
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
Mint,
TOKEN_PROGRAM_ID,
createAssociatedTokenAccountInstruction,
createMintToInstruction,
Expand All @@ -46,6 +50,7 @@ import airdropAdmin from '@store/consts/airdropAdmin'
import { getTokenDetails } from './token'
import { openWalletSelectorModal } from '@utils/web3/selector'
import { PayloadAction } from '@reduxjs/toolkit'
import { TOKEN_2022_PROGRAM_ID } from '@invariant-labs/sdk-eclipse'

export function* getWallet(): SagaGenerator<WalletAdapter> {
const wallet = yield* call(getSolanaWallet)
Expand All @@ -64,68 +69,83 @@ export function* handleBalance(): Generator {
yield* put(actions.setIsBalanceLoading(true))
const balance = yield* call(getBalance, wallet.publicKey)
yield* put(actions.setBalance(balance))
// yield* call(fetchTokensAccounts)
yield* call(fetchTokensAccounts)
yield* put(actions.setIsBalanceLoading(false))
}

// interface IparsedTokenInfo {
// mint: string
// owner: string
// tokenAmount: {
// amount: string
// decimals: number
// uiAmount: number
// }
// }
// export function* fetchTokensAccounts(): Generator {
// const connection = yield* call(getConnection)
// const wallet = yield* call(getWallet)
// const tokensAccounts = yield* call(
// [connection, connection.getParsedTokenAccountsByOwner],
// wallet.publicKey,
// {
// programId: TOKEN_PROGRAM_ID
// }
// )
// const allTokens = yield* select(tokens)
// const newAccounts: ITokenAccount[] = []
// const unknownTokens: Record<string, StoreToken> = {}
// for (const account of tokensAccounts.value) {
// const info: IparsedTokenInfo = account.account.data.parsed.info
// newAccounts.push({
// programId: new PublicKey(info.mint),
// balance: new BN(info.tokenAmount.amount),
// address: account.pubkey,
// decimals: info.tokenAmount.decimals
// })

// if (!allTokens[info.mint]) {
// unknownTokens[info.mint] = {
// name: info.mint,
// symbol: `${info.mint.slice(0, 4)}...${info.mint.slice(-4)}`,
// decimals: info.tokenAmount.decimals,
// address: new PublicKey(info.mint),
// logoURI: '/unknownToken.svg',
// isUnknown: true
// }
// }
// }

// yield* put(actions.addTokenAccounts(newAccounts))
// yield* put(poolsActions.addTokens(unknownTokens))
// }

// export function* getToken(tokenAddress: PublicKey): SagaGenerator<Token> {
// const connection = yield* call(getConnection)
// const token = new Token(connection, tokenAddress, TOKEN_PROGRAM_ID, new Account())
// return token
// }

export function* getToken(tokenAddress: PublicKey): SagaGenerator<any> {
interface IparsedTokenInfo {
mint: string
owner: string
tokenAmount: {
amount: string
decimals: number
uiAmount: number
}
}

interface TokenAccountInfo {
pubkey: PublicKey
account: AccountInfo<ParsedAccountData>
}
export function* fetchTokensAccounts(): Generator {
const connection = yield* call(getConnection)
const wallet = yield* call(getWallet)
console.log(connection)
const splTokensAccounts: RpcResponseAndContext<TokenAccountInfo[]> = yield* call(
[connection, connection.getParsedTokenAccountsByOwner],
wallet.publicKey,
{
programId: TOKEN_PROGRAM_ID
}
)
console.log(splTokensAccounts)
const token2022TokensAccounts: RpcResponseAndContext<TokenAccountInfo[]> = yield* call(
[connection, connection.getParsedTokenAccountsByOwner],
wallet.publicKey,
{
programId: TOKEN_2022_PROGRAM_ID
}
)
console.log(token2022TokensAccounts)
const mergedAccounts: TokenAccountInfo[] = [
...splTokensAccounts.value,
...token2022TokensAccounts.value
]
console.log(mergedAccounts)
const allTokens = yield* select(tokens)
const newAccounts: ITokenAccount[] = []
const unknownTokens: Record<string, StoreToken> = {}
for (const account of mergedAccounts) {
const info: IparsedTokenInfo = account.account.data.parsed.info
newAccounts.push({
programId: new PublicKey(info.mint),
balance: new BN(info.tokenAmount.amount),
address: account.pubkey,
decimals: info.tokenAmount.decimals
})

const mintInfo = yield* call(getMint, connection, tokenAddress)
if (!allTokens[info.mint]) {
unknownTokens[info.mint] = {
name: info.mint,
symbol: `${info.mint.slice(0, 4)}...${info.mint.slice(-4)}`,
decimals: info.tokenAmount.decimals,
address: new PublicKey(info.mint),
logoURI: '/unknownToken.svg',
isUnknown: true
}
}
}
console.log(newAccounts)
console.log(unknownTokens)
yield* put(actions.addTokenAccounts(newAccounts))
yield* put(poolsActions.addTokens(unknownTokens))
}

export function* getToken(tokenAddress: PublicKey): SagaGenerator<Mint> {
const connection = yield* call(getConnection)

const mintInfo = yield* call(getMint, connection, tokenAddress)
console.log(mintInfo)
return mintInfo
}

Expand Down Expand Up @@ -203,7 +223,7 @@ export function* setEmptyAccounts(collateralsAddresses: PublicKey[]): Generator
? tokensAccounts[collateral.toString()].address
: null
if (accountAddress == null) {
acc.push(collateralTokenProgram.publicKey)
acc.push(new PublicKey(collateralTokenProgram.address))
}
}
if (acc.length !== 0) {
Expand Down Expand Up @@ -295,7 +315,7 @@ export function* getCollateralTokenAirdrop(

export function* signAndSend(wallet: WalletAdapter, tx: Transaction): SagaGenerator<string> {
const connection = yield* call(getConnection)
const blockhash = yield* call([connection, connection.getLatestBlockhash])
const blockhash = yield* call([connection, connection.getRecentBlockhash])
tx.feePayer = wallet.publicKey
tx.recentBlockhash = blockhash.blockhash
const signedTx = yield* call([wallet, wallet.signTransaction], tx)
Expand Down Expand Up @@ -448,7 +468,7 @@ export function* init(isEagerConnect?: boolean): Generator {
const balance = yield* call(getBalance, wallet.publicKey)
yield* put(actions.setBalance(balance))
yield* put(actions.setStatus(Status.Initialized))
// yield* call(fetchTokensAccounts)
yield* call(fetchTokensAccounts)
yield* put(actions.setIsBalanceLoading(false))
} catch (error) {
yield* put(actions.setStatus(Status.Uninitialized))
Expand All @@ -462,7 +482,6 @@ export function* handleReconnect(): Generator {
yield* call(handleConnect, { type: actions.connect.type, payload: false })
}


export const sleep = (ms: number) => {
return new Promise(resolve => setTimeout(resolve, ms))
}
Expand Down
10 changes: 9 additions & 1 deletion frontend/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { FormatNumberThreshold, PrefixConfig } from '@store/consts/types'
import { getMint } from '@solana/spl-token'
import mainnetList from '@store/consts/tokenLists/mainnet.json'
import icons from '@static/icons'
import { getTokenProgramAddress } from '@invariant-labs/sdk-eclipse'
export const createLoaderKey = () => (new Date().getMilliseconds() + Math.random()).toString()

export const trimZeros = (amount: string) => {
Expand Down Expand Up @@ -202,7 +203,7 @@ export const getNetworkTokensList = (networkType: NetworkType): Record<string, T
const obj: Record<string, Token> = {}
switch (networkType) {
case NetworkType.MAINNET:
(mainnetList as any[]).forEach(token => {
;(mainnetList as any[]).forEach(token => {
obj[token.address] = {
...token,
address: new PublicKey(token.address),
Expand Down Expand Up @@ -261,3 +262,10 @@ export const tickerToAddress = (ticker: string): string => {
export const parsePathFeeToFeeString = (pathFee: string): string => {
return (+pathFee.replace('_', '') * Math.pow(10, 8)).toString()
}

export const getTokenProgramId = async (
connection: Connection,
address: PublicKey
): Promise<PublicKey> => {
return await getTokenProgramAddress(connection, address)
}

0 comments on commit f7892ac

Please sign in to comment.