laconic-wallet/utils/SignMessage.ts
2024-02-21 10:41:05 +05:30

83 lines
2.1 KiB
TypeScript

/* Importing this library provides react native with a secure random source.
For more information, "visit https://docs.ethers.org/v5/cookbook/react-native/#cookbook-reactnative-security" */
import 'react-native-get-random-values';
import '@ethersproject/shims';
import { Wallet } from 'ethers';
import { SignMessageParams } from '../types';
import { getCosmosAccounts, getMnemonic, getPathKey } from './utils';
const signMessage = async ({
message,
network,
accountId,
}: SignMessageParams): Promise<string | undefined> => {
const hdPath = (await getPathKey(network, accountId)).hdPath;
switch (network) {
case 'eth':
return await signEthMessage(message, accountId);
case 'cosmos':
return await signCosmosMessage(message, hdPath);
default:
throw new Error('Invalid wallet type');
}
};
const signEthMessage = async (
message: string,
accountId: number,
): Promise<string | undefined> => {
try {
const privKey = (await getPathKey('eth', accountId)).privKey;
const wallet = new Wallet(privKey);
const signature = await wallet.signMessage(message);
return signature;
} catch (error) {
console.error('Error signing Ethereum message:', error);
return undefined;
}
};
const signCosmosMessage = async (
message: string,
hdPath: string,
): Promise<string | undefined> => {
try {
const mnemonic = await getMnemonic();
const cosmosAccount = await getCosmosAccounts(mnemonic, hdPath);
const address = cosmosAccount.data.address;
const cosmosSignature = await cosmosAccount.cosmosWallet.signAmino(
address,
{
chain_id: '',
account_number: '0',
sequence: '0',
fee: {
gas: '0',
amount: [],
},
msgs: [
{
type: 'sign/MsgSignData',
value: {
signer: address,
data: btoa(message),
},
},
],
memo: '',
},
);
return cosmosSignature.signature.signature;
} catch (error) {
console.error('Error signing Cosmos message:', error);
return undefined;
}
};
export { signMessage, signEthMessage, signCosmosMessage };