Skip to content

Commit

Permalink
refactor: solana redpacket (#12035)
Browse files Browse the repository at this point in the history
  • Loading branch information
guanbinrui authored Jan 16, 2025
1 parent 744bbac commit ba1f969
Show file tree
Hide file tree
Showing 102 changed files with 5,045 additions and 266 deletions.
5 changes: 4 additions & 1 deletion cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"jkoeaghipilijlahjplgbfiocjhldnap",
"keccak",
"keybase",
"keypair",
"kiwistand",
"klaytn",
"lamport",
Expand Down Expand Up @@ -140,6 +141,7 @@
"nftx",
"nonfungiblefriends",
"notistack",
"nstructions",
"oembed",
"okex",
"okxwallet",
Expand Down Expand Up @@ -198,6 +200,7 @@
"suji",
"suspendable",
"swappable",
"sysvar",
"telos",
"testid",
"tinycolor",
Expand Down Expand Up @@ -237,5 +240,5 @@
],
"ignoreRegExpList": ["/[A-Za-z0-9]{44}/", "/[A-Za-z0-9]{46}/", "/[A-Za-z0-9]{59}/"],
"overrides": [],
"words": ["cashtags", "endregion", "linkedin", "Luma", "tiktok", "waitlist", "youtube"]
"words": ["cashtags", "endregion", "linkedin", "luma", "muln", "tiktok", "tweetnacl", "waitlist", "youtube"]
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"@types/react": "npm:types-react@beta",
"@types/react-dom": "npm:types-react-dom@beta",
"@typescript/lib-dom": "npm:@types/web@^0.0.183",
"buffer": "^6.0.3",
"knip": "^5.38.1",
"lodash-es": "^4.17.21",
"react": "0.0.0-experimental-58af67a8f8-20240628",
Expand Down
4 changes: 2 additions & 2 deletions packages/icons/general/Location.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions packages/icons/icon-generated-as-jsx.js

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

26 changes: 26 additions & 0 deletions packages/injected-script/sdk/OKX.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,29 @@ export class OKXProvider extends InjectedWalletBridge {
}
}
}

export class OKXSolanaProvider extends InjectedWalletBridge {
constructor() {
super('okxwallet.solana')
}

override async untilAvailable(): Promise<void> {
await super.untilAvailable(async () => !!(await super.getProperty<boolean>('isOKExWallet')))
}

override connect(): Promise<void> {
return createPromise((id) =>
sendEvent('web3BridgeExecute', [this.pathname, 'connect'].join('.'), id, {
onlyIfTrusted: false,
}),
)
}

override emit(event: string, data: unknown[]) {
for (const f of this.events.get(event) || []) {
try {
Reflect.apply(f, null, event === 'chainChanged' ? [`0x${Number(data[0]).toString(16)}`] : data)
} catch {}
}
}
}
3 changes: 2 additions & 1 deletion packages/injected-script/sdk/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BrowserProvider } from './Browser.js'
import { Coin98Provider, Coin98ProviderType } from './Coin98.js'
import { CoinbaseProvider } from './Coinbase.js'
import { OKXProvider } from './OKX.js'
import { OKXProvider, OKXSolanaProvider } from './OKX.js'
import { CryptoProvider } from './Crypto.js'
import { BitGetProvider } from './BitGet.js'
import { RainbowProvider } from './Rainbow.js'
Expand Down Expand Up @@ -30,6 +30,7 @@ export const injectedMetaMaskProvider = new MetaMaskProvider()
export const injectedCoinbaseProvider = new CoinbaseProvider()
export const injectedOneKeyProvider = new OneKeyProvider()
export const injectedOKXProvider = new OKXProvider()
export const injectedOKXSolanaProvider = new OKXSolanaProvider()
export const injectedCryptoProvider = new CryptoProvider()
export const injectedBitGetProvider = new BitGetProvider()
export const injectedRainbowProvider = new RainbowProvider()
Expand Down
1 change: 1 addition & 0 deletions packages/mask/.webpack/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export async function createConfiguration(
stream: require.resolve('stream-browserify'),
crypto: require.resolve('crypto-browserify'),
zlib: require.resolve('zlib-browserify'),
buffer: require.resolve('buffer/'),
},
conditionNames: ['mask-src', '...'],
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import Services from '#services'
import { encodeByNetwork } from '@masknet/encryption'
import { PluginID, RedPacketMetaKey, RedPacketNftMetaKey, Sniffings, SOCIAL_MEDIA_NAME } from '@masknet/shared-base'
import {
PluginID,
RedPacketMetaKey,
RedPacketNftMetaKey,
Sniffings,
SOCIAL_MEDIA_NAME,
SolanaRedPacketMetaKey,
} from '@masknet/shared-base'
import type { Meta } from '@masknet/typed-message'
import { Telemetry } from '@masknet/web3-telemetry'
import { EventID, EventType } from '@masknet/web3-telemetry/types'
Expand Down Expand Up @@ -66,7 +73,11 @@ export function useSubmit(onClose: () => void, reason: 'timeline' | 'popup' | 'r
})
}

if (content.meta?.has(RedPacketMetaKey) || content.meta?.has(RedPacketNftMetaKey))
if (
content.meta?.has(RedPacketMetaKey) ||
content.meta?.has(RedPacketNftMetaKey) ||
content.meta?.has(SolanaRedPacketMetaKey)
)
Telemetry.captureEvent(EventType.Interact, EventID.EntryAppLuckSend)
Telemetry.captureEvent(EventType.Interact, EventID.EntryMaskComposeEncrypt)

Expand All @@ -82,11 +93,11 @@ function decorateEncryptedText(encrypted: string, _: I18nContext['_'], meta?: Me
if (!meta) return null
const hasOfficialAccount = Sniffings.is_twitter_page || Sniffings.is_facebook_page
const officialAccount = Sniffings.is_twitter_page ? _(msg`realMaskNetwork`) : _(msg`masknetwork`)
const token = meta.has(RedPacketMetaKey) ? _(msg`a token`) : _(msg`an NFT`)
const token = meta.has(RedPacketMetaKey) || meta.has(SolanaRedPacketMetaKey) ? _(msg`a token`) : _(msg`an NFT`)
const sns = SOCIAL_MEDIA_NAME[activatedSiteAdaptorUI!.networkIdentifier]

// Note: since this is in the composition stage, we can assume plugins don't insert old version of meta.
if (meta.has(RedPacketMetaKey) || meta.has(RedPacketNftMetaKey)) {
if (meta.has(RedPacketMetaKey) || meta.has(RedPacketNftMetaKey) || meta.has(SolanaRedPacketMetaKey)) {
const promote_red_packet = _(msg`Hi friends, I just created ${token} Lucky Drop. Download Mask.io to claim.`)
const promote_red_packet2 = _(msg`🧧🧧🧧 Try sending Lucky Drop to your friends with Mask.io.`)
return hasOfficialAccount ?
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { Fragment, useContext, useEffect, useReducer, type Dispatch, type SetStateAction } from 'react'
import { extractTextFromTypedMessage, isTypedMessageEqual, type TypedMessage } from '@masknet/typed-message'
import { RedPacketMetaKey, RedPacketNftMetaKey, type ProfileIdentifier } from '@masknet/shared-base'
import {
RedPacketMetaKey,
RedPacketNftMetaKey,
SolanaRedPacketMetaKey,
type ProfileIdentifier,
} from '@masknet/shared-base'

import Services, { GeneratorServices } from '#services'
import type { DecryptionProgress, FailureDecryption, SuccessDecryption } from './types.js'
Expand Down Expand Up @@ -150,7 +155,11 @@ export function DecryptPost({ whoAmI, onImageDecrypted }: DecryptPostProps) {
})
if (!message.meta) return
// For now, we only care about RedPacket payload
if (message.meta.has(RedPacketMetaKey) || message.meta.has(RedPacketNftMetaKey)) {
if (
message.meta.has(RedPacketMetaKey) ||
message.meta.has(RedPacketNftMetaKey) ||
message.meta.has(SolanaRedPacketMetaKey)
) {
onImageDecrypted((images) => (images.includes(url) ? images : [...images, url]))
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { getHub } from '@masknet/web3-providers'
import { makeStyles, ShadowRootMenu } from '@masknet/theme'
import { OrderSide, resolveSourceTypeName, SourceType } from '@masknet/web3-shared-base'
import { Button, MenuItem, Table, TableBody, TableCell, TableRow, TextField, Typography } from '@mui/material'
import type { NetworkPluginID } from '@masknet/shared-base'
import { NetworkPluginID } from '@masknet/shared-base'
import { SelectFungibleTokenModal } from '@masknet/shared'

interface HubContentProps {
onClose?: () => void
Expand Down Expand Up @@ -176,6 +177,25 @@ export function HubContent(props: HubContentProps) {
</TableRow>
)
})}
<TableRow>
<TableCell>
<Typography variant="body2" whiteSpace="nowrap">
Open Select Token
</Typography>
</TableCell>
<TableCell>
<Button
size="small"
onClick={async () => {
SelectFungibleTokenModal.openAndWaitForClose({
pluginID: NetworkPluginID.PLUGIN_SOLANA,
lockChainId: true,
})
}}>
Query
</Button>
</TableCell>
</TableRow>
</TableBody>
</Table>
</section>
Expand Down
6 changes: 6 additions & 0 deletions packages/plugins/RedPacket/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
}
},
"dependencies": {
"@coral-xyz/anchor": "^0.30.1",
"@masknet/icons": "workspace:^",
"@masknet/plugin-infra": "workspace:^",
"@masknet/shared": "workspace:^",
Expand All @@ -30,12 +31,17 @@
"@masknet/web3-providers": "workspace:^",
"@masknet/web3-shared-base": "workspace:^",
"@masknet/web3-shared-evm": "workspace:^",
"@masknet/web3-shared-solana": "workspace:^",
"@masknet/web3-telemetry": "workspace:^",
"@solana/spl-token": "^0.4.9",
"@solana/web3.js": "^1.75.0",
"@tanstack/react-query": "^5.49.2",
"bignumber.js": "9.1.2",
"date-fns": "^3.6.0",
"immer": "^10.1.1",
"react-router-dom": "^6.24.0",
"react-use": "^17.5.0",
"tweetnacl": "^1.0.3",
"urlcat": "^3.1.0",
"web3-core": "1.10.4",
"web3-utils": "1.10.2"
Expand Down
39 changes: 24 additions & 15 deletions packages/plugins/RedPacket/src/SiteAdaptor/MainDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { RouterDialog } from './components/RouterDialog.js'
import { RedPacketRoutes } from './Routes.js'
import { RedPacketProvider } from './contexts/RedPacketContext.js'
import { RestorableScrollContext } from '@masknet/shared'
import { EVMWeb3ContextProvider } from '@masknet/web3-hooks-base'
import { RedPacketTabs } from '../types.js'

interface RedPacketDialogProps {
onClose: () => void
Expand Down Expand Up @@ -38,28 +40,35 @@ const useStyles = makeStyles()((theme) => ({
}))

const initialEntries = [RoutePaths.Exit, RoutePaths.CreateErc20RedPacket]

export function RedPacketMainDialog({ onClose }: RedPacketDialogProps) {
const { classes } = useStyles()

const initialIndex = 1

return (
<MemoryRouter initialEntries={initialEntries} initialIndex={initialIndex}>
<RedPacketProvider>
<RouterDialog
open
onClose={onClose}
classes={{ paper: classes.paper }}
maxWidth="xs"
fullWidth
independent>
<DialogContent className={classes.content}>
<RestorableScrollContext>
<RedPacketRoutes />
</RestorableScrollContext>
</DialogContent>
</RouterDialog>
</RedPacketProvider>
<EVMWeb3ContextProvider>
<RedPacketProvider>
<RouterDialog
pageMap={{
[RedPacketTabs.tokens]: RoutePaths.CreateErc20RedPacket,
[RedPacketTabs.collectibles]: RoutePaths.CreateNftRedPacket,
}}
open
onClose={onClose}
classes={{ paper: classes.paper }}
maxWidth="xs"
fullWidth
independent>
<DialogContent className={classes.content}>
<RestorableScrollContext>
<RedPacketRoutes />
</RestorableScrollContext>
</DialogContent>
</RouterDialog>
</RedPacketProvider>
</EVMWeb3ContextProvider>
</MemoryRouter>
)
}
33 changes: 4 additions & 29 deletions packages/plugins/RedPacket/src/SiteAdaptor/RedPacket/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
/* eslint-disable no-irregular-whitespace */
import { msg } from '@lingui/core/macro'
import { useLingui } from '@lingui/react'
import { useLastRecognizedIdentity, usePostInfoDetails, usePostLink } from '@masknet/plugin-infra/content-script'
import { requestLogin, share } from '@masknet/plugin-infra/content-script/context'
import { LoadingStatus, TransactionConfirmModal } from '@masknet/shared'
import { EMPTY_LIST, EnhanceableSite, NetworkPluginID, Sniffings } from '@masknet/shared-base'
import { EMPTY_LIST, NetworkPluginID, Sniffings } from '@masknet/shared-base'
import { queryClient } from '@masknet/shared-base-ui'
import { makeStyles } from '@masknet/theme'
import type { HappyRedPacketV4 } from '@masknet/web3-contracts/types/HappyRedPacketV4.js'
Expand Down Expand Up @@ -77,7 +76,8 @@ export const RedPacket = memo(function RedPacket({ payload }: RedPacketProps) {
const { _ } = useLingui()
const token = payload.token
const { pluginID } = useNetworkContext()
const payloadChainId = token?.chainId ?? EVMChainResolver.chainId(payload.network ?? '') ?? ChainId.Mainnet
const payloadChainId: ChainId =
(token?.chainId as ChainId) ?? EVMChainResolver.chainId(payload.network ?? '') ?? ChainId.Mainnet
const { account } = useChainContext<NetworkPluginID.PLUGIN_EVM>({
chainId: payloadChainId,
account: pluginID === NetworkPluginID.PLUGIN_EVM ? undefined : '',
Expand All @@ -101,10 +101,8 @@ export const RedPacket = memo(function RedPacket({ payload }: RedPacketProps) {
const postLink = usePostLink()

const [{ loading: isClaiming, value: claimTxHash }, claimCallback] = useClaimCallback(account, payload)
const site = usePostInfoDetails.site()
const source = usePostInfoDetails.source()
const platform = source?.toLowerCase()
const isOnFirefly = site === EnhanceableSite.Firefly
const postUrl = usePostInfoDetails.url()
const handle = usePostInfoDetails.handle()
const link = postLink.toString() || postUrl?.toString()
Expand All @@ -114,30 +112,7 @@ export const RedPacket = memo(function RedPacket({ payload }: RedPacketProps) {

const getShareText = useCallback(
(hasClaimed: boolean) => {
const sender = (handle ?? '').replace(/^@/, '')
const promote_short = _(msg`🧧🧧🧧 Try sending Lucky Drop to your friends with Mask.io.`)
const farcaster_lens_claimed =
_(msg`🤑 Just claimed a #LuckyDrop 🧧💰✨ on https://firefly.mask.social from @${sender} !`) +
'\n\n' +
_(msg`Claim on Lens: ${link}`)
const notClaimed =
_(msg`🤑 Check this Lucky Drop 🧧💰✨ sent by @${sender}.`) +
'\n\n' +
_(
msg`Grow your followers and engagement with Lucky Drop on Firefly mobile app or https://firefly.mask.social !`,
) +
'\n'
if (isOnFirefly) {
if (platform === 'farcaster') {
if (hasClaimed) {
return farcaster_lens_claimed
} else return notClaimed + '\n' + _(msg`Claim on Farcaster: ${link}`)
} else if (platform === 'lens') {
if (hasClaimed) {
return farcaster_lens_claimed
} else return notClaimed + '\n' + _(msg`Claim on Lens: ${link}`)
} else return notClaimed + '\n' + _(msg`Claim on: ${link}`)
}
const isOnTwitter = Sniffings.is_twitter_page
const isOnFacebook = Sniffings.is_facebook_page
const shareTextOption = {
Expand Down Expand Up @@ -165,7 +140,7 @@ export const RedPacket = memo(function RedPacket({ payload }: RedPacketProps) {
`\n${promote_short}\n#mask_io #LuckyDrop\n${shareTextOption.payload}`
: `${head}\n${promote_short}\n${shareTextOption.payload}`
},
[payload, link, claimTxHash, network?.name, platform, isOnFirefly, handle, _],
[payload, link, claimTxHash, network?.name, platform, handle, _],
)
const claimedShareText = useMemo(() => getShareText(true), [getShareText])

Expand Down
Loading

0 comments on commit ba1f969

Please sign in to comment.