Skip to content

Commit

Permalink
[Add] - Add offramp form data
Browse files Browse the repository at this point in the history
  • Loading branch information
tunghp2002 committed Oct 29, 2024
1 parent 068b04c commit 0c8a38e
Show file tree
Hide file tree
Showing 11 changed files with 111 additions and 19 deletions.
6 changes: 5 additions & 1 deletion packages/extension-base/src/services/chain-service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { EventService } from '@subwallet/extension-base/services/event-service';
import { IChain, IMetadataItem } from '@subwallet/extension-base/services/storage-service/databases';
import DatabaseService from '@subwallet/extension-base/services/storage-service/DatabaseService';
import AssetSettingStore from '@subwallet/extension-base/stores/AssetSetting';
import { addLazy, calculateMetadataHash, fetchStaticData, filterAssetsByChainAndType, getShortMetadata, MODULE_SUPPORT } from '@subwallet/extension-base/utils';
import { addLazy, calculateMetadataHash, fetchStaticData, filterAssetsByChainAndSymbol, filterAssetsByChainAndType, getShortMetadata, MODULE_SUPPORT } from '@subwallet/extension-base/utils';
import { BehaviorSubject, Subject } from 'rxjs';
import Web3 from 'web3';

Expand Down Expand Up @@ -453,6 +453,10 @@ export class ChainService {
return filterAssetsByChainAndType(this.getAssetRegistry(), chainSlug, assetTypes);
}

public getAssetByChainAndSymbol (chainSlug: string, symbol: string) {
return filterAssetsByChainAndSymbol(this.getAssetRegistry(), chainSlug, symbol);
}

public getSmartContractNfts () {
const result: _ChainAsset[] = [];

Expand Down
10 changes: 10 additions & 0 deletions packages/extension-base/src/utils/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,13 @@ export const filterAssetsByChainAndType = (chainAssetMap: Record<string, _ChainA

return result;
};

export const filterAssetsByChainAndSymbol = (chainAssetMap: Record<string, _ChainAsset>, chain: string, symbol: string): _ChainAsset | null => {
for (const assetInfo of Object.values(chainAssetMap)) {
if (assetInfo.originChain === chain && assetInfo.symbol === symbol) {
return assetInfo;
}
}

return null;
};
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,7 @@ const _SendFund = ({ className = '' }: Props): React.ReactElement<Props> => {

const onValuesChange: FormCallbacks<TransferParams>['onValuesChange'] = useCallback(
(part: Partial<TransferParams>, values: TransferParams) => {
console.debug('changes', part);
const validateField: string[] = [];

if (part.from) {
Expand Down
24 changes: 21 additions & 3 deletions packages/extension-web-ui/src/Popup/BuyTokens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ function Component ({ className, modalContent, slug }: Props) {
return false;
}, [selectedService, selectedAddress, selectedTokenKey, tokens, tokenItems]);

const onClickNext = useCallback(() => {
const onClickNext = useCallback((action: 'BUY' | 'SELL') => {
setLoading(true);

const { address, service, tokenKey } = form.getFieldsValue();
Expand Down Expand Up @@ -255,7 +255,7 @@ function Component ({ className, modalContent, slug }: Props) {

disclaimerPromise.then(() => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return urlPromise!(symbol, walletAddress, serviceNetwork, walletReference);
return urlPromise!(symbol, walletAddress, serviceNetwork, walletReference, action);
})
.then((url) => {
openInNewTab(url)();
Expand Down Expand Up @@ -438,11 +438,29 @@ function Component ({ className, modalContent, slug }: Props) {
/>
)}
loading={loading}
onClick={onClickNext}
// eslint-disable-next-line react/jsx-no-bind
onClick={() => onClickNext('BUY')}
>
{t('Buy now')}
</Button>
</div>
<div className={'__layout-footer'}>
<Button
color={'red'}
disabled={!isSupportBuyTokens}
icon={ (
<Icon
phosphorIcon={ShoppingCartSimple}
weight={'fill'}
/>
)}
loading={loading}
// eslint-disable-next-line react/jsx-no-bind
onClick={() => onClickNext('SELL')}
>
{t('Sell now')}
</Button>
</div>
<BaseModal
center={true}
className={CN(className)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,12 +239,15 @@ const _SendFund = ({ className = '', modalContent }: Props): React.ReactElement<
};
}, [defaultData]);

console.log('Whats wrong here', defaultData);
const destChain = useWatchTransaction('destChain', form, defaultData);
const transferAmount = useWatchTransaction('value', form, defaultData);
const from = useWatchTransaction('from', form, defaultData);
const chain = useWatchTransaction('chain', form, defaultData);
const asset = useWatchTransaction('asset', form, defaultData);

console.log('Checking', [defaultData, from, asset]);

const assetInfo = useFetchChainAssetInfo(asset);
const { alertProps, closeAlert, openAlert } = useAlert(alertModalId);

Expand Down Expand Up @@ -285,6 +288,9 @@ const _SendFund = ({ className = '', modalContent }: Props): React.ReactElement<
const currentChainAsset = useMemo(() => {
const _asset = isFirstRender ? defaultData.asset : asset;

console.log('Yp', asset);
console.log(_asset, isFirstRender, assetRegistry[_asset]);

return _asset ? assetRegistry[_asset] : undefined;
}, [isFirstRender, defaultData.asset, asset, assetRegistry]);

Expand Down Expand Up @@ -313,7 +319,7 @@ const _SendFund = ({ className = '', modalContent }: Props): React.ReactElement<
const destChainGenesisHash = chainInfoMap[destChain]?.substrateInfo?.genesisHash || '';

const tokenItems = useMemo<TokenItemType[]>(() => {
return getTokenItems(
console.debug('tokenItems',
from,
accounts,
chainInfoMap,
Expand All @@ -322,7 +328,22 @@ const _SendFund = ({ className = '', modalContent }: Props): React.ReactElement<
multiChainAssetMap,
sendFundSlug,
isZKModeEnabled
);
)

const result = getTokenItems(
from,
accounts,
chainInfoMap,
assetRegistry,
assetSettingMap,
multiChainAssetMap,
sendFundSlug,
isZKModeEnabled
)

console.debug('tokenItems', result);

return result;
}, [accounts, assetRegistry, assetSettingMap, chainInfoMap, from, isZKModeEnabled, multiChainAssetMap, sendFundSlug]);

const validateRecipientAddress = useCallback((rule: Rule, _recipientAddress: string): Promise<void> => {
Expand Down Expand Up @@ -719,6 +740,7 @@ const _SendFund = ({ className = '', modalContent }: Props): React.ReactElement<
}
}
} else {
updateInfoWithTokenSlug(asset);
// Apply default asset if current asset is not in token list
isApplyDefaultAsset = !tokenItems.some((i) => i.slug === asset);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ function Component (props: Props, ref: ForwardedRef<InputRef>): React.ReactEleme

return chainAsset ? filterFunction(chainAsset) : false;
});
console.debug('filteredItems', assetRegistry, items, raw);

raw.sort((a, b) => {
return convertChainActivePriority(chainStateMap[b.originChain]?.active) - convertChainActivePriority(chainStateMap[a.originChain]?.active);
Expand Down Expand Up @@ -155,7 +156,8 @@ function Component (props: Props, ref: ForwardedRef<InputRef>): React.ReactEleme
const existed = filteredItems.find((item) => item.slug === value);

if (!existed) {
onSelect(filteredItems[0]?.slug || '');
console.log('Was here');
// onSelect(filteredItems[0]?.slug || '');
}
}
}, [value, filteredItems, onSelect]);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2019-2022 @polkadot/extension-ui authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { balanceNoPrefixFormater, formatNumber } from '@subwallet/extension-base/utils';
import { balanceNoPrefixFormater, filterAssetsByChainAndSymbol, formatNumber, toBNString } from '@subwallet/extension-base/utils';
import { ReceiveQrModal, TokensSelectorModal } from '@subwallet/extension-web-ui/components/Modal';
import { AccountSelectorModal } from '@subwallet/extension-web-ui/components/Modal/AccountSelectorModal';
import { BaseModal } from '@subwallet/extension-web-ui/components/Modal/BaseModal';
Expand Down Expand Up @@ -36,7 +36,24 @@ type Action = {
disabled?: boolean
}

function useQuery () {
return new URLSearchParams(useLocation().search);
}

function Component ({ className }: Props): React.ReactElement<Props> {
// Pathname query
const query = useQuery();
const orderId = query.get('orderId');
const partnerCustomerId = query.get('partnerCustomerId') || '';
const cryptoCurrency = query.get('cryptoCurrency') || '';
const cryptoAmount = query.get('cryptoAmount') || '';
const numericCryptoAmount = parseFloat(cryptoAmount);
const walletAddress = query.get('walletAddress') || '';
const network = query.get('network') || '';
const { assetRegistry } = useSelector((state) => state.assetRegistry);
const Testing = filterAssetsByChainAndSymbol(assetRegistry, network, cryptoCurrency);
const bnAmount = toBNString(!isNaN(numericCryptoAmount) ? numericCryptoAmount.toString() : '0', Testing?.decimals || 0);

const dataContext = useContext(DataContext);
const { isWebUI } = useContext(ScreenContext);
const { setBackground } = useContext(WebUIContext);
Expand Down Expand Up @@ -147,18 +164,30 @@ function Component ({ className }: Props): React.ReactElement<Props> {
return;
}

const address = currentAccount ? isAccountAll(currentAccount.address) ? '' : currentAccount.address : '';
const address = currentAccount ? (isAccountAll(currentAccount.address) ? partnerCustomerId : currentAccount.address) : '';

setStorage({
...DEFAULT_TRANSFER_PARAMS,
chain: Testing?.originChain || '',
destChain: Testing?.originChain || '',
asset: Testing?.slug || '',
from: address,
defaultSlug: tokenGroupSlug || ''
defaultSlug: Testing?.slug || tokenGroupSlug || '',
to: walletAddress,
value: bnAmount.toString()
});
activeModal(TRANSACTION_TRANSFER_MODAL);
},
[currentAccount, setStorage, tokenGroupSlug, activeModal, notify, t]
[currentAccount, setStorage, activeModal, notify, t, tokenGroupSlug, partnerCustomerId, walletAddress, bnAmount, Testing]
);

// Auto open when exists ID
useEffect(() => {
if (orderId) {
onOpenSendFund();
}
}, [orderId, onOpenSendFund]);

useEffect(() => {
setSendFundKey(`sendFundKey-${Date.now()}`);
setBuyTokensKey(`buyTokensKey-${Date.now()}`);
Expand Down
2 changes: 1 addition & 1 deletion packages/extension-web-ui/src/constants/buy/transak.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
export const TRANSAK_API_KEY = process.env.TRANSAK_API_KEY || '4b767e2c-2e01-45c9-978e-d32c6f0c8900';
export const TRANSAK_TEST_MODE = process.env.TRANSAK_TEST_MODE !== undefined ? !!process.env.TRANSAK_TEST_MODE : true;

export const TRANSAK_URL = TRANSAK_TEST_MODE ? 'https://global-stg.transak.com/' : 'https://global.transak.com';
export const TRANSAK_URL = 'https://global.transak.com';
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const useWatchTransaction = <T extends TransactionFormBaseProps, K extends keyof
const isFirstRender = useIsFirstRender();
const watch = Form.useWatch(key, form);

console.log('Watching',[key, watch]);

return isFirstRender ? defaultData[key] : watch;
};

Expand Down
2 changes: 1 addition & 1 deletion packages/extension-web-ui/src/types/buy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ export interface BuyServiceInfo {
url: string;
}

export type CreateBuyOrderFunction = (token: string, address: string, network: string, walletReference: string) => Promise<string>;
export type CreateBuyOrderFunction = (token: string, address: string, network: string, walletReference: string, action: 'BUY' | 'SELL') => Promise<string>;
16 changes: 10 additions & 6 deletions packages/extension-web-ui/src/utils/buy/transak.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@ import { TRANSAK_API_KEY, TRANSAK_URL } from '@subwallet/extension-web-ui/consta
import { CreateBuyOrderFunction } from '@subwallet/extension-web-ui/types';
import qs from 'querystring';

export const createTransakOrder: CreateBuyOrderFunction = (symbol, address, network) => {
export const createTransakOrder: CreateBuyOrderFunction = (symbol, address, network, walletReference, action) => {
return new Promise((resolve) => {
const params = {
apiKey: TRANSAK_API_KEY,
defaultCryptoCurrency: symbol,
networks: network,
cryptoCurrencyList: symbol,
walletAddress: address
apiKey: '307807a5-5fb3-4add-8a6c-fca4972e0470',
defaultCryptoCurrency: 'USDT',
networks: 'ethereum',
cryptoCurrencyList: 'USDT',
walletAddress: address,
partnerCustomerId: address,
productsAvailed: action,
redirectURL: 'http://192.168.5.103:9000/home/tokens',
walletRedirection: true
};

const query = qs.stringify(params);
Expand Down

0 comments on commit 0c8a38e

Please sign in to comment.