Skip to content

Commit

Permalink
unify the methods for wallet provider and web3
Browse files Browse the repository at this point in the history
  • Loading branch information
Elli610 committed Aug 23, 2023
1 parent 9543ddc commit 908b9c5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 104 deletions.
16 changes: 11 additions & 5 deletions packages/massa-proto-cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ program
'optional output directory for the callers to generate',
'./helpers/',
)
.option(
'-c, --check-dep <value>',
'optional check dependencies before generating callers',
false,
)
.parse(process.argv);

// Get the URL for a public JSON RPC API endpoint from the environment variables
Expand All @@ -49,6 +54,7 @@ async function run() {
let mode: string = args['gen'];
let address: string = args['addr'];
let out: string = args['out'];
let checkDep: boolean = args['checkDep'] == true ? true : false;

if (mode === '' || address === '' || publicApi === undefined) {
program.help();
Expand All @@ -57,7 +63,7 @@ async function run() {

// check if the necessary dependencies are installed
let missingDeps: string[] = [];
if (mode === 'sc') {
if (checkDep && mode === 'sc') {
/* check if the following node dependencies are installed:
- as-proto
- as-proto-gen
Expand All @@ -77,7 +83,7 @@ async function run() {
} catch (e) {
throw new Error(`Error checking for dependencies: ${e}`);
}
} else if (mode === 'web3' || mode === 'wallet') {
} else if (checkDep && mode === 'web3') {
/* check if the following node dependencies are installed:
- @massalabs/massa-web3
- @protobuf-ts/plugin
Expand All @@ -89,7 +95,7 @@ async function run() {
throw new Error(`Error checking for dependencies: ${e}`);
}
}
if (missingDeps.length > 0) {
if (checkDep && missingDeps.length > 0) {
/* eslint-disable-next-line no-console */
console.log(`Missing dependencies: ${missingDeps.join(', ')}`);

Expand Down Expand Up @@ -150,8 +156,8 @@ async function run() {
// call the generator
if (mode === 'sc') {
generateAsCallers(files, address, out);
} else if (mode === 'web3' || mode === 'wallet') {
generateTsCallers(files, out, address, mode, address.slice(-10));
} else if (mode === 'web3') {
generateTsCallers(files, out, address, address.slice(-10));
} else {
throw new Error(`Unsupported mode: ${mode}`);
}
Expand Down
126 changes: 27 additions & 99 deletions packages/massa-proto-cli/src/ts-gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,10 @@ function generateDocArgs(protoFile: ProtoFile): string {
}

/**
* Generate the TypeScript code for the ts caller function, depending of the chosen mode
* Generate the TypeScript code for the ts caller function
*/
function callSCConstructor(mode: string): string {
if (mode == 'web3') {
return `{ operationId:
function callSCConstructor(): string {
return `{ operationId:
await account.callSmartContract(
{
fee: fee,
Expand All @@ -168,21 +167,8 @@ function callSCConstructor(mode: string): string {
functionName: functionName,
parameter: Array.from(args),
} as ICallData,
)
),
}`;
}
if (mode == 'wallet') {
return `await account.callSC(
contractAddress,
functionName,
args,
coins,
fee,
maxGas,
)`;
} else {
throw Error('Unsupported mode: ' + mode);
}
}

/**
Expand Down Expand Up @@ -262,7 +248,7 @@ export function generateTSCaller(
// writeFileSync(`${outputPath}${fileName}`, content, 'utf8');
}

function generateCommonHelperFile(outputPath: string, mode: string) {
function generateCommonHelperFile(outputPath: string) {
const content = `/*****************HELPER GENERATED BY MASSA-PROTO-CLI*****************/
import {
Expand All @@ -278,10 +264,7 @@ import {
INodeStatus,
withTimeoutRejection,
} from "@massalabs/massa-web3";
${mode == 'wallet'
? 'import { IAccount } from "@massalabs/wallet-provider";\n'
: ''
}
export const MASSA_EXEC_ERROR = 'massa_execution_error';
/**
Expand Down Expand Up @@ -430,13 +413,11 @@ const pollAsyncEvents = async (
* generate a personalized extractOutputsAndEvents function for each proto file
*
* @param protoFile - The protoFile object
* @param mode - The generation mode
* @param outputPath - The path where the file will be generated
* @param contractName - The name of the contract
*/
function generatePollerFunction(
protoFile: ProtoFile,
mode: string,
outputPath: string,
contractName: string,
) {
Expand Down Expand Up @@ -466,14 +447,11 @@ import {
OperationOutputs,
} from "./${contractName}Caller";
import { getEvents } from "./commonHelper";
import { IBaseAccount } from "@massalabs/massa-web3/dist/esm/interfaces/IBaseAccount";
import {
IEvent,${mode == 'web3'
? `\n SmartContractsClient,
ICallData,`
: ''
}
IEvent,
ICallData,
} from "@massalabs/massa-web3";${customResponseImport}
${mode == 'wallet' ? 'import { IAccount, providers } from "@massalabs/wallet-provider";\n' : ''}
`;

Expand All @@ -491,7 +469,7 @@ export async function ${protoFile.funcName}ExtractOutputsAndEvents(
args: Uint8Array,
coins: bigint,
returnType: string,
account: ${mode == 'web3' ? 'SmartContractsClient' : 'IAccount'},
account: IBaseAccount,
nodeUrl: string,
fee = 0n,
maxGas = BigInt(4_294_967_295), // = max block gas limit
Expand All @@ -502,7 +480,7 @@ export async function ${protoFile.funcName}ExtractOutputsAndEvents(
// try to call the Smart Contract
try{
events = await getEvents(
${callSCConstructor(mode)},
${callSCConstructor()},
nodeUrl,
)
}
Expand Down Expand Up @@ -585,7 +563,6 @@ export async function ${protoFile.funcName}ExtractOutputsAndEvents(

function generateCommonCallerFile(
protoFiles: ProtoFile[],
mode: string,
contractName: string,
): string {
// import the ${protoFile.funcName}ExtractOutputsAndEvents functions
Expand All @@ -607,20 +584,10 @@ function generateCommonCallerFile(
return `
${imports.slice(0, -1)}
import {
IEvent,${mode == 'web3'
? `\n ProviderType,
SmartContractsClient,
PublicApiClient,
IAccount,
IEvent,
WalletClient,
Web3Account,`
: ''
}
} from "@massalabs/massa-web3";
${mode == 'wallet'
? 'import { IAccount, providers } from "@massalabs/wallet-provider";\n'
: ''
}${customTypesImports}
import { IBaseAccount } from "@massalabs/massa-web3/dist/esm/interfaces/IBaseAccount";${customTypesImports}
/**
* This interface is used to represents the outputs of the SC call.
Expand All @@ -637,13 +604,13 @@ export interface OperationOutputs {
export class ${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller {
private nodeRPC: string;
public account: ${mode == 'web3' ? 'SmartContractsClient' : 'IAccount'};
public account: IBaseAccount;
public coins: bigint;
public fee: bigint = 0n;
public maxGas: bigint = BigInt(4_294_967_295); // = max block gas limit
constructor(account: ${mode == 'web3' ? 'SmartContractsClient' : 'IAccount'}, coins: bigint, nodeRPC: string, fee?: bigint, maxGas?: bigint) {
constructor(account: IBaseAccount, coins: bigint, nodeRPC: string, fee?: bigint, maxGas?: bigint) {
this.nodeRPC = nodeRPC;
this.account = account;
this.coins = coins;
Expand All @@ -654,52 +621,17 @@ export class ${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainC
/**
* This method have been generated by the Massa Proto CLI.
* It allows you to instantiate a new ${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller object with the default values.
* ${mode == 'web3'
? ''
: `
* @param {string} providerName - The name of the provider to use
* @param {number} accountIndex - The index of the account to use in the provider's list of accounts
* `}
*
* @param {WalletClient} walletClient - The wallet client object to create the account from
*
* @returns {Promise<${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller>} A promise that resolves to a new ${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller object
*/
static async newDefault(${mode == 'web3' ? '' : 'providerName: string, accountIndex: number'}): Promise<${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller> {
${mode == 'web3'
? `// check if the environment variables are set
if (!process.env.NODE_RPC) {
throw new Error('NODE_RPC environment variable is not set');
}
if (!process.env.ACCOUNT_SECRET_KEY) {
throw new Error('ACCOUNT_SECRET_KEY environment variable is not set');
}
const providerPub = {
url: process.env.NODE_RPC,
type: ProviderType.PUBLIC,
};
const clientConfig = {
providers: [providerPub],
periodOffset: null,
};
const publicApiClient = new PublicApiClient(clientConfig);
const iaccount: IAccount = await WalletClient.getAccountFromSecretKey(process.env.ACCOUNT_SECRET_KEY);
const account = new Web3Account(iaccount, publicApiClient);
const walletClient = new WalletClient(clientConfig, publicApiClient, account);
const SC_Client = new SmartContractsClient(
clientConfig,
publicApiClient,
walletClient,
);`
: `// get the available providers
const provider = await providers();
// chose the provider
const providerToUse = provider.find((p) => String(p.name()) === providerName);
if (!providerToUse) {
throw new Error("Provider '" + providerName + "'not found");
}`}
return new ${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller(${mode == 'web3'
? 'SC_Client'
: '(await providerToUse.accounts())[accountIndex]'}, 0n, ${mode == 'web3'
? 'process.env.NODE_RPC'
: '(await providerToUse.getNodesUrls())[0]'});
static async newDefault(walletClient: WalletClient): Promise<${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller> {
const nodeRPC = await walletClient.clientConfig.providers[0].url;
const account = await walletClient.getBaseAccount();
if(!account) throw new Error("No account found in the wallet");
const coins = 0n;
return new ${contractName[0].toUpperCase() + contractName.slice(1)}BlockchainCaller(account, coins, nodeRPC);
}
`;
}
Expand Down Expand Up @@ -740,12 +672,8 @@ export function generateTsCallers(
protoFiles: ProtoFile[],
outputDirectory: string,
address: string,
mode: string,
contractName: string,
) {
// check the mode
if (mode != 'web3' && mode != 'wallet')
throw new Error('Error: mode must be either "web3" or "wallet".');
// generate the helper file for each proto file
for (let protoFile of protoFiles) {
// generate the helper file using protoc. Throws an error if the command fails.
Expand Down Expand Up @@ -777,13 +705,13 @@ export function generateTsCallers(
}

// add the event pollerClass into the helper file
generatePollerFunction(protoFile, mode, outputDirectory, contractName);
generatePollerFunction(protoFile, outputDirectory, contractName);
}
// generate the common helper file
generateCommonHelperFile(outputDirectory, mode);
generateCommonHelperFile(outputDirectory);

// generate the common part of the caller file
const part1 = generateCommonCallerFile(protoFiles, mode, contractName);
const part1 = generateCommonCallerFile(protoFiles, contractName);

// generate the caller method file for each proto file
let part2 = '';
Expand Down

0 comments on commit 908b9c5

Please sign in to comment.