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

[JSS-101] Estimate smart-contract update energy costs #362

Open
wants to merge 5 commits into
base: main
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
3 changes: 3 additions & 0 deletions .markdown-linkcheck.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
"ignorePatterns": [
{
"pattern": "classes/grpc.ConcordiumGRPCClient.html"
},
{
"pattern": "https://grpc.testnet.concordium.com:20000"
}
]
}
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ npm_config_target_arch=x64 yarn

### Building for a release

Note: you need rustup in order to build rust-bindings (can be installed from [rust-lang.org](https://www.rust-lang.org/tools/install))

To build the project run

```shell
Expand Down
4 changes: 4 additions & 0 deletions examples/nodejs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,7 @@ yarn run-example /path/to/example.ts [opts]
```

Where opts are any arguments that the example script takes.

Default endpoint for node is 'localhost:20000',
but instead of installing local node,
can be used testnet node <https://grpc.testnet.concordium.com:20000>
6 changes: 6 additions & 0 deletions packages/sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Added

- Method (`getContractUpdateEnergyCost`) for estimating energy usage of contract update.

## 7.4.0

### Added
Expand Down
13 changes: 13 additions & 0 deletions packages/sdk/src/contractHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,16 @@ export function getNamesFromReceive(receiveName: string): {
entrypointName: receiveName.substring(splitPoint + 1),
};
}

/**
* Get contract update payload size by adding reserved offsets to parameter size and receive name size
* Amount (8 bytes), Contract address (16 bytes), Receive name size (2 bytes), Parameter size (2 bytes)
*/
export function getUpdatePayloadSize(
parameterSize: number,
receiveNameLength: number
): bigint {
return (
8n + 16n + 2n + BigInt(parameterSize) + 2n + BigInt(receiveNameLength)
);
}
57 changes: 57 additions & 0 deletions packages/sdk/src/energyCost.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ConcordiumGRPCClient } from './grpc/GRPCClient.js';
import { getAccountTransactionHandler } from './accountTransactions.js';
import { collapseRatio, multiplyRatio } from './ratioHelpers.js';
import {
Expand All @@ -8,6 +9,14 @@ import {
} from './types.js';
import * as Energy from './types/Energy.js';
import * as CcdAmount from './types/CcdAmount.js';
import * as BlockHash from './types/BlockHash.js';
import {
AccountAddress,
ContractAddress,
Parameter,
ReceiveName,
} from './pub/types.js';
import { getUpdatePayloadSize } from './contractHelpers.js';

/**
* These constants must be consistent with constA and constB in:
Expand Down Expand Up @@ -60,6 +69,54 @@ export function getEnergyCost(
);
}

/**
* Get contract update energy cost
* Estimated by calculateEnergyCost, where transactionSpecificCost received from invokeContract used energy
* @param {ConcordiumGRPCClient} grpcClient - The client to be used for the query
* @param {ContractAddress.Type} contractAddress - The address of the contract to query
* @param {AccountAddress.Type} invoker - Representation of an account address
* @param {Parameter.Type} parameter - Input for contract function
* @param {ReceiveName.Type} method - Represents a receive-function in a smart contract module
* @param {bigint} signatureCount - Number of expected signatures
* @param {BlockHash.Type} [blockHash] - Optional block hash allowing for dry-running the contract update at the end of a specific block.
*
* @throws {Error} 'no response' if either the block does not exist, or then node fails to parse any of the inputs
* If the response tag is `failure`, then error contains a response message
*
* @returns {Energy} estimated amount of energy for the last finalized block according to the node,
* this means that the actual energy cost might be different depending on the implementation of the smart contract
* and the interaction with the instance, since this was estimated
*/
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggestion: Please document when this function throws and also that the estimate is given for the last finalized block according to the node, which means this the actual energy cost might be different depending on the implementation of the smart contract and the interaction with the instance, since this was estimated.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Would it not make sense to add an optional blockHash argument which can be passed to the grpc client?

export async function getContractUpdateEnergyCost(
grpcClient: ConcordiumGRPCClient,
contractAddress: ContractAddress.Type,
invoker: AccountAddress.Type,
parameter: Parameter.Type,
method: ReceiveName.Type,
signatureCount: bigint,
blockHash?: BlockHash.Type
): Promise<Energy.Type> {
const res = await grpcClient.invokeContract(
{
contract: contractAddress,
invoker,
parameter,
method,
},
blockHash
);

if (!res || res.tag === 'failure') {
throw new Error(res?.reason?.tag || 'no response');
}

return calculateEnergyCost(
signatureCount,
getUpdatePayloadSize(parameter.buffer.length, method.toString().length),
res.usedEnergy.value
);
}

/**
* Given the current blockchain parameters, return the microCCD per NRG exchange rate of the chain.
* @returns the microCCD per NRG exchange rate as a ratio.
Expand Down
Loading