laconic-wallet/utils/sign-message.ts
nabarun c6128f222c Load config values from env (#1)
Part of https://www.notion.so/WalletConnect-integration-84b2f7377d514d7ead698bebd84f1e31

- Use `react-native-config` library

Co-authored-by: Shreerang Kale <shreerangkale@gmail.com>
Reviewed-on: cerc-io/laconic-wallet#1
2024-03-08 06:54:16 +00:00

84 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 path = (await getPathKey(network, accountId)).path;
switch (network) {
case 'eth':
return await signEthMessage(message, accountId);
case 'cosmos':
return await signCosmosMessage(message, path);
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,
path: string,
): Promise<string | undefined> => {
try {
const mnemonic = await getMnemonic();
const cosmosAccount = await getCosmosAccounts(mnemonic, path);
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 };