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 watchGas CLI command #8

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
64 changes: 63 additions & 1 deletion packages/near-sdk-js/lib/cli/cli.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions packages/near-sdk-js/lib/cli/utils.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions packages/near-sdk-js/lib/cli/utils.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/near-sdk-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"eslint": "^8.23.1",
"eslint-config-prettier": "^8.5.0",
"json5": "^2.2.3",
"near-workspaces": "3.5.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.7.1",
"typescript": "^4.7.2"
Expand Down
86 changes: 84 additions & 2 deletions packages/near-sdk-js/src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import { rollup } from "rollup";
import { Command } from "commander";
import signal from "signale";

import { executeCommand, validateContract } from "./utils.js";
import { executeCommand, formatGas, parseNamedArgs, validateContract } from "./utils.js";
import { runAbiCompilerPlugin } from "./abi.js";
import { Worker } from "near-workspaces";

const { Signale } = signal;
const PROJECT_DIR = process.cwd();
const NEAR_SDK_JS = "node_modules/near-sdk-js";
const TSC = "node_modules/.bin/tsc";
const TSC = "node_modules/.bin/tsc";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like that the formatting is a little bit off. Could you run the formatter here is an example of that?

const QJSC_DIR = `${NEAR_SDK_JS}/lib/cli/deps/quickjs`;
const QJSC = `${NEAR_SDK_JS}/lib/cli/deps/qjsc`;

Expand Down Expand Up @@ -85,6 +86,21 @@ program
.option("--verbose", "Whether to print more verbose output.", false)
.action(transpileJsAndBuildWasmCom)
)
.addCommand(
new Command("watchGas")
.usage("[target] [methodName params...] [methodName params...]")
.description(
"Measure gas used for a contract method. Run this command after deploying the contract."
)
.argument(
"[target]",
"Target file path and name. (e.g., ./build/counter.wasm)"
)
.argument(
"[...methodCalls]", "Method calls with their parameters (e.g., increase n=5 decrease n=2)"
)
.action(measureGas)
)
.parse();

function getTargetDir(target: string): string {
Expand Down Expand Up @@ -389,3 +405,69 @@ async function wasiStubContract(contractTarget: string, verbose = false) {
const WASI_STUB = `${NEAR_SDK_JS}/lib/cli/deps/binaryen/wasi-stub/run.sh`;
await executeCommand(`${WASI_STUB} ${contractTarget}`, verbose);
}

async function measureGas(target: string, ...methodCalls) {
let worker;
try {
worker = await Worker.init();
const root = worker.rootAccount;
const contract = await root.devDeploy(target);
const account = await root.createSubAccount("ali");

let currentMethod = null;
let methodParams = [];
const methodCallsArr = methodCalls.pop().args.slice(1);

const output = [];

for (let i = 0; i < methodCallsArr.length; i++) {
if (methodCallsArr[i].includes("=")) {
methodParams.push(methodCallsArr[i]);
continue;
}

if (currentMethod) {
const res = await processMethod(account, contract, currentMethod, methodParams);
output.push(res);
}

currentMethod = methodCallsArr[i];
methodParams = [];
}

if (currentMethod) {
const res = await processMethod(account, contract, currentMethod, methodParams);
output.push(res);
}

console.table(output.map(({Method, Params, TotalGas}) => ({
Method,
Params: JSON.stringify(Params),
TotalGas
})));
} catch (error) {
console.error(error);
} finally {
await worker?.tearDown();
}
}

async function processMethod(account, contract, method, params) {
const parsedParams = parseNamedArgs(params);
const tx = await account.callRaw(contract, method, parsedParams);

if (!tx.result.status.SuccessValue && tx.result.status.Failure) {
console.error(JSON.stringify(tx.result.status));
return {};
}

return {
Method: method,
Params: parsedParams,
TotalGas: formatGas(
tx.result.transaction_outcome.outcome.gas_burnt +
tx.result.receipts_outcome[0].outcome.gas_burnt +
tx.result.receipts_outcome[1].outcome.gas_burnt
)
}
}
31 changes: 31 additions & 0 deletions packages/near-sdk-js/src/cli/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,34 @@ export async function validateContract(

return true;
}

export function parseNamedArgs(args) {
return args.reduce((acc, arg) => {
const [key, value] = arg.split('=');
acc[key] = value;
return acc;
}, {});
}

export function logTotalGas(r) {
console.log(
'Total gas used: ',
formatGas(
r.result.transaction_outcome.outcome.gas_burnt +
r.result.receipts_outcome[0].outcome.gas_burnt +
r.result.receipts_outcome[1].outcome.gas_burnt
),
'\n'
);
}

export function formatGas(gas) {
if (gas < 10 ** 12) {
const tGas = gas / 10 ** 12;
const roundTGas = Math.round(tGas * 100000) / 100000;
return roundTGas + "T";
}
const tGas = gas / 10 ** 12;
const roundTGas = Math.round(tGas * 100) / 100;
return roundTGas + "T";
}
Loading
Loading