0.0.4-rc.1 • Published 7 months ago

@57block/stellar-resource-usage v0.0.4-rc.1

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

NPM version View changelog

Stellar Resource Usage

Welcome to Stellar Resource Usage! This tool is designed for Web3 developers working on the Stellar network, providing a convenient way to monitor and analyze the resources consumed by smart contracts during execution. This enables developers to optimize contract performance effectively.

Result table

Features Overview

  1. Real-Time Resource Monitoring: The tool monitors resource usage in real-time during smart contract execution, including cpu_insns, mem_bytes etc. for more information,see the supported resource documentation.
  1. Detailed Report Generation: After contract execution, the tool generates a detailed report to help developers gain deeper insights into resource usage.
  1. Easy to use: The amount of intrusion code is very small and it is easy to use.
  1. Open Source Contribution: As an open-source project, we welcome community contributions, including bug fixes, feature enhancements, and improvement suggestions.

Installation Guide

To install and run Stellar Resource Usage locally, follow these steps:

  1. Install dependencies:

Using npm:

npm i @57block/stellar-resource-usage

Using pnpm:

pnpm add @57block/stellar-resource-usage

Using bun:

bun add @57block/stellar-resource-usage

Usage Instructions

  1. Make sure Docker Desktop is running on your system

  2. Start the unlimited network simulator. Executing the code below will launch a stellar/quickstart image. You can also customize your own image according to the quickstart if you want.

    Note: Using npx requires you to install npm globally in advance, more info please refer to npx

npx dockerDev [--port=your port] # The default port is 8000 
  1. Make sure you have seen a steady stream of stellar-core: Synced! logs in step 2. Deploy your contract once your local network is running. If you don’t know how to deploy a contract, you can check the Stellar build doc or the deploy.example.ts we provide for reference.

  2. Using @57block/stellar-resource-usage in your code

Scenario 1

Using StellarRpcServer.

import { Keypair, Networks, nativeToScVal, rpc, TransactionBuilder, Operation, Account } from '@stellar/stellar-sdk';

const rpcUrl = 'http://localhost:8000/rpc';
const keypair = Keypair.fromSecret(Bun.env.SECRET);
const contractId = Bun.env.CONTRACT_ID;
const networkPassphrase = Networks.STANDALONE;
const publicKey = keypair.publicKey();
const rpcServer = new rpc.Server(rpcUrl, { allowHttp: true });
const sourceAccount = await rpcServer
  .getAccount(publicKey)
  .then((account) => new Account(account.accountId(), account.sequenceNumber()))
  .catch(() => {
    throw new Error(`Issue with ${publicKey} account.`);
  })
const args = [
  nativeToScVal(150, { type: 'u32' }),
  nativeToScVal(20, { type: 'u32' }),
  nativeToScVal(2, { type: 'u32' }),
  nativeToScVal(4, { type: 'u32' }),
  nativeToScVal(1, { type: 'u32' }),
  nativeToScVal(Buffer.alloc(71_680)),
];
const tx = new TransactionBuilder(sourceAccount, {
  fee: '0',
  networkPassphrase,
})
  .addOperation(
    Operation.invokeContractFunction({
      contract: contractId,
      function: 'run',
      args,
    })
  )
  .setTimeout(0)
  .build();

const simRes = await rpcServer.simulateTransaction(tx);
const MAX_U32 = 2 ** 32 - 1;
if (rpc.Api.isSimulationSuccess(simRes)) {
  simRes.minResourceFee = MAX_U32.toString();
  const resources = simRes.transactionData.build().resources();
  const assembledTx = rpc
    .assembleTransaction(tx, simRes)
    .setSorobanData(
      simRes.transactionData
        .setResourceFee(100_000_000)
        .setResources(MAX_U32, resources.readBytes(), resources.writeBytes())
        .build()
    )
    .build();
  assembledTx.sign(keypair);

  await rpcServer.sendTransaction(assembledTx);
  rpcServer.printTable();
}

While using @57block/stellar-resource-usage:

import { Keypair, Networks, nativeToScVal, rpc, TransactionBuilder, Operation, Account } from '@stellar/stellar-sdk';
+ import { StellarRpcServer } from "@57block/stellar-resource-usage";

const rpcUrl = 'http://localhost:8000/rpc';
const keypair = Keypair.fromSecret(Bun.env.SECRET);
const contractId = Bun.env.CONTRACT_ID;
const networkPassphrase = Networks.STANDALONE;
const publicKey = keypair.publicKey();
- const rpcServer = new rpc.Server(rpcUrl, { allowHttp: true });
+ const rpcServer = new StellarRpcServer(rpcUrl, { allowHttp: true });
const sourceAccount = await rpcServer
  .getAccount(publicKey)
  .then((account) => new Account(account.accountId(), account.sequenceNumber()))
  .catch(() => {
    throw new Error(`Issue with ${publicKey} account.`);
  })
const args = [
  nativeToScVal(150, { type: 'u32' }),
  nativeToScVal(20, { type: 'u32' }),
  nativeToScVal(2, { type: 'u32' }),
  nativeToScVal(4, { type: 'u32' }),
  nativeToScVal(1, { type: 'u32' }),
  nativeToScVal(Buffer.alloc(71_680)),
];
const tx = new TransactionBuilder(sourceAccount, {
  fee: '0',
  networkPassphrase,
})
  .addOperation(
    Operation.invokeContractFunction({
      contract: contractId,
      function: 'run',
      args,
    })
  )
  .setTimeout(0)
  .build();

const simRes = await rpcServer.simulateTransaction(tx);
const MAX_U32 = 2 ** 32 - 1;
if (rpc.Api.isSimulationSuccess(simRes)) {
  simRes.minResourceFee = MAX_U32.toString();
  const resources = simRes.transactionData.build().resources();
  const assembledTx = rpc
    .assembleTransaction(tx, simRes)
    .setSorobanData(
      simRes.transactionData
        .setResourceFee(100_000_000)
        .setResources(MAX_U32, resources.readBytes(), resources.writeBytes())
        .build()
    )
    .build();
  assembledTx.sign(keypair);

  await rpcServer.sendTransaction(assembledTx);
+ rpcServer.printTable();
}

Scenario 2

When you generate a typescript module using the stellar contract bindings typescript command, and use the Client in this module to call and execute the contract functions.

import { Keypair } from "@stellar/stellar-sdk";
import { basicNodeSigner } from "@stellar/stellar-sdk/contract";

import { Client, networks } from "yourPath/to/module";

const callContract = async () => {
  try {
    const keypair = Keypair.fromSecret(Bun.env.SECRET!);
    const pubkey = keypair.publicKey();

    const { signTransaction } = basicNodeSigner(
      keypair,
      networks.standalone.networkPassphrase
    );

    const _contract = new Client({
      contractId: networks.standalone.contractId,
      networkPassphrase: networks.standalone.networkPassphrase,
      rpcUrl: "http://localhost:8000/soroban/rpc",
      publicKey: pubkey, // process.env.SOROBAN_PUBLIC_KEY,
      allowHttp: true,
      signTransaction,
    });
    const res = await _contract.run({
      cpu: 700,
      mem: 180,
      set: 20,
      get: 40,
      events: 1,
      _txn: Buffer.alloc(71_680),
    });

    await res.signAndSend();
  } catch (error) {
    console.error(error);
  }
};

callContract();

While using @57block/stellar-resource-usage:

import { Keypair } from "@stellar/stellar-sdk";
import { basicNodeSigner } from "@stellar/stellar-sdk/contract";
// Add ResourceUsageClient
+ import { ResourceUsageClient } from "@57block/stellar-resource-usage";
import { Client, networks } from "./package/typescriptBinding/src";

const callContract = async () => {
  try {
    const keypair = Keypair.fromSecret(Bun.env.SECRET!);
    const pubkey = keypair.publicKey();

    const { signTransaction } = basicNodeSigner(
      keypair,
      networks.standalone.networkPassphrase
    );

-    const _contract = new Client({
+    const _contract = await ResourceUsageClient<Client>(Client, {
      contractId: networks.standalone.contractId,
      networkPassphrase: networks.standalone.networkPassphrase,
      rpcUrl: "http://localhost:8000/soroban/rpc",
      publicKey: pubkey, // process.env.SOROBAN_PUBLIC_KEY,
      allowHttp: true,
      signTransaction,
    });
    const res = await _contract.run({
      cpu: 700,
      mem: 180,
      set: 20,
      get: 40,
      events: 1,
      _txn: Buffer.alloc(71_680),
    });

    await res.signAndSend();

+   _contract.printTable();
  } catch (error) {
    console.error(error);
  }
};

callContract();
  1. Execute the file

For typescript files, we recommend using bun to run directly, which makes the command very simple, just execute bun run filepath. Then you will see the reporter in the terminal.

Support

If you need assistance or have any questions, you can submit issues on GitHub Issues, and we'll respond as soon as possible.

License

This project is open-source under the MIT License.

Enhance your smart contract efficiency and speed with Stellar Resource Usage! Thank you for using this tool, and we look forward to your feedback and contributions.

0.0.4-rc.1

7 months ago

0.0.3-rc.1

7 months ago

1.2.0

7 months ago

0.0.3

7 months ago

0.0.2-rc.1

9 months ago

0.0.2

9 months ago

0.0.1-rc.1

10 months ago

0.0.1

10 months ago