Skip to content
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

✨ Implement transfer of custom tokens #128

Merged
merged 2 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/background/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,17 @@ export async function modifyEthBalance(amount: bigint) {
}
}

export async function sendToAccount(recipientAddr: string, amount: bigint) {
export async function sendToAccount(
recipientAddr: string,
amount: bigint,
tokenAddress: string = ETH_ADDRESS
) {
try {
const provider = await getProvider();
const acc = await getSelectedAccount();

const contract = await provider.getClassAt(ETH_ADDRESS);
const erc20 = new Contract(contract.abi, ETH_ADDRESS, provider);
const contract = await provider.getClassAt(tokenAddress);
const erc20 = new Contract(contract.abi, tokenAddress, provider);

erc20.connect(acc);
const balance = await erc20.balanceOf(acc.address);
Expand All @@ -170,6 +174,7 @@ export async function sendToAccount(recipientAddr: string, amount: bigint) {
entrypoint: 'transfer',
calldata: [recipientAddr, uint256.bnToUint256(amount)],
});

if (estimate.suggestedMaxFee > amount) {
transferResponse = await erc20.transfer(recipientAddr, amount + estimate.suggestedMaxFee);
} else {
Expand Down
24 changes: 20 additions & 4 deletions src/components/account/accountSend.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,29 @@ import {
Typography,
Container,
CircularProgress,
SelectChangeEvent,
} from '@mui/material';
import React, { useState, useCallback, FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { ChevronLeft } from '@mui/icons-material';
import { fetchCurrentBlockNumber } from '../../background/utils';
import { useSharedState } from '../context/context';
import { sendToAccount } from '../../background/contracts';
import { TokenDropdown } from './tokenDropdown';
import { ETH_ADDRESS } from '../../background/constants';

export const AccountSend: React.FC = () => {
const navigate = useNavigate();
const { selectedAccount, updateCurrentBalance, setLastFetchedUrl, setCurrentBlock } =
useSharedState();
const [formData, setFormData] = useState<{ recipient: string; amount: number }>({
const [formData, setFormData] = useState<{
recipient: string;
amount: number;
tokenAddress: string;
}>({
recipient: '',
amount: 0,
tokenAddress: '',
});
const [isSubmitting, setIsSubmitting] = useState(false);

Expand All @@ -41,8 +49,8 @@ export const AccountSend: React.FC = () => {
if (!formData.recipient || formData.amount <= 0) return;
setIsSubmitting(true);
const sendAmountWei = BigInt(formData.amount * 10 ** 18);
const balance = await sendToAccount(formData.recipient, sendAmountWei);
if (balance) {
const balance = await sendToAccount(formData.recipient, sendAmountWei, formData.tokenAddress);
if (balance && formData.tokenAddress === ETH_ADDRESS) {
await updateCurrentBalance(balance);
await updateCurrentBlockNumber();
}
Expand Down Expand Up @@ -80,6 +88,14 @@ export const AccountSend: React.FC = () => {
{!isSubmitting ? (
<>
<Stack textAlign={'left'} paddingX={3} spacing={3}>
<Box flex={1}>
<TokenDropdown
value={formData.tokenAddress}
onChange={(e: SelectChangeEvent) =>
setFormData((prev) => ({ ...prev, tokenAddress: e.target.value }))
}
/>
</Box>
<Box flex={1}>
<TextField
fullWidth
Expand All @@ -99,7 +115,7 @@ export const AccountSend: React.FC = () => {
fullWidth
name="amount"
value={formData.amount}
label={'Amount (ETH)'}
label={'Amount'}
onChange={(e) => {
setFormData({ ...formData, amount: parseInt(e.target.value, 10) });
}}
Expand Down
84 changes: 84 additions & 0 deletions src/components/account/tokenDropdown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import React from 'react';
import { validateAndParseAddress } from 'starknet-6';
import {
Box,
FormControl,
InputLabel,
MenuItem,
Select,
SelectChangeEvent,
Typography,
} from '@mui/material';

import { useSharedState } from '../context/context';
import { useAccountContracts } from '../hooks/useAccountContracts';
import { getTokenBalance } from '../../background/contracts';
import { ETH_ADDRESS } from '../../background/constants';
import { getBalanceStr } from '../utils/utils';

interface ITokenDropdownProps {
value: string;
onChange: (e: SelectChangeEvent) => void;
}

export interface Token {
address: string;
balance: string;
symbol: string;
}

export const TokenDropdown: React.FC<ITokenDropdownProps> = ({ value, onChange }) => {
const { data: accountContracts } = useAccountContracts();
const { selectedAccount, currentBalance } = useSharedState();

const [tokenBalances, setTokenBalances] = React.useState<Array<Token>>([
{
address: ETH_ADDRESS,
symbol: 'ETH',
balance: getBalanceStr(currentBalance),
},
]);

const contracts = React.useMemo(
() => accountContracts.get(selectedAccount?.address ?? '') ?? [],
[accountContracts, selectedAccount]
);

React.useEffect(() => {
if (!contracts?.length) return;

const balancePromises = contracts.map(async (address) => {
const cleanAddress = validateAndParseAddress(address);
const resp = await getTokenBalance(cleanAddress);
if (!resp) return [];

const balance = resp.balance / BigInt(10n ** 18n);
const balanceStr = balance.toString();
return {
address,
symbol: resp.symbol,
balance: balanceStr,
};
});
Promise.all(balancePromises).then((results) => {
const validTokens = results.filter((token): token is Token => token !== null);
setTokenBalances((prev) => [...prev, ...validTokens]);
});
}, [contracts]);

return (
<FormControl fullWidth>
<InputLabel id="token-dropdown">Token</InputLabel>
<Select labelId="token-dropdown" value={value} label="Token" onChange={onChange}>
{tokenBalances.map((token) => (
<MenuItem key={token.address} value={token.address} disabled={token.balance === '0'}>
<Box display="flex" alignItems="center" gap={1}>
<Typography variant="subtitle1">{token.symbol}</Typography>-
<Typography variant="subtitle2">{token.balance}</Typography>
</Box>
</MenuItem>
))}
</Select>
</FormControl>
);
};