type Address = string;
type Quantity = string;
type Hex = string;
type MethodDefinitions = [
{
Method: 'eth_accounts';
Parameters?: undefined;
ReturnType: Address[];
},
{
Method: 'eth_chainId';
Parameters?: undefined;
ReturnType: Quantity;
},
{
Method: 'eth_switchAccount';
Parameters: [address: Hex];
ReturnType: null;
},
{
Method: 'eth_requestAccounts';
Parameters?: undefined;
ReturnType: Address[];
}
];
type MethodNames = MethodDefinitions[number]['Method'];
type MethodParams<T extends MethodNames> = Extract<MethodDefinitions[number], { Method: T }>['Parameters'];
type MethodReturnType<T extends MethodNames> = Extract<MethodDefinitions[number], { Method: T }>['ReturnType'];
type RequestParams<T extends MethodNames> = MethodParams<T> extends undefined
? { method: T; params?: MethodParams<T> }
: { method: T; params: MethodParams<T> };
async function request<T extends MethodNames>(args: RequestParams<T>): Promise<MethodReturnType<T>> {
const { method } = args;
switch (method) {
case 'eth_accounts':
return ['0x1234567890abcdef1234567890abcdef12345678'] as MethodReturnType<T>;
case 'eth_chainId':
return '0x1' as MethodReturnType<T>;
case 'eth_switchAccount':
return null as MethodReturnType<T>;
case 'eth_requestAccounts':
return ['0x1234567890abcdef1234567890abcdef12345678'] as MethodReturnType<T>;
default:
throw new Error(`Unknown method: ${method}`);
}
}
async function exampleUsage() {
const chainId = await request({ method: 'eth_chainId' });
}
exampleUsage();