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 #412

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
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
65 changes: 64 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.

23 changes: 23 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 @@ -76,6 +76,7 @@
"eslint": "8.54.0",
"eslint-config-prettier": "8.10.0",
"json5": "2.2.3",
"near-workspaces": "4.0.0",
"npm-run-all": "4.1.5",
"prettier": "2.8.8",
"typescript": "4.7.4"
Expand Down
85 changes: 84 additions & 1 deletion packages/near-sdk-js/src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ 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();
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)
Comment on lines +89 to +102
Copy link
Contributor

Choose a reason for hiding this comment

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

How is it different from using near.cli.rs and watching for "Gas burned" in the output?

image
$ near contract call-function as-transaction qq.frol8.testnet f1 json-args '{}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR'

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

All transactions here are executed on sandbox env. The idea of this command was to make it easier for new people to start working with near-sdk-js.

)
.parse();

function getTargetDir(target: string): string {
Expand Down Expand Up @@ -389,3 +405,70 @@ 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 +
// TODO: remove after near-workspaces is updated
(tx.result.receipts_outcome[1].outcome.gas_burnt || 0)
)
}
}
32 changes: 32 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,35 @@ 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 +
// TODO: remove after near-workspaces is updated
(r.result.receipts_outcome[1].outcome.gas_burnt || 0)
),
'\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