Skip to content

Commit

Permalink
Merge branch 'refs/heads/telegram-dev' into koni/dev/issue-103
Browse files Browse the repository at this point in the history
  • Loading branch information
anhnhu committed Aug 15, 2024
2 parents f8a03e4 + b964caf commit eef4a12
Show file tree
Hide file tree
Showing 39 changed files with 299 additions and 172 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default class BeforeCreditcoinCampaign extends BaseMigrationJob {
public override async run (): Promise<void> {
const state = this.state;

await state.chainService.updateAssetSetting('creditcoin-NATIVE-CTC', { visible: true });
// await state.chainService.updateAssetSetting('creditcoin-NATIVE-CTC', { visible: true });
await state.chainService.updateAssetSetting('creditcoinTest-NATIVE-CTC', { visible: true });
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Copyright 2019-2022 @subwallet/extension-koni authors & contributors
// SPDX-License-Identifier: Apache-2.0

import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';

export default class BeforeCreditcoinCampaign2 extends BaseMigrationJob {
public override async run (): Promise<void> {
const state = this.state;

await new Promise((resolve) => setTimeout(resolve, 300));
state.chainService.disableChain('creditcoin');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import MigrateRemoveGenesisHash from '@subwallet/extension-base/services/migrati
import MigrateTransactionHistoryBySymbol from '@subwallet/extension-base/services/migration-service/scripts/MigrateTransactionHistoryBySymbol';

import BaseMigrationJob from '../Base';
import BeforeCreditcoinCampaign2
from "@subwallet/extension-base/services/migration-service/scripts/BeforeCreditcoinCampaign2";

export const EVERYTIME = '__everytime__';

Expand Down Expand Up @@ -42,5 +44,6 @@ export default <Record<string, typeof BaseMigrationJob>>{
'1.1.69-02': MigrateTransactionHistoryBySymbol,
'1.1.69-04': MigrateRemoveGenesisHash,
'1.2.10-p3': BeforeVaraCampaign,
'1.2.10-p4': BeforeCreditcoinCampaign
'1.2.10-p4': BeforeCreditcoinCampaign,
'1.2.10-p5': BeforeCreditcoinCampaign2
};
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import styled from 'styled-components';

type Props = ThemeProps & {
airdropHistory: AirdropRewardHistoryLog | null;
onClaim: (airdrop_record_id: number) => void;
onClaim: (airdrop_record_id: number) => Promise<void>;
};

function Component ({ airdropHistory, className, onClaim }: Props) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ function Component (props: Props): React.ReactElement<Props> {
const [isShareClaimed, setIsShareClaimed] = useState<boolean>(false);
const [loadingShare, setLoadingShare] = useState(false);

const _onClaim = useCallback(() => {
onClaim();
}, [onClaim]);

const onClickShare = useCallback(async () => {
if (!currentAirdrop) {
return;
Expand Down Expand Up @@ -126,7 +130,7 @@ function Component (props: Props): React.ReactElement<Props> {
/>
}
loading={isLoading}
onClick={onClaim}
onClick={_onClaim}
shape={'round'}
size={'sm'}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const Component: React.FC<Props> = ({ className, currentAirdrop }: Props) => {

const fetchHistory = useCallback(async () => {
try {
const data = await apiSDK.fetchAirdropHistory(currentAirdrop.airdrop_campaign_id) as AirdropRewardHistoryLog;
const data = await apiSDK.fetchAirdropHistory(currentAirdrop.airdrop_campaign_id);

if (data) {
setAirdropHistory(data);
Expand Down Expand Up @@ -179,7 +179,7 @@ const Component: React.FC<Props> = ({ className, currentAirdrop }: Props) => {
const onRaffle = useCallback(async () => {
try {
setIsLoadingRaffle(true);
const raffleResult = await apiSDK.raffleAirdrop(currentAirdrop.airdrop_campaign_id) as AirdropRaffle;
const raffleResult = await apiSDK.raffleAirdrop(currentAirdrop.airdrop_campaign_id);

setRaffle(raffleResult);
activeModal(rewardModalId);
Expand All @@ -204,10 +204,10 @@ const Component: React.FC<Props> = ({ className, currentAirdrop }: Props) => {
try {
let airdropRecordLogId;

if (raffle) {
airdropRecordLogId = raffle.airdropRecordLogId;
} else if (airdropRecordId !== undefined) {
if (airdropRecordId !== undefined) {
airdropRecordLogId = airdropRecordId;
} else if (raffle) {
airdropRecordLogId = raffle.airdropRecordLogId;
} else {
throw new Error('No airdrop record ID available');
}
Expand Down
39 changes: 28 additions & 11 deletions packages/extension-koni-ui/src/Popup/Home/Airdrop/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,41 @@ const AirdropComponent: React.FC<Props> = ({ className }) => {
const [airdropCampaign, setAirdropCampaign] = useState<AirdropCampaign[]>(apiSDK.airdropCampaignList);

const orderAirdropCampaign = useMemo(() => {
return [...airdropCampaign].sort((a, b) => {
if (a.start === null && b.start === null) {
return 0;
const futureList: AirdropCampaign[] = [];
const nowList: AirdropCampaign[] = [];
const pastList: AirdropCampaign[] = [];

airdropCampaign.forEach((campaign) => {
const now = Date.now();
const start = new Date(campaign.start).getTime();
const end = new Date(campaign.end).getTime();

if (now < start) {
futureList.push(campaign);
} else if (now > end) {
pastList.push(campaign);
} else {
nowList.push(campaign);
}
});

if (a.start === null) {
return -1;
function sortByStart (a: AirdropCampaign, b: AirdropCampaign) {
if (!a.start || !b.start) {
return 0;
}

if (b.start === null) {
return 1;
return new Date(a.start).getTime() - new Date(b.start).getTime();
}

function sortByStartDesc (a: AirdropCampaign, b: AirdropCampaign) {
if (!a.start || !b.start) {
return 0;
}

const aTime = new Date(a.end).getTime();
const bTime = new Date(b.end).getTime();
return new Date(b.start).getTime() - new Date(a.start).getTime();
}

return bTime - aTime;
});
return [...nowList.sort(sortByStartDesc), ...futureList.sort(sortByStart), ...pastList];
}, [airdropCampaign]);

const onExplore = useCallback((campaignId: number) => {
Expand Down
21 changes: 19 additions & 2 deletions packages/extension-koni-ui/src/Popup/Home/Games/gameSDK.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { SWStorage } from '@subwallet/extension-base/storage';
import { addLazy, createPromiseHandler, removeLazy } from '@subwallet/extension-base/utils';
import { BookaSdk } from '@subwallet/extension-koni-ui/connector/booka/sdk';
import { Game } from '@subwallet/extension-koni-ui/connector/booka/types';
import { TelegramConnector } from '@subwallet/extension-koni-ui/connector/telegram';
import { camelCase } from 'lodash';
import z from 'zod';

Expand All @@ -18,6 +19,7 @@ export interface GameAppOptions {
}

const cloudStorage = SWStorage.instance;
const telegramConnector = TelegramConnector.instance;

export class GameApp {
private listener = this._onMessage.bind(this);
Expand Down Expand Up @@ -268,6 +270,11 @@ export class GameApp {

async getLatestGameState () {
const skd = this.apiSDK;

while (!this.currentGameInfo?.id) {
await new Promise((resolve) => setTimeout(resolve, 300));
}

const gameId = this.currentGameInfo.id;

if (this.currentGameInfo.gameType !== 'farming') {
Expand Down Expand Up @@ -318,9 +325,19 @@ export class GameApp {
state = storageState;
}

await this.onPlay();
try {
await this.onPlay();

this.gameStateHandler.resolve(state || {} as GameState<any>);
this.gameStateHandler.resolve(state || {} as GameState<any>);
} catch (e) {
this.onExit();
telegramConnector.showAlert('Not enough energy to play', () => {
console.log('alert closed');
});
throw e;
} finally {
await this.apiSDK.reloadAccount().catch(console.error);
}
}

private async _onMessage (event: MessageEvent) {
Expand Down
30 changes: 28 additions & 2 deletions packages/extension-koni-ui/src/Popup/Home/Games/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { WalletModalContext } from '@subwallet/extension-koni-ui/contexts/Wallet
import { useSetCurrentPage } from '@subwallet/extension-koni-ui/hooks';
import { GameApp } from '@subwallet/extension-koni-ui/Popup/Home/Games/gameSDK';
import { ThemeProps } from '@subwallet/extension-koni-ui/types';
import { populateTemplateString } from '@subwallet/extension-koni-ui/utils';
import { isDesktop, isMobile, populateTemplateString } from '@subwallet/extension-koni-ui/utils';
import { ModalContext } from '@subwallet/react-ui';
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
Expand Down Expand Up @@ -76,8 +76,34 @@ const Component = ({ className }: Props): React.ReactElement => {
}, 600);
}, []);

const checkAccess = useCallback((game: Game) => {
const restrictedAccess = game.restrictedAccess || [];

if (restrictedAccess.length > 0) {
if (isDesktop() && restrictedAccess.indexOf('desktop') > -1) {
return false;
}

if (isMobile() && restrictedAccess.indexOf('mobile') > -1) {
return false;
}
}

return true;
}, []);

const playGame = useCallback((game: Game) => {
return () => {
if (!checkAccess(game)) {
const alertContent = game.restrictedAccessText || 'This game is not available on your device';

telegramConnector.showAlert(alertContent, () => {
// Do nothing
});

return;
}

setCurrentGame(game);

const checkInterval = setInterval(() => {
Expand All @@ -95,7 +121,7 @@ const Component = ({ className }: Props): React.ReactElement => {
}
}, 30);
};
}, [exitGame]);
}, [checkAccess, exitGame]);

// @ts-ignore
const onOpenShop = useCallback((gameId?: number) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,6 @@ const Component = ({ className }: Props): React.ReactElement => {

const taskListSub = apiSDK.subscribeTaskList().subscribe((data) => {
clearInterval(taskListUpdaterInterval);
console.log('data', data)

setTaskCategoryInfoMap(getTaskCategoryInfoMap(data));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ function Component ({ className = '' }: Props): React.ReactElement<Props> {
title={t('Wallet theme')}
/>

<SettingItem
{false && <SettingItem
className={'__setting-item setting-group-item'}
leftItemIcon={(
<BackgroundIcon
Expand All @@ -263,7 +263,7 @@ function Component ({ className = '' }: Props): React.ReactElement<Props> {
type='phosphor'
/>
}
/>
/>}
</div>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,24 @@ import styled from 'styled-components';

type Props = {
item: AirdropRewardHistoryLog,
onClaim: (airdrop_record_id: number) => void;
onClaim: (airdrop_record_id: number) => Promise<void>;
} & ThemeProps;

const Component = ({ className, item, onClaim }: Props): React.ReactElement => {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState<boolean>(false);
const logoMaps = useSelector((state: RootState) => state.settings.logoMaps).assetLogoMap;

const _onClaim = useCallback(async (airdropRcordId: number) => {
const _onClaim = useCallback(async () => {
setIsLoading(true);

try {
await onClaim(airdropRcordId);
await onClaim(item.id);
setIsLoading(false);
} catch (error) {
setIsLoading(false);
}
}, [onClaim]);
}, [item.id, onClaim]);

const renderDate = () => {
let content: string;
Expand Down Expand Up @@ -94,7 +94,7 @@ const Component = ({ className, item, onClaim }: Props): React.ReactElement => {
<Button
className={'-primary-2'}
loading={isLoading}
onClick={() => _onClaim(item.id)}
onClick={_onClaim}
shape={'round'}
size={'xs'}
>
Expand Down
20 changes: 10 additions & 10 deletions packages/extension-koni-ui/src/components/Layout/base/Base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,6 @@ const Component = ({ backgroundImages, backgroundStyle, children, className, hea
const { language } = useSelector((state) => state.settings);

const tabBarItems = useMemo((): Array<Omit<SwTabBarItem, 'onClick'> & { url: string }> => ([
{
icon: {
type: 'phosphor',
phosphorIcon: Wallet,
weight: 'fill'
},
label: t('Wallet'),
key: 'tokens',
url: '/home/tokens'
},
{
icon: {
type: 'customIcon',
Expand Down Expand Up @@ -95,6 +85,16 @@ const Component = ({ backgroundImages, backgroundStyle, children, className, hea
label: t('Airdrop'),
key: 'airdrop',
url: '/home/airdrop'
},
{
icon: {
type: 'phosphor',
phosphorIcon: Wallet,
weight: 'fill'
},
label: t('Wallet'),
key: 'tokens',
url: '/home/tokens'
}
// {
// icon: {
Expand Down
8 changes: 4 additions & 4 deletions packages/extension-koni-ui/src/connector/booka/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { InGameItem } from '@playnation/game-sdk';
import { GameState } from '@playnation/game-sdk/dist/types';
import { SWStorage } from '@subwallet/extension-base/storage';
import { createPromiseHandler, detectTranslate } from '@subwallet/extension-base/utils';
import { AccountRankType, AirdropCampaign, AirdropEligibility, BookaAccount, EnergyConfig, Game, GameInventoryItem, GameItem, GamePlay, LeaderboardPerson, RankInfo, ReferralRecord, Task, TaskCategory } from '@subwallet/extension-koni-ui/connector/booka/types';
import { AccountRankType, AirdropCampaign, AirdropEligibility, AirdropRaffle, AirdropRewardHistoryLog, BookaAccount, EnergyConfig, Game, GameInventoryItem, GameItem, GamePlay, LeaderboardPerson, RankInfo, ReferralRecord, Task, TaskCategory } from '@subwallet/extension-koni-ui/connector/booka/types';
import { TelegramConnector } from '@subwallet/extension-koni-ui/connector/telegram';
import { signRaw } from '@subwallet/extension-koni-ui/messaging';
import { populateTemplateString } from '@subwallet/extension-koni-ui/utils';
Expand Down Expand Up @@ -199,7 +199,7 @@ export class BookaSdk {
return await response.json() as T;
}

private async reloadAccount () {
async reloadAccount () {
const account = this.account;
const newAccountData = await this.getRequest<Omit<BookaAccount, 'token'>>(`${GAME_API_HOST}/api/account/get-attribute`);

Expand Down Expand Up @@ -765,7 +765,7 @@ export class BookaSdk {
// airdrop raffle
async raffleAirdrop (campaignId: number) {
try {
const raffle = await this.postRequest(`${GAME_API_HOST}/api/airdrop/raffle`, { campaign_id: campaignId });
const raffle = await this.postRequest<AirdropRaffle>(`${GAME_API_HOST}/api/airdrop/raffle`, { campaign_id: campaignId });

await this.fetchAirdropCampaign();
await this.reloadAccount();
Expand All @@ -780,7 +780,7 @@ export class BookaSdk {
// airdrop history
async fetchAirdropHistory (campaignId: number) {
try {
return await this.postRequest(`${GAME_API_HOST}/api/airdrop/history`, { campaign_id: campaignId });
return await this.postRequest<AirdropRewardHistoryLog>(`${GAME_API_HOST}/api/airdrop/history`, { campaign_id: campaignId });
} catch (error) {
console.error('Error in fetchAirdropHistory:', error);
throw error;
Expand Down
2 changes: 2 additions & 0 deletions packages/extension-koni-ui/src/connector/booka/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ export interface Game {
pointConversionRate: number;
gameType: 'casual' | 'farming';
leaderboard_groups: LeaderboardGroups[];
restrictedAccess: string[] | null;
restrictedAccessText: string | null;
}

export enum TaskHistoryStatus {
Expand Down
Loading

0 comments on commit eef4a12

Please sign in to comment.