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

Improve wallet provider #200

Merged
merged 5 commits into from
Feb 2, 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
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ docs
dist
test-extension/simple-browser-extension
test-extension/dapp-vite
unit-tests/code-snippets
test-extension
9 changes: 8 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
module.exports = {
extends: ['@massalabs'],
extends: ['@massalabs', 'prettier'],
rules: {
'tsdoc/syntax': 'warn',
'max-len': ['error', 200],
camelcase: 'off',
'@typescript-eslint/no-unused-vars': 'error',
'no-console': 'warn',
},
};
7 changes: 7 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}
316 changes: 30 additions & 286 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@
],
"dependencies": {
"@hicaru/bearby.js": "^0.5.5",
"@massalabs/massa-web3": "^3.0.2",
"@massalabs/web3-utils": "^1.4.7",
"@massalabs/web3-utils": "^1.4.8",
"axios": "^0.26.1",
"bignumber.js": "^9.1.1",
"bs58check": "^3.0.1",
Expand All @@ -67,7 +66,6 @@
"devDependencies": {
"@babel/preset-env": "^7.22.14",
"@massalabs/eslint-config": "^0.0.9",
"@massalabs/prettier-config-as": "^0.0.2",
"@playwright/test": "^1.32.3",
"@types/bn.js": "^5.1.1",
"@types/chai": "^4.3.4",
Expand All @@ -78,6 +76,7 @@
"babel-jest": "^29.6.4",
"chai": "^4.3.7",
"chalk": "^4.1.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jsdoc": "^41.1.1",
"express": "^4.18.2",
"fs-extra": "^11.1.1",
Expand All @@ -101,7 +100,6 @@
"bufferutil": "^4.0.7",
"utf-8-validate": "^6.0.2"
},
"prettier": "@massalabs/prettier-config-as",
"_moduleAliases": {
"@massalabs/wallet-provider": "./dist/index.js"
}
Expand Down
163 changes: 23 additions & 140 deletions src/bearbyWallet/BearbyAccount.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,20 @@
import {
Args,
CHAIN_ID_RPC_URL_MAP,
IContractReadOperationData,
IContractReadOperationResponse,
MAX_GAS_CALL,
} from '@massalabs/web3-utils';
import { ITransactionDetails } from '..';
import { IAccountBalanceResponse, IAccountDetails } from '../account';
import { IAccount } from '../account/IAccount';
import { web3 } from '@hicaru/bearby.js';
import {
postRequest,
JsonRpcResponseData,
} from '../massaStation/RequestHandler';
import { postRequest } from '../massaStation/RequestHandler';
import { BalanceResponse } from './BalanceResponse';
import { NodeStatus } from './NodeStatus';
import { JSON_RPC_REQUEST_METHOD } from './jsonRpcMethods';
import axios, { AxiosRequestHeaders, AxiosResponse } from 'axios';
import { IAccountSignOutput } from '../account/AccountSign';
/**
* The maximum allowed gas for a read operation
*/
const MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);

/**
* The RPC we are using to query the node
*/
export const PUBLIC_NODE_RPC = 'https://buildnet.massa.net/api/v2';

export enum OperationsType {
Payment,
Expand All @@ -45,17 +35,10 @@
CallSC = 4,
}

const requestHeaders = {
Accept:
'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Content-Type': 'application/json',
} as AxiosRequestHeaders;

export class BearbyAccount implements IAccount {
private _providerName: string;
private _address: string;
private _name: string;
private _nodeUrl = PUBLIC_NODE_RPC;

public constructor({ address, name }: IAccountDetails, providerName: string) {
this._address = address;
Expand All @@ -75,17 +58,16 @@
return this._providerName;
}

// TODO: Should be removed from account interface as it more a provider method
public async connect() {
try {
await web3.wallet.connect();
} catch (ex) {
console.log('Bearby connection error: ', ex);

Check warning on line 65 in src/bearbyWallet/BearbyAccount.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
}
}

// needs testing
public async balance(): Promise<IAccountBalanceResponse> {
// TODO: check if we need to connect every time
await this.connect();
// Not available on bearby. we have to manually call the api
const body = {
Expand All @@ -95,14 +77,15 @@
id: 0,
};

const addressInfos = await postRequest<BalanceResponse>(
PUBLIC_NODE_RPC,
body,
);
// get node url: This is a temporary solution. We should get the balance from the provider
const nodeUrl = await getNodesUrl();

const addressInfos = await postRequest<BalanceResponse>(nodeUrl, body);

if (addressInfos.isError || addressInfos.error) {
throw addressInfos.error.message;
}

return {
finalBalance: addressInfos.result.result[0].final_balance,
candidateBalance: addressInfos.result.result[0].candidate_balance,
Expand All @@ -129,11 +112,7 @@
};
}

// need testing
public async buyRolls(
amount: bigint,
fee: bigint,
): Promise<ITransactionDetails> {
public async buyRolls(amount: bigint): Promise<ITransactionDetails> {
await this.connect();
const operationId = await web3.massa.buyRolls(amount.toString());

Expand All @@ -142,11 +121,7 @@
} as ITransactionDetails;
}

// need testing
public async sellRolls(
amount: bigint,
fee: bigint,
): Promise<ITransactionDetails> {
public async sellRolls(amount: bigint): Promise<ITransactionDetails> {
await this.connect();
const operationId = await web3.massa.sellRolls(amount.toString());

Expand All @@ -158,7 +133,6 @@
public async sendTransaction(
amount: bigint,
recipientAddress: string,
fee: bigint,
): Promise<ITransactionDetails> {
await this.connect();

Expand All @@ -167,9 +141,7 @@
recipientAddress,
);

return {
operationId,
} as ITransactionDetails;
return { operationId };
}

public async callSC(
Expand All @@ -182,6 +154,7 @@
nonPersistentExecution = false,
): Promise<ITransactionDetails | IContractReadOperationResponse> {
await this.connect();

if (nonPersistentExecution) {
return this.nonPersistentCallSC(
contractAddress,
Expand Down Expand Up @@ -212,101 +185,6 @@
return { operationId };
}

/**
* Retrieves the node's status.
*
* @remarks
* The returned information includes:
* - Whether the node is reachable
* - The number of connected peers
* - The node's version
* - The node's configuration parameters
*
* @returns A promise that resolves to the node's status information.
*/
public async getNodeStatus(): Promise<NodeStatus> {
const jsonRpcRequestMethod = JSON_RPC_REQUEST_METHOD.GET_STATUS;
return await this.sendJsonRPCRequest<NodeStatus>(jsonRpcRequestMethod, []);
}

/**
* Sends a post JSON rpc request to the node.
*
* @param resource - The rpc method to call.
* @param params - The parameters to pass to the rpc method.
*
* @throws An error if the rpc method returns an error.
*
* @returns A promise that resolves as the result of the rpc method.
*/
protected async sendJsonRPCRequest<T>(
resource: JSON_RPC_REQUEST_METHOD,
params: object,
): Promise<T> {
let resp: JsonRpcResponseData<T> = null;
resp = await this.promisifyJsonRpcCall(resource, params);

// in case of rpc error, rethrow the error.
if (resp.isError || resp.error) {
throw resp.error;
}

return resp.result;
}

/**
* Converts a json rpc call to a promise that resolves as a JsonRpcResponseData
*
* @privateRemarks
* If there is an error while sending the request, the function catches the error, the isError
* property is set to true, the result property set to null, and the error property set to a
* new Error object with a message indicating that there was an error.
*
* @param resource - The rpc method to call.
* @param params - The parameters to pass to the rpc method.
*
* @returns A promise that resolves as a JsonRpcResponseData.
*/
private async promisifyJsonRpcCall<T>(
resource: JSON_RPC_REQUEST_METHOD,
params: object,
): Promise<JsonRpcResponseData<T>> {
let resp: AxiosResponse<JsonRpcResponseData<T>> = null;

const body = {
jsonrpc: '2.0',
method: resource,
params: params,
id: 0,
};

try {
resp = await axios.post(this._nodeUrl, body, { headers: requestHeaders });
} catch (ex) {
return {
isError: true,
result: null,
error: new Error('JSON.parse error: ' + String(ex)),
} as JsonRpcResponseData<T>;
}

const responseData: JsonRpcResponseData<T> = resp.data;

if (responseData.error) {
return {
isError: true,
result: null,
error: new Error(responseData.error.message),
} as JsonRpcResponseData<T>;
}

return {
isError: false,
result: responseData.result as T,
error: null,
} as JsonRpcResponseData<T>;
}

public async nonPersistentCallSC(
contractAddress: string,
functionName: string,
Expand All @@ -315,14 +193,12 @@
fee: bigint,
maxGas: bigint,
): Promise<IContractReadOperationResponse> {
// not clean but bearby doesn't allow us to get its node urls
const node = PUBLIC_NODE_RPC;
// Gas amount check
if (maxGas > MAX_READ_BLOCK_GAS) {
if (maxGas > MAX_GAS_CALL) {
throw new Error(
`
The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of
${MAX_READ_BLOCK_GAS.toString()}
${MAX_GAS_CALL.toString()}
`,
);
}
Expand Down Expand Up @@ -354,9 +230,10 @@
];
// returns operation ids
let jsonRpcCallResult: Array<IContractReadOperationData> = [];
const nodeUrl = await getNodesUrl();
try {
let resp = await postRequest<Array<IContractReadOperationData>>(
node,
nodeUrl,
body,
);
if (resp.isError || resp.error) {
Expand All @@ -382,3 +259,9 @@
};
}
}

// TODO: Should be removed from account when bearby.js is updated
async function getNodesUrl(): Promise<string> {
const info = (await web3.massa.getNodesStatus()) as any;

Check warning on line 265 in src/bearbyWallet/BearbyAccount.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
return CHAIN_ID_RPC_URL_MAP[info.result.chain_id];
}
1 change: 0 additions & 1 deletion src/bearbyWallet/BearbyConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
try {
await web3.wallet.connect();
} catch (ex) {
console.log(ex);

Check warning on line 11 in src/bearbyWallet/BearbyConnect.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
}
}

export async function disconnectBearby(): Promise<void> {
await web3.wallet.disconnect();
console.log('Bearby disconnected');
}
Loading
Loading