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

WalletConnect Solana adapter #17360

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions packages/blockchain-link-types/src/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export interface EstimateFee {
payload: {
feePerUnit: string;
feePerTx?: string;
feePayer?: string;
feeLimit?: string;
eip1559?: Eip1559Fees;
}[];
Expand Down
6 changes: 3 additions & 3 deletions packages/blockchain-link/src/workers/solana/fee.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
Address,
Base64EncodedWireTransaction,
CompilableTransactionMessage,
CompiledTransactionMessage,
GetFeeForMessageApi,
GetRecentPrioritizationFeesApi,
Expand All @@ -9,7 +10,6 @@ import {
SimulateTransactionApi,
TransactionMessageBytes,
TransactionMessageBytesBase64,
decompileTransactionMessage,
getBase64Decoder,
getCompiledTransactionMessageEncoder,
getTransactionEncoder,
Expand Down Expand Up @@ -56,12 +56,12 @@ export const getBaseFee = async (
// https://solana.com/developers/guides/advanced/how-to-use-priority-fees#how-do-i-estimate-priority-fees
export const getPriorityFee = async (
api: Rpc<GetRecentPrioritizationFeesApi & SimulateTransactionApi>,
decompiledMessage: CompilableTransactionMessage,
compiledMessage: CompiledTransactionMessage,
signatures: SignaturesMap,
) => {
const message = decompileTransactionMessage(compiledMessage);
const affectedAccounts = new Set<Address>(
message.instructions
decompiledMessage.instructions
.flatMap(instruction => instruction.accounts ?? [])
.filter(({ role }) => isWritableRole(role))
.map(({ address }) => address),
Expand Down
14 changes: 13 additions & 1 deletion packages/blockchain-link/src/workers/solana/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
createSolanaRpcFromTransport,
createSolanaRpcSubscriptions,
decompileTransactionMessage,
decompileTransactionMessageFetchingLookupTables,
getBase16Encoder,
getBase64Encoder,
getCompiledTransactionMessageDecoder,
Expand Down Expand Up @@ -482,7 +483,17 @@ const estimateFee = async (request: Request<MessageTypes.EstimateFee>) => {
const transaction = pipe(messageHex, getBase16Encoder().encode, getTransactionDecoder().decode);
const message = pipe(transaction.messageBytes, getCompiledTransactionMessageDecoder().decode);

const priorityFee = await getPriorityFee(api.rpc, message, transaction.signatures);
const decompiledTransactionMessage = await decompileTransactionMessageFetchingLookupTables(
message,
api.rpc,
);

const priorityFee = await getPriorityFee(
api.rpc,
decompiledTransactionMessage,
message,
transaction.signatures,
);
const baseFee = await getBaseFee(api.rpc, message);

const accountCreationFee = newAccountProgramName
Expand All @@ -501,6 +512,7 @@ const estimateFee = async (request: Request<MessageTypes.EstimateFee>) => {
.toString(10),
feePerUnit: priorityFee.computeUnitPrice,
feeLimit: priorityFee.computeUnitLimit,
feePayer: decompiledTransactionMessage.feePayer.address,
},
];

Expand Down
9 changes: 9 additions & 0 deletions packages/components/src/components/form/Select/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ type WrapperProps = TransientProps<
$isWithPlaceholder: boolean;
$elevation: Elevation;
$isLoading?: boolean;
$menuFitContent?: boolean;
};

const SelectWrapper = styled.div<WrapperProps>`
Expand Down Expand Up @@ -230,6 +231,11 @@ const SelectWrapper = styled.div<WrapperProps>`
${menuStyle}
border: none;
z-index: ${zIndices.base};
${({ $menuFitContent }) =>
$menuFitContent &&
css`
width: fit-content;
`}
}

${({ $isDisabled }) =>
Expand Down Expand Up @@ -276,6 +282,7 @@ export type SelectProps = KeyPressScrollProps &
label?: ReactNode;
size?: InputSize;
minValueWidth?: string;
menuFitContent?: boolean;
isMenuOpen?: boolean;
isLoading?: boolean;
onChange?: (value: Option, ref?: SelectInstance<Option, boolean> | null) => void;
Expand All @@ -289,6 +296,7 @@ export const Select = ({
useKeyPressScroll,
isSearchable = false,
minValueWidth = 'initial',
menuFitContent,
isMenuOpen,
components,
onChange,
Expand Down Expand Up @@ -348,6 +356,7 @@ export const Select = ({
$isSearchable={isSearchable}
$size={size}
$minValueWidth={minValueWidth}
$menuFitContent={menuFitContent}
$isDisabled={isDisabled}
$isLoading={isLoading}
$isMenuOpen={isMenuOpen}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,131 @@
import { useEffect, useMemo, useState } from 'react';
import { GroupBase } from 'react-select';

import { TrezorDevice } from '@suite-common/suite-types';
import { AccountType, NetworkType } from '@suite-common/wallet-config';
import { selectAccounts, selectDevices } from '@suite-common/wallet-core';
import { Account } from '@suite-common/wallet-types';
import {
selectPendingProposal,
sessionProposalApproveThunk,
sessionProposalRejectThunk,
} from '@suite-common/walletconnect';
import { Banner, Card, H2, NewModal, Note, Paragraph, Row, Text } from '@trezor/components';
import { PendingConnectionProposalNetwork } from '@suite-common/walletconnect/src/walletConnectTypes';
import {
Banner,
Card,
H2,
NewModal,
Note,
Option,
Paragraph,
Row,
Select,
Text,
} from '@trezor/components';
import { BannerButton } from '@trezor/components/src/components/Banner/BannerButton';
import { CoinLogo } from '@trezor/product-components';
import { spacings } from '@trezor/theme';

import { onCancel } from 'src/actions/suite/modalActions';
import { goto } from 'src/actions/suite/routerActions';
import { Translation } from 'src/components/suite';
import { AccountLabel, Translation, WalletLabeling } from 'src/components/suite';
import { AccountTypeBadge } from 'src/components/suite/AccountTypeBadge';
import { useDispatch, useSelector } from 'src/hooks/suite';
import { selectAccountLabels } from 'src/reducers/suite/metadataReducer';

interface WalletConnectProposalModalProps {
eventId: number;
}

interface AccountGroup extends GroupBase<Account> {
options: Account[];
label: string;
device: TrezorDevice;
accountType: AccountType;
networkType: NetworkType;
}

export const WalletConnectProposalModal = ({ eventId }: WalletConnectProposalModalProps) => {
const dispatch = useDispatch();
const pendingProposal = useSelector(selectPendingProposal);
const accounts = useSelector(selectAccounts);
const accountLabels = useSelector(selectAccountLabels);
const devices = useSelector(selectDevices);
const [selectedDefaultAccounts, setSelectedDefaultAccounts] = useState<Account[]>([]);

const handleAccept = () => {
dispatch(sessionProposalApproveThunk({ eventId }));
dispatch(sessionProposalApproveThunk({ eventId, selectedDefaultAccounts }));
dispatch(onCancel());
};
const handleReject = () => {
dispatch(sessionProposalRejectThunk({ eventId }));
dispatch(onCancel());
};
const handleSelectAccount = (account: Account) => {
setSelectedDefaultAccounts(prev => {
const newAccounts = prev.filter(prevAccount => prevAccount.symbol !== account.symbol);

return [...newAccounts, account];
});
};

const orderedAccounts = useMemo(
() =>
[...accounts]
.filter(account => account.visible)
.map(account => ({
...account,
accountLabel: accountLabels[account.key],
}))
.sort((a, b) => {
if (a.deviceState !== b.deviceState) {
return a.deviceState.localeCompare(b.deviceState);
}
if (a.accountType !== b.accountType) {
// normal first
if (a.accountType === 'normal' && b.accountType !== 'normal') return -1;
if (a.accountType !== 'normal' && b.accountType === 'normal') return 1;

return a.accountType.localeCompare(b.accountType);
}

return a.index - b.index;
}),
[accounts, accountLabels],
);
useEffect(() => {
const newDefaultAccounts = pendingProposal?.networks
.filter(network => network.status === 'active')
.map(network => orderedAccounts.find(account => account.symbol === network.symbol))
.filter(Boolean) as Account[];
setSelectedDefaultAccounts(newDefaultAccounts);
}, [orderedAccounts, pendingProposal?.networks]);

const buildAccountOptionGroups = (network: PendingConnectionProposalNetwork) => {
const groups: AccountGroup[] = [];
orderedAccounts
.filter(account => account.symbol === network.symbol)
.forEach(account => {
const device = devices.find(d => d.state?.staticSessionId === account.deviceState);
if (!device) return;
const label = `${account.deviceState}-${account.accountType}`;
const group = groups.find(g => g.label === label);
if (group) {
group.options.push(account);
} else {
groups.push({
label,
device,
accountType: account.accountType,
networkType: account.networkType,
options: [account],
});
}
});

return groups;
};

if (!pendingProposal) return null;

Expand Down Expand Up @@ -103,12 +200,59 @@ export const WalletConnectProposalModal = ({ eventId }: WalletConnectProposalMod
size={24}
/>
)}
<Text>
{network.name}
{network.required && (
<Text variant="destructive">*</Text>
)}
</Text>
{status === 'active' &&
network.namespaceId.startsWith('solana') ? (
<Select
isSearchable={false}
isClearable={false}
isClean
menuFitContent
size="small"
value={selectedDefaultAccounts.find(
account => account.symbol === network.symbol,
)}
options={buildAccountOptionGroups(network)}
formatGroupLabel={(data: GroupBase<Account>) => (
<Row gap={spacings.xs}>
<WalletLabeling
device={(data as AccountGroup).device}
shouldUseDeviceLabel
/>
<AccountTypeBadge
accountType={
(data as AccountGroup).accountType
}
networkType={
(data as AccountGroup).networkType
}
size="small"
onElevation
/>
</Row>
)}
formatOptionLabel={(account: Account) => (
<AccountLabel
key={account.descriptor}
accountLabel={account.accountLabel}
accountType={account.accountType}
networkType={account.networkType}
symbol={account.symbol}
index={account.index}
path={account.path}
/>
)}
onChange={(option: Option) =>
handleSelectAccount(option)
}
/>
) : (
<Text>
{network.name}
{network.required && (
<Text variant="destructive">*</Text>
)}
</Text>
)}
</Row>
))}
</Row>
Expand Down
3 changes: 2 additions & 1 deletion suite-common/walletconnect/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@suite-common/wallet-types": "workspace:*",
"@trezor/connect": "workspace:*",
"@walletconnect/core": "^2.18.1",
"@walletconnect/utils": "^2.18.1"
"@walletconnect/utils": "^2.18.1",
"bs58": "^6.0.0"
}
}
Loading
Loading