-
Notifications
You must be signed in to change notification settings - Fork 3
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
Portfolio Onboarding Section #391
Open
JasonMHasperhoven
wants to merge
6
commits into
main
Choose a base branch
from
onboarding
base: main
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
6 commits
Select commit
Hold shift + click to select a range
6da0386
Add onboarding section
JasonMHasperhoven 8deb284
Copy paste Josefs cosmos feature
JasonMHasperhoven 2e77dca
Add children prop to cosmos connect button
JasonMHasperhoven 53ecb5f
Fix lint issues
JasonMHasperhoven 4a79f0b
Merge branch 'main' into onboarding
JasonMHasperhoven 56c3671
Make inner cards responsive
JasonMHasperhoven 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 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
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains 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,79 @@ | ||
import { ChainProvider } from '@cosmos-kit/react'; | ||
import { assets, chains } from 'chain-registry'; | ||
import { SignerOptions, wallets } from 'cosmos-kit'; | ||
import { ReactNode, useMemo } from 'react'; | ||
import { Chain, Registry as PenumbraRegistry } from '@penumbra-labs/registry'; | ||
|
||
import { GeneratedType, Registry } from '@cosmjs/proto-signing'; | ||
import { AminoTypes } from '@cosmjs/stargate'; | ||
import { | ||
cosmosAminoConverters, | ||
cosmosProtoRegistry, | ||
cosmwasmAminoConverters, | ||
cosmwasmProtoRegistry, | ||
ibcAminoConverters, | ||
ibcProtoRegistry, | ||
osmosisAminoConverters, | ||
osmosisProtoRegistry, | ||
} from 'osmo-query'; | ||
|
||
// @ts-expect-error type error, but it works. | ||
import '@interchain-ui/react/styles'; | ||
|
||
const protoRegistry: readonly [string, GeneratedType][] = [ | ||
...cosmosProtoRegistry, | ||
...cosmwasmProtoRegistry, | ||
...ibcProtoRegistry, | ||
...osmosisProtoRegistry, | ||
]; | ||
|
||
const aminoConverters = { | ||
...cosmosAminoConverters, | ||
...cosmwasmAminoConverters, | ||
...ibcAminoConverters, | ||
...osmosisAminoConverters, | ||
}; | ||
|
||
const registry = new Registry(protoRegistry); | ||
const aminoTypes = new AminoTypes(aminoConverters); | ||
|
||
const signerOptions: SignerOptions = { | ||
// @ts-expect-error type error, but it works. | ||
signingStargate: () => { | ||
return { | ||
aminoTypes, | ||
registry, | ||
}; | ||
}, | ||
}; | ||
|
||
interface IbcProviderProps { | ||
registry: PenumbraRegistry; | ||
children: ReactNode; | ||
} | ||
|
||
export const IbcChainProvider = ({ registry, children }: IbcProviderProps) => { | ||
const chainsToDisplay = useMemo( | ||
() => chainsInPenumbraRegistry(registry.ibcConnections), | ||
[registry], | ||
); | ||
|
||
return ( | ||
<ChainProvider | ||
chains={chainsToDisplay} | ||
assetLists={assets} | ||
// Not using mobile wallets as WalletConnect is a centralized service that requires an account | ||
wallets={wallets.extension} | ||
signerOptions={signerOptions} | ||
modalTheme={{ defaultTheme: 'light' }} | ||
logLevel={'NONE'} | ||
> | ||
{children} | ||
</ChainProvider> | ||
); | ||
}; | ||
|
||
// Searches cosmos registry for chains that have ibc connections to Penumbra | ||
export const chainsInPenumbraRegistry = (ibcConnections: Chain[]) => { | ||
return chains.filter(c => ibcConnections.some(i => c.chain_id === i.chainId)); | ||
}; |
This file contains 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,50 @@ | ||
import { observer } from 'mobx-react-lite'; | ||
import { Button, ButtonProps } from '@penumbra-zone/ui/Button'; | ||
import dynamic from 'next/dynamic'; | ||
import { useChains } from '@cosmos-kit/react'; | ||
import { Wallet2 } from 'lucide-react'; | ||
import { Density } from '@penumbra-zone/ui/Density'; | ||
import { chainsInPenumbraRegistry } from '@/features/cosmos/chain-provider.tsx'; | ||
import { useRegistry } from '@/shared/api/registry.ts'; | ||
|
||
interface CosmosConnectButtonProps { | ||
actionType?: ButtonProps['actionType']; | ||
variant?: 'default' | 'minimal'; | ||
children?: React.ReactNode; | ||
} | ||
|
||
const CosmosConnectButtonInner = observer( | ||
({ actionType = 'accent', variant = 'default', children }: CosmosConnectButtonProps) => { | ||
const { data: registry } = useRegistry(); | ||
const penumbraIbcChains = chainsInPenumbraRegistry(registry?.ibcConnections ?? []).map( | ||
c => c.chain_name, | ||
); | ||
const chains = useChains(penumbraIbcChains); | ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Osmosis is always available | ||
const { address, disconnect, openView, isWalletConnected } = (chains['osmosis'] ?? | ||
chains['osmosistestnet'])!; | ||
|
||
const handleConnect = () => { | ||
openView(); | ||
}; | ||
|
||
return ( | ||
<Density variant={variant === 'default' ? 'sparse' : 'compact'}> | ||
{isWalletConnected && address ? ( | ||
<Button actionType={actionType} onClick={() => void disconnect()}> | ||
{`${address.slice(0, 8)}...${address.slice(-4)}`} | ||
</Button> | ||
) : ( | ||
<Button icon={Wallet2} actionType={actionType} onClick={handleConnect}> | ||
{children ?? 'Connect Cosmos Wallet'} | ||
</Button> | ||
)} | ||
</Density> | ||
); | ||
}, | ||
); | ||
|
||
// Export a dynamic component to prevent SSR issues with window object | ||
export const CosmosConnectButton = dynamic(() => Promise.resolve(CosmosConnectButtonInner), { | ||
ssr: false, | ||
}); |
This file contains 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,111 @@ | ||
import { useWallet } from '@cosmos-kit/react'; | ||
import { useQuery } from '@tanstack/react-query'; | ||
import { ChainWalletBase, WalletStatus } from '@cosmos-kit/core'; | ||
import { useRegistry } from '@/shared/api/registry'; | ||
import { Chain } from '@penumbra-labs/registry'; | ||
import { sha256HashStr } from '@penumbra-zone/crypto-web/sha256'; | ||
import { Asset } from '@chain-registry/types'; | ||
import { assets as cosmosAssetList } from 'chain-registry'; | ||
import { Coin, StargateClient } from '@cosmjs/stargate'; | ||
|
||
export const fetchChainBalances = async ( | ||
address: string, | ||
chain: ChainWalletBase, | ||
): Promise<readonly Coin[]> => { | ||
const endpoint = await chain.getRpcEndpoint(); | ||
const client = await StargateClient.connect(endpoint); | ||
return client.getAllBalances(address); | ||
}; | ||
|
||
// Searches for corresponding denom in asset registry and returns the metadata | ||
export const augmentToAsset = (denom: string, chainName: string): Asset => { | ||
const match = cosmosAssetList | ||
.find(({ chain_name }) => chain_name === chainName) | ||
?.assets.find(asset => asset.base === denom); | ||
|
||
return match ? match : fallbackAsset(denom); | ||
}; | ||
|
||
const fallbackAsset = (denom: string): Asset => { | ||
return { | ||
base: denom, | ||
denom_units: [{ denom, exponent: 0 }], | ||
display: denom, | ||
name: denom, | ||
symbol: denom, | ||
type_asset: 'sdk.coin', | ||
}; | ||
}; | ||
|
||
const generatePenumbraIbcDenoms = async (chains: Chain[]): Promise<string[]> => { | ||
const ibcAddrs: string[] = []; | ||
for (const c of chains) { | ||
const ibcStr = `transfer/${c.counterpartyChannelId}/upenumbra`; | ||
const encoder = new TextEncoder(); | ||
const encodedString = encoder.encode(ibcStr); | ||
|
||
const hash = await sha256HashStr(encodedString); | ||
ibcAddrs.push(`ibc/${hash.toUpperCase()}`); | ||
} | ||
return ibcAddrs; | ||
}; | ||
|
||
export const usePenumbraIbcDenoms = () => { | ||
const { data: registry, isLoading: registryIsLoading, error: registryErr } = useRegistry(); | ||
|
||
const { | ||
data: ibcAddrs, | ||
isLoading: ibcAddrsLoading, | ||
error: ibcAddrssErr, | ||
} = useQuery({ | ||
queryKey: ['penumbraIbcDenoms', registry], | ||
queryFn: async () => generatePenumbraIbcDenoms(registry?.ibcConnections ?? []), | ||
enabled: Boolean(registry), | ||
}); | ||
|
||
return { | ||
data: ibcAddrs, | ||
isLoading: registryIsLoading || ibcAddrsLoading, | ||
error: registryErr ?? ibcAddrssErr, | ||
}; | ||
}; | ||
|
||
export const useBalances = () => { | ||
const { chainWallets, status } = useWallet(); | ||
const { data: registry } = useRegistry(); | ||
|
||
const fetchAllChainBalances = async (): Promise<{ asset: Asset; amount: string }[]> => { | ||
return [ | ||
await Promise.all( | ||
chainWallets.map(async chain => { | ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- okay | ||
const balances = await fetchChainBalances(chain.address!, chain); | ||
return balances.map(coin => { | ||
return { asset: augmentToAsset(coin.denom, chain.chainName), amount: coin.amount }; | ||
}); | ||
}), | ||
), | ||
].flat(2); | ||
}; | ||
|
||
const result = useQuery({ | ||
queryKey: [ | ||
'cosmos-balances', | ||
status, | ||
chainWallets.map(chain => chain.chainId).join(','), | ||
// Use a stable string representation of the registry to avoid unnecessary invalidation | ||
registry ? 'registry-available' : 'no-registry', | ||
], | ||
queryFn: fetchAllChainBalances, | ||
enabled: status === WalletStatus.Connected && chainWallets.length > 0, | ||
retry: 3, // Retry failed requests 3 times | ||
retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential backoff starting at 1s | ||
}); | ||
|
||
return { | ||
balances: result.data ?? [], | ||
isLoading: result.isLoading && status === WalletStatus.Connected, | ||
error: result.error ? String(result.error) : null, | ||
refetch: result.refetch, | ||
}; | ||
}; |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
comment: unused import?