Skip to content
Closed
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
26 changes: 21 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,11 +235,11 @@ EXAMPLES:
genlayer deploy
genlayer deploy --contract ./my_contract.gpy
genlayer deploy --contract ./my_contract.gpy --args "arg1" "arg2" 123
genlayer deploy --contract ./my_contract.gpy --fees '{"distribution":{"leaderTimeunitsAllocation":"100","validatorTimeunitsAllocation":"200","rotations":["0"]}}'
genlayer deploy --contract ./my_contract.gpy --fees "$(genlayer estimate-fees --json)"
genlayer deploy --contract ./my_contract.gpy --fee-profile ./artifacts/fee-profile.json
genlayer call 0x123456789abcdef greet --args "Hello World!"
genlayer write 0x123456789abcdef updateValue --args 42
genlayer write 0x123456789abcdef updateValue --fees '{"distribution":{"leaderTimeunitsAllocation":"100","validatorTimeunitsAllocation":"200","rotations":["0"]}}' --args 42
genlayer write 0x123456789abcdef updateValue --fees "$(genlayer estimate-fees 0x123456789abcdef updateValue --args 42 --json)" --args 42
genlayer write 0x123456789abcdef updateValue --fee-profile ./artifacts/fee-profile.json --fee-preset standard --args 42
genlayer estimate-fees
genlayer estimate-fees 0x123456789abcdef updateValue --args 42
Expand Down Expand Up @@ -293,9 +293,25 @@ Use `callKeyMethod` for internal GenVM messages, `callKeySelector` for a 4-byte
EVM selector, or `callKeyCalldata` for full external calldata. Explicit
`callKey` is still accepted for advanced cases.

If `--fees` includes a `distribution` and `--fee-value` is omitted, the SDK
derives the fee deposit from FeeManager on network backends, or from
`sim_getFeeConfig` on Studio. Use `--fee-value` only when you need to force an
When the network fee policy is enabled (Studio reports it through
`sim_getFeeConfig`), `deploy` and `write` without any fee flags submit the same
estimate that `estimate-fees` prints for that transaction: `write` uses the
target-write estimate and `deploy` uses `estimateTransactionFees`. When the
policy is disabled the transaction is sent without fees, as before.

```bash
# Estimated automatically on a fee-enabled network
genlayer deploy --contract ./my_contract.gpy --args 42
genlayer write 0x123456789abcdef updateValue --args 42

# Review the estimate first, then send exactly that preset
genlayer deploy --contract ./my_contract.gpy --args 42 --fees "$(genlayer estimate-fees --json)"
```

If `--fees` has no `feeValue` and `--fee-value` is omitted, the CLI keeps every
field you set and fills the rest, including the fee deposit, from
`estimateTransactionFees`. A `feeValue` in `--fees` or `--fee-value` is sent
as given, with no estimate. Use `--fee-value` only when you need to force an
explicit deposit value.

`estimate-fees` prints the SDK fee preset. Without a contract/method it calls
Expand Down
42 changes: 40 additions & 2 deletions src/commands/contracts/fees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,13 +370,51 @@ export const toTransactionFees = (estimate: Record<string, any>): Record<string,
feeValue: estimate.feeValue ?? estimate.fee_value,
});

export type WriteFeeEstimateTarget = {address: string; functionName: string; args?: any[]};

type FeeEstimatingClient = {
chain?: {isStudio?: boolean; feeManagerContract?: {address?: string} | null};
getCurrentFeePolicy?: () => Promise<{enabled?: boolean}>;
estimateTransactionFees?: (options?: Record<string, any>) => Promise<Record<string, any>>;
estimateTransactionFeesForWrite?: (
options: WriteFeeEstimateTarget & {address: any},
) => Promise<Record<string, any>>;
};

const isFeePolicyEnabled = async (client: FeeEstimatingClient): Promise<boolean> => {
if (typeof client.getCurrentFeePolicy !== "function") return false;
if (!client.chain?.isStudio && !client.chain?.feeManagerContract?.address) return false;
return (await client.getCurrentFeePolicy()).enabled === true;
};

const estimateOmittedFees = async (
client: FeeEstimatingClient,
options: ContractFeeCliOptions,
config: FeeParseConfig,
writeTarget?: WriteFeeEstimateTarget,
): Promise<Record<string, any>> => {
// The write estimator resizes execution/message budgets, so it only runs when the user set no fields.
if (!options.fees && writeTarget && typeof client.estimateTransactionFeesForWrite === "function") {
return client.estimateTransactionFeesForWrite({...writeTarget, args: writeTarget.args ?? []});
}
if (typeof client.estimateTransactionFees !== "function") {
throw new Error("The active genlayer-js client does not support fee estimation.");
}
return client.estimateTransactionFees(parseFeeEstimateOptions({fees: options.fees}, config));
};

export const resolveTransactionFees = async (
client: {estimateTransactionFees?: (options?: Record<string, any>) => Promise<Record<string, any>>},
client: FeeEstimatingClient,
options: ContractFeeCliOptions,
config: FeeParseConfig = {},
writeTarget?: WriteFeeEstimateTarget,
): Promise<Record<string, any> | undefined> => {
if (!options.feeProfile) {
return parseTransactionFees(options, config);
const fees = parseTransactionFees(options, config);
if (fees?.feeValue !== undefined || !(await isFeePolicyEnabled(client))) {
return fees;
}
return toTransactionFees(await estimateOmittedFees(client, options, config, writeTarget));
}

if (typeof client.estimateTransactionFees !== "function") {
Expand Down
3 changes: 2 additions & 1 deletion src/commands/contracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ const FEES_HELP = [
"Transaction fee options JSON passed to genlayer-js.",
"Example:",
' \'{"distribution":{"leaderTimeunitsAllocation":"100","validatorTimeunitsAllocation":"200","rotations":["0"]}}\'',
"Omit --fee-value to let genlayer-js derive the fee deposit from FeeManager or Studio.",
"On fee-enabled networks without a feeValue, omitted fields are filled from the fee estimate;",
"with no fee flags at all, the estimate-fees estimate for the transaction is sent.",
'Message allocation messageType may be "internal", "external", 0, or 1.',
"Use callKeyMethod for internal messages, or callKeySelector/callKeyCalldata for external messages.",
].join("\n");
Expand Down
1 change: 1 addition & 0 deletions src/commands/contracts/write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export class WriteAction extends BaseAction {
client,
{fees, feeProfile, feePreset, appealRounds, feeValue, validUntil},
{profileTarget: {kind: "method", method}},
{address: contractAddress, functionName: method, args},
);
const parsedValidUntil = parseValidUntil({
fees,
Expand Down
130 changes: 130 additions & 0 deletions tests/actions/deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,136 @@ describe("DeployAction", () => {
});
});

describe("default fee estimation", () => {
const contractContent = "contract code";
const feeEstimate = {
distribution: {
leaderTimeunitsAllocation: 100n,
validatorTimeunitsAllocation: 200n,
executionBudgetPerRound: 25n,
rotations: [3n],
},
feeValue: 777n,
policy: {enabled: true},
};

const useFeePolicy = (enabled: boolean, chain: Record<string, any> = {isStudio: true}) => {
const getCurrentFeePolicy = vi.fn().mockResolvedValue({enabled});
vi.mocked(createClient).mockReturnValue({...mockClient, chain, getCurrentFeePolicy} as any);
return getCurrentFeePolicy;
};

beforeEach(() => {
vi.mocked(fs.readFileSync).mockReturnValue(contractContent);
vi.mocked(mockClient.estimateTransactionFees).mockResolvedValue(feeEstimate);
vi.mocked(mockClient.deployContract).mockResolvedValue("mocked_tx_hash");
vi.mocked(mockClient.waitForTransactionReceipt).mockResolvedValue({
statusName: "ACCEPTED",
txExecutionResultName: "FINISHED_WITH_RETURN",
data: {contract_address: "0xdasdsadasdasdada"},
});
});

test("submits the fee estimate when no fee flags are given and the policy is enabled", async () => {
useFeePolicy(true);

await deployer.deploy({contract: "/mocked/contract/path", args: [1]});

expect(mockClient.estimateTransactionFees).toHaveBeenCalledWith(undefined);
expect(mockClient.deployContract).toHaveBeenCalledWith({
code: contractContent,
args: [1],
leaderOnly: false,
fees: {distribution: feeEstimate.distribution, feeValue: 777n},
});
});

test("keeps gasless deploys when the fee policy is disabled", async () => {
const getCurrentFeePolicy = useFeePolicy(false);

await deployer.deploy({contract: "/mocked/contract/path", args: [1]});

expect(getCurrentFeePolicy).toHaveBeenCalled();
expect(mockClient.estimateTransactionFees).not.toHaveBeenCalled();
expect(mockClient.deployContract).toHaveBeenCalledWith({
code: contractContent,
args: [1],
leaderOnly: false,
});
});

test("does not read a fee policy on chains without Studio or a FeeManager", async () => {
const getCurrentFeePolicy = useFeePolicy(true, {isStudio: false, feeManagerContract: null});

await deployer.deploy({contract: "/mocked/contract/path", args: [1]});

expect(getCurrentFeePolicy).not.toHaveBeenCalled();
expect(mockClient.estimateTransactionFees).not.toHaveBeenCalled();
expect(mockClient.deployContract).toHaveBeenCalledWith({
code: contractContent,
args: [1],
leaderOnly: false,
});
});

test("completes --fees without a feeValue from the estimate, keeping the given fields", async () => {
useFeePolicy(true);

await deployer.deploy({
contract: "/mocked/contract/path",
args: [1],
fees: JSON.stringify({
distribution: {
leaderTimeunitsAllocation: "100",
validatorTimeunitsAllocation: "200",
rotations: ["0"],
},
messageAllocations: [
{messageType: "internal", recipient: "0x0000000000000000000000000000000000000001", budget: "5"},
],
}),
});

expect(mockClient.estimateTransactionFees).toHaveBeenCalledWith({
leaderTimeunitsAllocation: "100",
validatorTimeunitsAllocation: "200",
rotations: ["0"],
messageAllocations: [
{
messageType: 1,
recipient: "0x0000000000000000000000000000000000000001",
callKey: DEPLOY_CALL_KEY,
budget: "5",
},
],
});
expect(mockClient.deployContract).toHaveBeenCalledWith({
code: contractContent,
args: [1],
leaderOnly: false,
fees: {distribution: feeEstimate.distribution, feeValue: 777n},
});
});

test.each([
["--fee-value", {fees: JSON.stringify({distribution: {rotations: ["0"]}}), feeValue: "5"}],
["fees.feeValue", {fees: JSON.stringify({distribution: {rotations: ["0"]}, feeValue: "5"})}],
])("sends fees unchanged when %s is explicit", async (_label, feeOptions) => {
const getCurrentFeePolicy = useFeePolicy(true);

await deployer.deploy({contract: "/mocked/contract/path", args: [1], ...feeOptions});

expect(getCurrentFeePolicy).not.toHaveBeenCalled();
expect(mockClient.estimateTransactionFees).not.toHaveBeenCalled();
expect(mockClient.deployContract).toHaveBeenCalledWith({
code: contractContent,
args: [1],
leaderOnly: false,
fees: {distribution: {rotations: ["0"]}, feeValue: "5"},
});
});
});

test("fails when deployment reaches consensus but execution fails", async () => {
const options: DeployOptions = {
contract: "/mocked/contract/path",
Expand Down
128 changes: 128 additions & 0 deletions tests/actions/write.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,134 @@ describe("WriteAction", () => {
});
});

describe("default fee estimation", () => {
const feeEstimate = {
distribution: {
leaderTimeunitsAllocation: 100n,
validatorTimeunitsAllocation: 200n,
executionBudgetPerRound: 25n,
rotations: [3n],
},
feeValue: 777n,
policy: {enabled: true},
observed: {executionFeeConsumed: 1n},
};
const estimateTransactionFeesForWrite = vi.fn();
const getCurrentFeePolicy = vi.fn();

beforeEach(() => {
vi.mocked(createClient).mockReturnValue({
...mockClient,
chain: {isStudio: true},
getCurrentFeePolicy,
estimateTransactionFeesForWrite,
} as any);
getCurrentFeePolicy.mockResolvedValue({enabled: true});
estimateTransactionFeesForWrite.mockResolvedValue(feeEstimate);
vi.mocked(mockClient.estimateTransactionFees).mockResolvedValue(feeEstimate);
vi.mocked(mockClient.writeContract).mockResolvedValue("0xMockedTransactionHash");
vi.mocked(mockClient.waitForTransactionReceipt).mockResolvedValue({
statusName: "ACCEPTED",
txExecutionResultName: "FINISHED_WITH_RETURN",
});
});

test("submits the target-write estimate when no fee flags are given", async () => {
await writeAction.write({contractAddress: "0xMockedContract", method: "updateData", args: [42]});

expect(estimateTransactionFeesForWrite).toHaveBeenCalledWith({
address: "0xMockedContract",
functionName: "updateData",
args: [42],
});
expect(mockClient.estimateTransactionFees).not.toHaveBeenCalled();
expect(mockClient.writeContract).toHaveBeenCalledWith({
address: "0xMockedContract",
functionName: "updateData",
args: [42],
value: 0n,
fees: {distribution: feeEstimate.distribution, feeValue: 777n},
});
});

test("keeps gasless writes when the fee policy is disabled", async () => {
getCurrentFeePolicy.mockResolvedValue({enabled: false});

await writeAction.write({contractAddress: "0xMockedContract", method: "updateData", args: [42]});

expect(estimateTransactionFeesForWrite).not.toHaveBeenCalled();
expect(mockClient.writeContract).toHaveBeenCalledWith({
address: "0xMockedContract",
functionName: "updateData",
args: [42],
value: 0n,
});
});

test("completes --fees without a feeValue from estimateTransactionFees, keeping the given fields", async () => {
await writeAction.write({
contractAddress: "0xMockedContract",
method: "updateData",
args: [42],
fees: JSON.stringify({
distribution: {
leaderTimeunitsAllocation: "100",
validatorTimeunitsAllocation: "200",
rotations: ["0"],
},
}),
});

expect(estimateTransactionFeesForWrite).not.toHaveBeenCalled();
expect(mockClient.estimateTransactionFees).toHaveBeenCalledWith({
leaderTimeunitsAllocation: "100",
validatorTimeunitsAllocation: "200",
rotations: ["0"],
});
expect(mockClient.writeContract).toHaveBeenCalledWith({
address: "0xMockedContract",
functionName: "updateData",
args: [42],
value: 0n,
fees: {distribution: feeEstimate.distribution, feeValue: 777n},
});
});

test("sends an explicit --fee-value unchanged", async () => {
await writeAction.write({
contractAddress: "0xMockedContract",
method: "updateData",
args: [42],
feeValue: "9",
});

expect(getCurrentFeePolicy).not.toHaveBeenCalled();
expect(estimateTransactionFeesForWrite).not.toHaveBeenCalled();
expect(mockClient.writeContract).toHaveBeenCalledWith({
address: "0xMockedContract",
functionName: "updateData",
args: [42],
value: 0n,
fees: {feeValue: "9"},
});
});

test("falls back to estimateTransactionFees when the client has no write estimator", async () => {
vi.mocked(createClient).mockReturnValue({
...mockClient,
chain: {isStudio: true},
getCurrentFeePolicy,
} as any);

await writeAction.write({contractAddress: "0xMockedContract", method: "updateData", args: [42]});

expect(mockClient.estimateTransactionFees).toHaveBeenCalledWith(undefined);
expect(mockClient.writeContract).toHaveBeenCalledWith(
expect.objectContaining({fees: {distribution: feeEstimate.distribution, feeValue: 777n}}),
);
});
});

test("handles writeContract errors", async () => {
vi.mocked(mockClient.writeContract).mockRejectedValue(new Error("Mocked write error"));

Expand Down
Loading