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

Add metamask support #257

Merged
merged 8 commits into from
Dec 19, 2024
Merged
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
3 changes: 3 additions & 0 deletions jest.e2e.config.esm.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,7 @@ module.exports = {
testEnvironmentOptions: {
url: 'https://station.massa',
},
globals: {
window: {},
},
};
519 changes: 492 additions & 27 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"upgrade": "npm run up && npm run check && npm run build",
"clean": "rimraf dist/*",
"build": "npm-run-all clean build:esm",
"build:watch": "tsc --project tsconfig.esm.json --watch",
"build:esm": "tsc --project tsconfig.esm.json",
"test": "jest",
"test:serve-dapp": "cd test-extension/dapp-vite && npm run preview",
Expand Down Expand Up @@ -54,13 +55,15 @@
"dependencies": {
"@hicaru/bearby.js": "^0.5.9",
"@massalabs/massa-web3": "^5.0.1-dev",
"@metamask/providers": "^18.1.1",
"axios": "^0.28.0",
"bs58check": "^4.0.0",
"buffer": "^6.0.3",
"eventemitter3": "^5.0.1",
"lodash.isequal": "^4.5.0"
},
"devDependencies": {
"@massalabs/metamask-snap": "^1.1.0",
"@babel/preset-env": "^7.22.14",
"@massalabs/eslint-config": "^0.0.9",
"@playwright/test": "^1.36.2",
Expand Down
25 changes: 14 additions & 11 deletions src/bearbyWallet/BearbyWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ export class BearbyWallet implements Wallet {
return this.walletName;
}

static async checkInstalled(): Promise<boolean> {
return web3.wallet.installed;
static async createIfInstalled(): Promise<Wallet | null> {
if (web3.wallet.installed) {
return new BearbyWallet();
}
return null;
}

public async accounts(): Promise<BearbyAccount[]> {
Expand All @@ -24,17 +27,11 @@ export class BearbyWallet implements Wallet {
return [new BearbyAccount(await web3.wallet.account.base58)];
}

public async importAccount(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
publicKey: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
privateKey: string,
): Promise<void> {
public async importAccount(): Promise<void> {
throw new Error('Method not implemented.');
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async deleteAccount(address: string): Promise<void> {
public async deleteAccount(): Promise<void> {
throw new Error('Method not implemented.');
}

Expand All @@ -45,6 +42,12 @@ export class BearbyWallet implements Wallet {
return networkInfos();
}

public async setRpcUrl(): Promise<void> {
throw new Error(
'setRpcUrl is not yet implemented for the current provider.',
);
}

public async generateNewAccount(): Promise<Provider> {
throw new Error('Method not implemented.');
}
Expand Down Expand Up @@ -133,7 +136,7 @@ export class BearbyWallet implements Wallet {
*
* @returns a boolean indicating whether the wallet is connected.
*/
public connected(): boolean {
public async connected(): Promise<boolean> {
return web3.wallet.connected;
}

Expand Down
16 changes: 13 additions & 3 deletions src/massaStation/MassaStationWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,11 @@ export class MassaStationWallet implements Wallet {
return this.walletName;
}

static async checkInstalled(): Promise<boolean> {
return isMassaWalletEnabled();
static async createIfInstalled(): Promise<Wallet | null> {
if (await isMassaWalletEnabled()) {
return new MassaStationWallet();
}
return null;
}

public async accounts(): Promise<MassaStationAccount[]> {
Expand Down Expand Up @@ -104,6 +107,13 @@ export class MassaStationWallet implements Wallet {
return networkInfos();
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async setRpcUrl(url: string): Promise<void> {
throw new Error(
'setRpcUrl is not yet implemented for the current provider.',
);
}

/**
* This method sends an http call to the MassaStation server to create a new random account.
*
Expand Down Expand Up @@ -181,7 +191,7 @@ export class MassaStationWallet implements Wallet {
* Indicates if the station is connected.
* Always returns `true` because the station is always connected when running.
*/
public connected(): boolean {
public async connected(): Promise<boolean> {
return true;
}

Expand Down
274 changes: 274 additions & 0 deletions src/metamaskSnap/MetamaskAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
import { MetaMaskInpageProvider } from '@metamask/providers';
import {
Address,
CallSCParams,
DatastoreEntry,
DeploySCParams,
EventFilter,
formatNodeStatusObject,
MAX_GAS_CALL,
Network,
NodeStatusInfo,
Operation,
OperationOptions,
OperationStatus,
Provider,
ReadSCData,
ReadSCParams,
SignedData,
SmartContract,
strToBytes,
rpcTypes,
} from '@massalabs/massa-web3';
import { WalletName } from '../wallet';
import { errorHandler } from '../errors/utils/errorHandler';
import { operationType } from '../utils/constants';
import { getClient, networkInfos } from '../massaStation/utils/network';
import {
buyRolls,
callSC,
deploySC,
getBalance,
sellRolls,
signMessage,
transfer,
} from './services';
import type {
BuyRollsParams,
SellRollsParams,
TransferParams,
CallSCParams as MMCallSCParams,
DeploySCParams as MMDeploySCParams,
} from '@massalabs/metamask-snap';

export class MetamaskAccount implements Provider {
constructor(
public readonly address: string,
private readonly provider: MetaMaskInpageProvider,
) {}

get accountName(): string {
return this.address;
}

get providerName(): string {
return WalletName.Metamask;
}

async balance(final = false): Promise<bigint> {
const { finalBalance, candidateBalance } = await getBalance(this.provider, {
address: this.address,
});
return BigInt(final ? finalBalance : candidateBalance);
}

async networkInfos(): Promise<Network> {
return networkInfos();
}

async sign(inData: Uint8Array | string): Promise<SignedData> {
try {
const data = typeof inData === 'string' ? inData : Array.from(inData);
const { publicKey, signature } = await signMessage(this.provider, {
data,
});

return {
publicKey,
signature,
};
} catch (error) {
throw errorHandler(operationType.Sign, error);
}
}

private async handleRollOperation(
operation: 'buy' | 'sell',
amount: bigint,
opts?: OperationOptions,
): Promise<Operation> {
try {
const params: BuyRollsParams | SellRollsParams = {
amount: amount.toString(),
};
if (opts?.fee) {
params.fee = opts?.fee.toString();
}

const { operationId } = await (operation === 'buy'
? buyRolls(this.provider, params)
: sellRolls(this.provider, params));

return new Operation(this, operationId);
} catch (error) {
throw errorHandler(
operation === 'buy' ? operationType.BuyRolls : operationType.SellRolls,
error,
);
}
}

async buyRolls(amount: bigint, opts?: OperationOptions): Promise<Operation> {
return this.handleRollOperation('buy', amount, opts);
}

async sellRolls(amount: bigint, opts?: OperationOptions): Promise<Operation> {
return this.handleRollOperation('sell', amount, opts);
}

async transfer(
to: Address | string,
amount: bigint,
opts?: OperationOptions,
): Promise<Operation> {
try {
const params: TransferParams = {
amount: amount.toString(),
recipientAddress: to.toString(),
};
if (opts?.fee) {
params.fee = opts?.fee.toString();
}
const { operationId } = await transfer(this.provider, params);

return new Operation(this, operationId);
} catch (error) {
throw errorHandler(operationType.SendTransaction, error);
}
}

async callSC(params: CallSCParams): Promise<Operation> {
try {
const callSCparams: MMCallSCParams = {
functionName: params.func,
at: params.target,
};
if (params.parameter) {
callSCparams.args =
params.parameter instanceof Uint8Array
? Array.from(params.parameter)
: Array.from(params.parameter.serialize());
}
if (params.coins) {
callSCparams.coins = params.coins.toString();
}
if (params.maxGas) {
callSCparams.maxGas = params.maxGas.toString();
}
if (params.fee) {
callSCparams.fee = params.fee.toString();
}

const { operationId } = await callSC(this.provider, callSCparams);

return new Operation(this, operationId);
} catch (error) {
throw errorHandler(operationType.CallSC, error);
}
}

async readSC(params: ReadSCParams): Promise<ReadSCData> {
if (params?.maxGas > MAX_GAS_CALL) {
throw new Error(
`Gas amount ${params.maxGas} exceeds the maximum allowed ${MAX_GAS_CALL}`,
);
}
try {
const args = params.parameter ?? new Uint8Array();
const parameter =
args instanceof Uint8Array ? args : Uint8Array.from(args.serialize());

const client = await getClient();
const readOnlyParams = {
...params,
caller: params.caller ?? this.address,
parameter,
};
return client.executeReadOnlyCall(readOnlyParams);
} catch (error) {
throw new Error(`Smart contract read failed: ${error.message}`);
}
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
async deploySC(params: DeploySCParams): Promise<SmartContract> {
try {
const deployParams: MMDeploySCParams = {
bytecode: Array.from(params.byteCode),
};
if (params.parameter) {
deployParams.args = Array.from(
params.parameter instanceof Uint8Array
? params.parameter
: params.parameter.serialize(),
);
}
if (params.coins) {
deployParams.coins = params.coins.toString();
}
if (params.maxGas) {
deployParams.maxGas = params.maxGas.toString();
}
if (params.fee) {
deployParams.fee = params.fee.toString();
}
if (params.maxCoins) {
deployParams.fee = params.maxCoins.toString();
}

const { operationId } = await deploySC(this.provider, deployParams);
const op = new Operation(this, operationId);
const deployedAddress = await op.getDeployedAddress(
params.waitFinalExecution,
);

return new SmartContract(this, deployedAddress);
} catch (error) {
throw errorHandler(operationType.DeploySC, error);
}
}

async getOperationStatus(opId: string): Promise<OperationStatus> {
const client = await getClient();
return client.getOperationStatus(opId);
}

async getEvents(filter: EventFilter): Promise<rpcTypes.OutputEvents> {
const client = await getClient();
return client.getEvents(filter);
}

async getNodeStatus(): Promise<NodeStatusInfo> {
const client = await getClient();
const status = await client.status();
return formatNodeStatusObject(status);
}

async getStorageKeys(
address: string,
filter: Uint8Array | string = new Uint8Array(),
final = true,
): Promise<Uint8Array[]> {
const client = await getClient();
const filterBytes =
typeof filter === 'string' ? strToBytes(filter) : filter;
return client.getDataStoreKeys(address, filterBytes, final);
}

async readStorage(
address: string,
keys: Uint8Array[] | string[],
final = true,
): Promise<Uint8Array[]> {
const client = await getClient();
const entries: DatastoreEntry[] = keys.map((key) => ({
key,
address,
}));
return client.getDatastoreEntries(entries, final);
}

executeSC(): Promise<Operation> {
throw new Error('Method not implemented.');
}
}
Loading
Loading