Skip to content

Commit

Permalink
Merge remote-tracking branch 'refs/remotes/origin/koni/dev/issue-177'…
Browse files Browse the repository at this point in the history
… into story-protocol-od-dev

# Conflicts:
#	packages/extension-koni-ui/src/connector/booka/sdk.ts
  • Loading branch information
Thiendekaco committed Nov 26, 2024
2 parents 738e38a + aa7e92d commit af4df68
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 86 deletions.
58 changes: 40 additions & 18 deletions packages/extension-base/src/koni/background/handlers/Extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { createTransferExtrinsic, getTransferMockTxFee } from '@subwallet/extens
import { createSnowBridgeExtrinsic, createXcmExtrinsic, getXcmMockTxFee } from '@subwallet/extension-base/services/balance-service/transfer/xcm';
import { _API_OPTIONS_CHAIN_GROUP, _DEFAULT_MANTA_ZK_CHAIN, _MANTA_ZK_CHAIN_GROUP, _ZK_ASSET_PREFIX } from '@subwallet/extension-base/services/chain-service/constants';
import { _ChainApiStatus, _ChainConnectionStatus, _ChainState, _NetworkUpsertParams, _ValidateCustomAssetRequest, _ValidateCustomAssetResponse, EnableChainParams, EnableMultiChainParams } from '@subwallet/extension-base/services/chain-service/types';
import { _getAssetDecimals, _getAssetSymbol, _getChainNativeTokenBasicInfo, _getContractAddressOfToken, _getEvmChainId, _getSubstrateGenesisHash, _isAssetSmartContractNft, _isChainEvmCompatible, _isCustomAsset, _isLocalToken, _isMantaZkAsset, _isNativeToken, _isPureEvmChain, _isTokenEvmSmartContract, _isTokenTransferredByEvm } from '@subwallet/extension-base/services/chain-service/utils';
import { _getAssetDecimals, _getAssetSymbol, _getChainNativeTokenBasicInfo, _getContractAddressOfToken, _getEvmChainId, _getSubstrateGenesisHash, _isAssetSmartContractNft, _isChainEvmCompatible, _isCustomAsset, _isLocalToken, _isMantaZkAsset, _isNativeToken, _isPureEvmChain, _isSubstrateChain, _isTokenEvmSmartContract, _isTokenTransferredByEvm } from '@subwallet/extension-base/services/chain-service/utils';
import { EXTENSION_REQUEST_URL } from '@subwallet/extension-base/services/request-service/constants';
import { AuthUrls } from '@subwallet/extension-base/services/request-service/types';
import { DEFAULT_AUTO_LOCK_TIME } from '@subwallet/extension-base/services/setting-service/constants';
Expand Down Expand Up @@ -64,7 +64,7 @@ import { TransactionConfig } from 'web3-core';
import { SubmittableExtrinsic } from '@polkadot/api/types';
import { TypeRegistry } from '@polkadot/types';
import { SignerPayloadJSON, SignerPayloadRaw } from '@polkadot/types/types';
import { assert, hexStripPrefix, hexToU8a, isAscii, isHex, u8aToHex, u8aToString } from '@polkadot/util';
import { assert, hexStripPrefix, hexToU8a, isAscii, isHex, stringToHex, u8aToHex, u8aToString } from '@polkadot/util';
import { base64Decode, decodeAddress, isAddress, isEthereumAddress, jsonDecrypt, keyExtractSuri, mnemonicGenerate, mnemonicValidate } from '@polkadot/util-crypto';
import { EncryptedJson, KeypairType, Prefix } from '@polkadot/util-crypto/types';

Expand Down Expand Up @@ -4124,26 +4124,48 @@ export default class KoniExtension {
}

private async remarkWithEvent (request: RemarkWithEvent): Promise<SWTransactionResponse> {
const address = request.address;
const networkKey = request.networkKey;
const apiProps = this.#koniState.getSubstrateApi(networkKey);
const { address, dataRemark, networkKey } = request;
const chainInfo = this.#koniState.getChainInfo(networkKey);

if (!apiProps) {
return;
if (!chainInfo) {
throw new Error(t('Invalid network'));
}

const transaction = apiProps.api.tx.system.remarkWithEvent(request.dataRemark);
const rs = await this.#koniState.transactionService.handleTransaction({
address: address,
chain: networkKey,
transaction: transaction,
extrinsicType: ExtrinsicType.REMARK_WITH_EVENT,
chainType: ChainType.SUBSTRATE,
resolveOnHasExtrinsicHash: true,
data: {}
});
const handleTransaction = async (transaction: SWTransaction['transaction'], chainType: ChainType) => {
return await this.#koniState.transactionService.handleTransaction({
address,
chain: networkKey,
transaction,
extrinsicType: ExtrinsicType.REMARK_WITH_EVENT,
chainType,
resolveOnHasExtrinsicHash: true,
data: transaction.data
});
};

return rs;
if (_isChainEvmCompatible(chainInfo)) {
const evmApi = this.#koniState.getEvmApiMap()[networkKey];

if (!evmApi) {
throw new Error(t('Invalid network'));
}

const [transaction] = await getEVMTransactionObject(chainInfo, address, address, '0', false, evmApi, stringToHex(dataRemark));

return await handleTransaction(transaction, ChainType.EVM);
} else if (_isSubstrateChain(chainInfo)) {
const apiProps = this.#koniState.getSubstrateApi(networkKey);

if (!apiProps) {
throw new Error(t('Invalid network'));
}

const transaction = apiProps.api.tx.system.remarkWithEvent(request.dataRemark);

return await handleTransaction(transaction, ChainType.SUBSTRATE);
}

throw new Error(t('Invalid network'));
}

/* Swap service */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export async function getEVMTransactionObject (
to: string,
value: string,
transferAll: boolean,
web3Api: _EvmApi
web3Api: _EvmApi,
data?: string
): Promise<[TransactionConfig, string]> {
const networkKey = chainInfo.slug;

Expand All @@ -30,7 +31,8 @@ export async function getEVMTransactionObject (
from: from,
gasPrice: priority.gasPrice,
maxFeePerGas: priority.maxFeePerGas?.toString(),
maxPriorityFeePerGas: priority.maxPriorityFeePerGas?.toString()
maxPriorityFeePerGas: priority.maxPriorityFeePerGas?.toString(),
data
} as TransactionConfig;

const gasLimit = await web3Api.api.eth.estimateGas(transactionObject);
Expand Down
120 changes: 59 additions & 61 deletions packages/extension-koni-ui/src/Popup/Home/Mission/TaskItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,48 @@ const _TaskItem = ({ actionReloadPoint, className, openWidget, reloadTask, task
setTaskLoading(true);
let res: SWTransactionResponse | null = null;
const payload: Record<string, unknown> = {};
const networkKey = task.network || '';
const networkKey = task.network || 'storyOdyssey_testnet';
const isNftTask = !!task.metadata?.contractAddress;

payload.networkKey = networkKey;

const getWcAddress = async (): Promise<string | null> => {
if (wcAccount) {
return wcAccount.address;
} else {
try {
await requireWC();

return await connectWC();
} catch (e) {
const error = e as Error;

setTaskLoading(false);

if (error.message?.toLowerCase().includes('Unsupported chains'.toLowerCase())) {
telegramConnector.showPopup({
message: t('Your chosen wallet hasn’t supported Story Odyssey Testnet. Add network to your wallet or change to another wallet'),
buttons: [{ type: 'ok', text: t('Got it') }]
}, noop);
}

return null;
}
}
};

if (onChainType) {
const wcAddress = await getWcAddress();

if (!wcAddress) {
setTaskLoading(false);

return;
}

const now = new Date();
const date = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
const data = JSON.stringify({ address, type: onChainType, date });
const data = JSON.stringify({ address: wcAddress, type: onChainType, date });

const checkCompleted = await apiSDK.completeTask(taskId);

Expand All @@ -160,18 +193,16 @@ const _TaskItem = ({ actionReloadPoint, className, openWidget, reloadTask, task
}
}

res = await actionTaskOnChain(onChainType, networkKey, address, data);

if ((res && res.errors.length > 0) || !res) {
setTaskLoading(false);
let message = t(`Network ${networkKey} not enable`);

if (res && res.errors.length > 0) {
const error = res?.errors[0] || {};
try {
res = await actionTaskOnChain(onChainType, networkKey, wcAddress, data);

// @ts-ignore
message = error?.message || '';
if ((res && res.errors.length > 0) || !res) {
throw new Error(res?.errors[0].message || 'Error');
}
} catch (error) {
console.error(error);
setTaskLoading(false);
const message = t((error as Error)?.message || '');

notify({
message: message,
Expand All @@ -187,45 +218,10 @@ const _TaskItem = ({ actionReloadPoint, className, openWidget, reloadTask, task
payload.extrinsicHash = res.extrinsicHash || '';
}

let shareLeaderboard: ShareLeaderboard | null = null;

if (task.share_leaderboard) {
try {
shareLeaderboard = JSON.parse(task.share_leaderboard) as ShareLeaderboard;
} catch (e) {
console.error('shareLeaderboard', e);
}
}

if (isNftTask) {
let address: string;

if (wcAccount) {
address = wcAccount.address;
} else {
try {
await requireWC();
address = await connectWC();
} catch (e) {
const error = e as Error;

setTaskLoading(false);
const wcAddress = await getWcAddress();

if (error.message?.toLowerCase().includes('Unsupported chains'.toLowerCase())) {
telegramConnector.showPopup({
message: t('Your chosen wallet hasn’t supported Story Odyssey Testnet. Add network to your wallet or change to another wallet'),
buttons: [{
type: 'ok',
text: t('Got it')
}]
}, noop);
}

return;
}
}

if (!address) {
if (!wcAddress) {
setTaskLoading(false);

return;
Expand All @@ -237,14 +233,13 @@ const _TaskItem = ({ actionReloadPoint, className, openWidget, reloadTask, task

try {
const rs = await wcSignMessageRequest({
address,
address: wcAddress,
chainId: WC_DEFAULT_CHAIN_ID,
payload: stringToHex(message),
method: 'personal_sign'
});

closeWaiting();

payload.signature = rs.signature;
payload.address = address;
} catch (e) {
Expand Down Expand Up @@ -305,19 +300,22 @@ const _TaskItem = ({ actionReloadPoint, className, openWidget, reloadTask, task
});

if (!task.airlyftId) {
setTimeout(async () => {
let urlRedirect = task.url;
setTimeout(() => {
(async () => {
let urlRedirect = task.url;

if (shareLeaderboard && shareLeaderboard.content) {
const startEnv = shareLeaderboard.start_time;
const endEnv = shareLeaderboard.end_time;
if (task.share_leaderboard) {
const shareLeaderboard = JSON.parse(task.share_leaderboard) as ShareLeaderboard;
const startEnv = shareLeaderboard.start_time;
const endEnv = shareLeaderboard.end_time;

urlRedirect = await apiSDK.getShareTwitterURL(startEnv, endEnv, shareLeaderboard.content, task.gameId ?? 0, shareLeaderboard.url);
}
urlRedirect = await apiSDK.getShareTwitterURL(startEnv, endEnv, shareLeaderboard.content, task.gameId ?? 0, shareLeaderboard.url);
}

if (urlRedirect) {
telegramConnector.openLink(urlRedirect);
}
if (urlRedirect) {
telegramConnector.openLink(urlRedirect);
}
})().catch(console.error);
}, 100);
}
})().catch(console.error);
Expand Down
2 changes: 1 addition & 1 deletion packages/extension-koni-ui/src/connector/booka/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -998,7 +998,7 @@ export class BookaSdk {
share: {
url_share: 'https://x.koni.studio/mint-badge',
content: `Odyssey Testnet is LIVE! Have fun with easy-peasy tasks and earn the exclusive Koni Story badge through your IPventure 👑
%0ALast chance to become an @StoryProtocol OG before mainn letaunch 💨
%0ALast chance to become an @StoryProtocol OG before mainnet launch 💨
%0AJoin now 👇`
},
description: `
Expand Down
25 changes: 21 additions & 4 deletions packages/extension-koni-ui/src/utils/game/task/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// [object Object]
// Copyright 2019-2022 @subwallet/extension-ui authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { SWTransactionResponse } from '@subwallet/extension-base/services/transaction-service/types';
Expand All @@ -13,11 +13,11 @@ export async function actionTaskOnChain (type: string, networkKey: string, addre
}

export async function sendRemarkWithEvent (address: string, networkKey: string, data: any): Promise<SWTransactionResponse> {
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const sendPromise = remarkWithEvent({
address,
networkKey: networkKey,
dataRemark: data
dataRemark: JSON.stringify(data)
});

setTimeout(() => {
Expand All @@ -26,8 +26,25 @@ export async function sendRemarkWithEvent (address: string, networkKey: string,
.then((res) => {
resolve(res);
}).catch((err) => {
console.error('sendRemarkWithEvent', err);
reject(new Error(convertErrorMessage(err as Error, networkKey)));
});
}, 100);
});
}

function convertErrorMessage (error: Error, networkKey: string): string {
const message = error.message.toLowerCase();

// Network error
if (
message.includes('connection error') ||
message.includes('connection not open') ||
message.includes('connection timeout') ||
message.includes('can not active chain') ||
message.includes('invalid json rpc')
) {
return `Network ${networkKey} not enable`;
}

return error.message;
}

0 comments on commit af4df68

Please sign in to comment.