Compare commits
2
Commits
urbit
...
feat/snaps
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf25f1ecdf | ||
|
|
994969534a |
@@ -3,13 +3,16 @@ import {
|
||||
JsonRpcConnector,
|
||||
ViewConnector,
|
||||
InjectedConnector,
|
||||
SnapConnector,
|
||||
} from '@vegaprotocol/wallet';
|
||||
|
||||
export const rest = new RestConnector();
|
||||
export const jsonRpc = new JsonRpcConnector();
|
||||
export const injected = new InjectedConnector();
|
||||
export const snap = new SnapConnector();
|
||||
|
||||
let view: ViewConnector;
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
const urlParams = new URLSearchParams(window.location.hash.split('?')[1]);
|
||||
view = new ViewConnector(urlParams.get('address'));
|
||||
@@ -22,4 +25,5 @@ export const Connectors = {
|
||||
rest,
|
||||
jsonRpc,
|
||||
view,
|
||||
snap,
|
||||
};
|
||||
|
||||
@@ -7,11 +7,17 @@ import {
|
||||
VegaIcon,
|
||||
VegaIconNames,
|
||||
} from '@vegaprotocol/ui-toolkit';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { WalletClientError } from '@vegaprotocol/wallet-client';
|
||||
import { t } from '@vegaprotocol/i18n';
|
||||
import type { VegaConnector } from '../connectors';
|
||||
import { InjectedConnector } from '../connectors';
|
||||
import {
|
||||
InjectedConnector,
|
||||
SnapConnector,
|
||||
connectSnap,
|
||||
defaultSnapOrigin,
|
||||
getSnap,
|
||||
} from '../connectors';
|
||||
import { ViewConnector } from '../connectors';
|
||||
import { JsonRpcConnector, RestConnector } from '../connectors';
|
||||
import { RestConnectorForm } from './rest-connector-form';
|
||||
@@ -33,7 +39,7 @@ import { InjectedConnectorForm } from './injected-connector-form';
|
||||
|
||||
export const CLOSE_DELAY = 1700;
|
||||
type Connectors = { [key: string]: VegaConnector };
|
||||
export type WalletType = 'injected' | 'jsonRpc' | 'rest' | 'view';
|
||||
export type WalletType = 'injected' | 'jsonRpc' | 'rest' | 'view' | 'snap';
|
||||
|
||||
export interface VegaConnectDialogProps {
|
||||
connectors: Connectors;
|
||||
@@ -152,7 +158,10 @@ const ConnectDialogContainer = ({
|
||||
// for rest because we need to show an authentication form
|
||||
if (connector instanceof JsonRpcConnector) {
|
||||
jsonRpcConnect(connector, appChainId);
|
||||
} else if (connector instanceof InjectedConnector) {
|
||||
} else if (
|
||||
connector instanceof InjectedConnector ||
|
||||
connector instanceof SnapConnector
|
||||
) {
|
||||
injectedConnect(connector, appChainId);
|
||||
}
|
||||
};
|
||||
@@ -195,6 +204,20 @@ const ConnectorList = ({
|
||||
setWalletUrl: (value: string) => void;
|
||||
isMainnet: boolean;
|
||||
}) => {
|
||||
const [snapInstalled, setSnapInstalled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const getSnapStatus = async () => {
|
||||
const result = await getSnap(defaultSnapOrigin);
|
||||
if (result.enabled) {
|
||||
setSnapInstalled(true);
|
||||
} else {
|
||||
alert('Vega snap not installed');
|
||||
}
|
||||
};
|
||||
|
||||
getSnapStatus();
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<ConnectDialogTitle>{t('Connect')}</ConnectDialogTitle>
|
||||
@@ -216,6 +239,32 @@ const ConnectorList = ({
|
||||
/>
|
||||
</li>
|
||||
)}
|
||||
|
||||
<li className="mb-4 last:mb-0">
|
||||
{snapInstalled ? (
|
||||
<ConnectionOption
|
||||
type="snap"
|
||||
text={t('MetaMask Snap')}
|
||||
onClick={() => onSelect('snap')}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
fill={true}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await connectSnap(defaultSnapOrigin);
|
||||
const installedSnap = await getSnap(defaultSnapOrigin);
|
||||
console.log(installedSnap);
|
||||
setSnapInstalled(true);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('Install Vega MetaMask Snap')}
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
{!isMainnet && (
|
||||
<li className="mb-4 last:mb-0">
|
||||
<ConnectionOption
|
||||
@@ -261,7 +310,10 @@ const SelectedForm = ({
|
||||
onConnect: () => void;
|
||||
riskMessage?: React.ReactNode;
|
||||
}) => {
|
||||
if (connector instanceof InjectedConnector) {
|
||||
if (
|
||||
connector instanceof InjectedConnector ||
|
||||
connector instanceof SnapConnector
|
||||
) {
|
||||
return (
|
||||
<InjectedConnectorForm
|
||||
status={injectedState.status}
|
||||
|
||||
@@ -20,7 +20,6 @@ export const InjectedConnectorForm = ({
|
||||
reset,
|
||||
error,
|
||||
}: {
|
||||
// connector: JsonRpcConnector;
|
||||
appChainId: string;
|
||||
status: Status;
|
||||
error: Error | null;
|
||||
|
||||
@@ -3,3 +3,4 @@ export * from './rest-connector';
|
||||
export * from './injected-connector';
|
||||
export * from './json-rpc-connector';
|
||||
export * from './view-connector';
|
||||
export * from './snap-connector';
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { Transaction, VegaConnector } from './vega-connector';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
ethereum: any;
|
||||
}
|
||||
}
|
||||
|
||||
export const defaultSnapOrigin = 'local:http://localhost:8080';
|
||||
|
||||
// Requests permission for a website to communicate with the specified snaps
|
||||
// and attempts to install them if they're not already installed.
|
||||
// If the installation of any snap fails, returns the error that caused the failure.
|
||||
// More informations here: https://docs.metamask.io/snaps/reference/rpc-api/#wallet_requestsnaps
|
||||
//
|
||||
// The snapId when release will be using the following
|
||||
// pattern: `npm:@vegaprotocol/snapname` (prod snap ID)
|
||||
// to use the localy running extension use: `local:http://localhost:8080` (local snap ID)
|
||||
// params can contain an optional version
|
||||
export const connectSnap = async (
|
||||
snapId: string,
|
||||
params: Record<'version' | string, unknown> = {}
|
||||
) => {
|
||||
await window.ethereum.request({
|
||||
method: 'wallet_requestSnaps',
|
||||
params: {
|
||||
[snapId]: params,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export type GetSnapsResponse = Record<string, Snap>;
|
||||
|
||||
export type Snap = {
|
||||
permissionName: string;
|
||||
id: string;
|
||||
version: string;
|
||||
initialPermissions: Record<string, unknown>;
|
||||
};
|
||||
|
||||
// the returns the list of installed snaps
|
||||
// for more infos: https://docs.metamask.io/snaps/reference/rpc-api/#wallet_getsnaps
|
||||
export const getSnaps = async (): Promise<GetSnapsResponse> => {
|
||||
return (await window.ethereum.request({
|
||||
method: 'wallet_getSnaps',
|
||||
})) as unknown as GetSnapsResponse;
|
||||
};
|
||||
|
||||
// returns the snap informations if connected with this
|
||||
// webapp.
|
||||
export const getSnap = async (
|
||||
snapId: string,
|
||||
version?: string
|
||||
): Promise<Snap | undefined> => {
|
||||
try {
|
||||
const snaps = await getSnaps();
|
||||
return Object.values(snaps).find(
|
||||
(snap) => snap.id === snapId && (!version || snap.version === version)
|
||||
);
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export class SnapConnector implements VegaConnector {
|
||||
description = "Connects using Vega Protocol's MetaMask snap";
|
||||
snapId: string = defaultSnapOrigin;
|
||||
nodeAddress: string | undefined = undefined;
|
||||
|
||||
/**
|
||||
* @param nodeAddress url for the node (without pathname, eg /graphql)
|
||||
*/
|
||||
constructor(nodeAddress?: string) {
|
||||
this.nodeAddress = nodeAddress;
|
||||
}
|
||||
|
||||
async connectWallet() {
|
||||
return null;
|
||||
}
|
||||
|
||||
async connect() {
|
||||
const res = await window.ethereum.request({
|
||||
method: 'wallet_invokeSnap',
|
||||
params: {
|
||||
snapId: defaultSnapOrigin,
|
||||
request: { method: 'client.list_keys' },
|
||||
},
|
||||
});
|
||||
|
||||
// TODO: setConfig
|
||||
|
||||
console.log(res);
|
||||
|
||||
return res.keys;
|
||||
}
|
||||
|
||||
async sendTx(pubKey: string, transaction: Transaction) {
|
||||
if (!this.nodeAddress) throw new Error('nodeAddress not set');
|
||||
const payload = JSON.parse(
|
||||
JSON.stringify({
|
||||
method: 'wallet_invokeSnap',
|
||||
params: {
|
||||
snapId: defaultSnapOrigin,
|
||||
request: {
|
||||
method: 'client.send_transaction',
|
||||
params: {
|
||||
publicKey: pubKey,
|
||||
transaction,
|
||||
sendingMode: 'TYPE_SYNC',
|
||||
networkEndpoints: [this.nodeAddress],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
console.log(payload);
|
||||
const result = await window.ethereum.request(payload);
|
||||
|
||||
console.log(result);
|
||||
|
||||
return {
|
||||
transactionHash: result.transactionHash,
|
||||
receivedAt: result.receivedAt,
|
||||
sentAt: result.sentAt,
|
||||
signature: result.transaction.signature.value,
|
||||
};
|
||||
}
|
||||
|
||||
async getChainId(): Promise<{ chainID: string }> {
|
||||
if (!this.nodeAddress) throw new Error('nodeAddress not set');
|
||||
return await window.ethereum.request({
|
||||
method: 'wallet_invokeSnap',
|
||||
params: {
|
||||
snapId: defaultSnapOrigin,
|
||||
request: {
|
||||
method: 'client.get_chain_id',
|
||||
networkEndpoint: [this.nodeAddress],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// NO-OP
|
||||
async disconnect() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// async signTransaction(params) {
|
||||
// throw new Error('signTransaction not supported');
|
||||
// }
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import type { InjectedConnector } from './connectors';
|
||||
import { InjectedConnector, SnapConnector } from './connectors';
|
||||
import { useVegaWallet } from './use-vega-wallet';
|
||||
import { useEnvironment } from '@vegaprotocol/environment';
|
||||
|
||||
export enum Status {
|
||||
Idle = 'Idle',
|
||||
@@ -12,24 +13,39 @@ export enum Status {
|
||||
}
|
||||
|
||||
export const useInjectedConnector = (onConnect: () => void) => {
|
||||
const { VEGA_URL } = useEnvironment();
|
||||
const { connect, acknowledgeNeeded } = useVegaWallet();
|
||||
const [status, setStatus] = useState(Status.Idle);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const attemptConnect = useCallback(
|
||||
async (connector: InjectedConnector, appChainId: string) => {
|
||||
async (
|
||||
connector: InjectedConnector | SnapConnector,
|
||||
appChainId: string
|
||||
) => {
|
||||
try {
|
||||
if (!('vega' in window)) {
|
||||
if (connector instanceof InjectedConnector && !('vega' in window)) {
|
||||
throw new Error('window.vega not found');
|
||||
}
|
||||
|
||||
if (connector instanceof SnapConnector) {
|
||||
if (!('ethereum' in window)) {
|
||||
throw new Error('window.ethereum not found');
|
||||
}
|
||||
if (!VEGA_URL) {
|
||||
throw new Error('no connected node');
|
||||
}
|
||||
|
||||
connector.nodeAddress = new URL(VEGA_URL).origin;
|
||||
}
|
||||
|
||||
setStatus(Status.GettingChainId);
|
||||
|
||||
const { chainID } = await connector.getChainId();
|
||||
// const { chainID } = await connector.getChainId();
|
||||
|
||||
if (chainID !== appChainId) {
|
||||
throw new Error('Invalid chain');
|
||||
}
|
||||
// if (chainID !== appChainId) {
|
||||
// throw new Error('Invalid chain');
|
||||
// }
|
||||
|
||||
setStatus(Status.Connecting);
|
||||
await connector.connectWallet(); // authorize wallet
|
||||
@@ -42,6 +58,7 @@ export const useInjectedConnector = (onConnect: () => void) => {
|
||||
onConnect();
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
if (err instanceof Error) {
|
||||
setError(err);
|
||||
} else {
|
||||
@@ -50,7 +67,7 @@ export const useInjectedConnector = (onConnect: () => void) => {
|
||||
setStatus(Status.Error);
|
||||
}
|
||||
},
|
||||
[acknowledgeNeeded, connect, onConnect]
|
||||
[acknowledgeNeeded, connect, onConnect, VEGA_URL]
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user