Skip to content

Commit

Permalink
feat: default estimateFee to pending block
Browse files Browse the repository at this point in the history
  • Loading branch information
janek26 committed Apr 1, 2022
1 parent d3c1bdc commit 719dda5
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 37 deletions.
30 changes: 21 additions & 9 deletions src/account/default.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import assert from 'minimalistic-assert';

import { Provider } from '../provider';
import { BlockIdentifier } from '../provider/utils';
import { Signer, SignerInterface } from '../signer';
import {
Abi,
Expand Down Expand Up @@ -46,9 +47,15 @@ export class Account extends Provider implements AccountInterface {
return toHex(toBN(result[0]));
}

public async estimateFee(calls: Call | Call[]): Promise<EstimateFeeResponse> {
public async estimateFee(
calls: Call | Call[],
{
nonce: providedNonce,
blockIdentifier = 'pending',
}: { nonce?: BigNumberish; blockIdentifier?: BlockIdentifier } = {}
): Promise<EstimateFeeResponse> {
const transactions = Array.isArray(calls) ? calls : [calls];
const nonce = await this.getNonce();
const nonce = providedNonce ?? (await this.getNonce());
const signerDetails = {
walletAddress: this.address,
nonce: toBN(nonce),
Expand All @@ -57,12 +64,16 @@ export class Account extends Provider implements AccountInterface {
const signature = await this.signer.signTransaction(transactions, signerDetails);

const calldata = [...fromCallsToExecuteCalldata(transactions), signerDetails.nonce.toString()];
return this.fetchEndpoint('estimate_fee', undefined, {
contract_address: this.address,
entry_point_selector: getSelectorFromName('__execute__'),
calldata,
signature: bigNumberishArrayToDecimalStringArray(signature),
});
return this.fetchEndpoint(
'estimate_fee',
{ blockIdentifier },
{
contract_address: this.address,
entry_point_selector: getSelectorFromName('__execute__'),
calldata,
signature: bigNumberishArrayToDecimalStringArray(signature),
}
);
}

/**
Expand All @@ -80,7 +91,8 @@ export class Account extends Provider implements AccountInterface {
): Promise<AddTransactionResponse> {
const transactions = Array.isArray(calls) ? calls : [calls];
const nonce = toBN(transactionsDetail.nonce ?? (await this.getNonce()));
const maxFee = transactionsDetail.maxFee ?? (await this.estimateFee(transactions)).amount;
const maxFee =
transactionsDetail.maxFee ?? (await this.estimateFee(transactions, { nonce })).amount;
const signerDetails = {
walletAddress: this.address,
nonce,
Expand Down
38 changes: 20 additions & 18 deletions src/contract/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import assert from 'minimalistic-assert';

import { AccountInterface } from '../account';
import { ProviderInterface, defaultProvider } from '../provider';
import { BlockIdentifier } from '../provider/utils';
import {
Abi,
AbiEntry,
Expand Down Expand Up @@ -528,7 +529,11 @@ export class Contract implements ContractInterface {
}, [] as Result);
}

public invoke(method: string, args: Array<any> = []): Promise<AddTransactionResponse> {
public invoke(
method: string,
args: Array<any> = [],
options: Overrides = {}
): Promise<AddTransactionResponse> {
// ensure contract is connected
assert(this.address !== null, 'contract isnt connected to an address');
// validate method and args
Expand All @@ -542,11 +547,6 @@ export class Contract implements ContractInterface {
return acc;
}, 0);

const overrides: Overrides = {};
if (args.length === inputsLength + 1 && Array.isArray(args[args.length - 1])) {
Object.assign(overrides, args.pop());
}

if (args.length !== inputsLength) {
throw Error(
`Invalid number of arguments, expected ${inputsLength} arguments, but got ${args.length}`
Expand All @@ -562,31 +562,33 @@ export class Contract implements ContractInterface {
};
if ('execute' in this.providerOrAccount) {
return this.providerOrAccount.execute(invocation, undefined, {
maxFee: overrides.maxFee,
nonce: overrides.nonce,
maxFee: options.maxFee,
nonce: options.nonce,
});
}

return this.providerOrAccount.invokeFunction({
...invocation,
signature: overrides.signature || [],
signature: options.signature || [],
});
}

public async call(method: string, args: Array<any> = []): Promise<Result> {
public async call(
method: string,
args: Array<any> = [],
{
blockIdentifier = 'pending',
}: {
blockIdentifier?: BlockIdentifier;
} = {}
): Promise<Result> {
// ensure contract is connected
assert(this.address !== null, 'contract isnt connected to an address');

// validate method and args
this.validateMethodAndArgs('CALL', method, args);
const { inputs } = this.abi.find((abi) => abi.name === method) as FunctionAbi;
const inputsLength = inputs.length;
const options = {
blockIdentifier: null,
};
if (args.length === inputsLength + 1 && typeof args[args.length - 1] === 'object') {
Object.assign(options, args.pop());
}

// compile calldata
const calldata = this.compileCalldata(args, inputs);
return this.providerOrAccount
Expand All @@ -596,7 +598,7 @@ export class Contract implements ContractInterface {
calldata,
entrypoint: method,
},
options
{ blockIdentifier }
)
.then((x) => this.parseResponse(method, x.result));
}
Expand Down
1 change: 0 additions & 1 deletion src/provider/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,6 @@ export class Provider implements ProviderInterface {

public async waitForTransaction(txHash: BigNumberish, retryInterval: number = 8000) {
let onchain = false;
await wait(retryInterval);

while (!onchain) {
// eslint-disable-next-line no-await-in-loop
Expand Down
15 changes: 7 additions & 8 deletions src/provider/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ type BlockIdentifierObject =
* @returns block identifier object
*/
export function getBlockIdentifier(blockIdentifier: BlockIdentifier): BlockIdentifierObject {
if (blockIdentifier === null) {
return { type: 'BLOCK_NUMBER', data: null };
}
if (blockIdentifier === 'pending') {
return { type: 'BLOCK_NUMBER', data: 'pending' };
}
if (typeof blockIdentifier === 'number') {
return { type: 'BLOCK_NUMBER', data: blockIdentifier };
}
Expand All @@ -52,12 +58,6 @@ export function getBlockIdentifier(blockIdentifier: BlockIdentifier): BlockIdent
if (typeof blockIdentifier === 'string' && !Number.isNaN(parseInt(blockIdentifier, 10))) {
return { type: 'BLOCK_NUMBER', data: parseInt(blockIdentifier, 10) };
}
if (blockIdentifier === null) {
return { type: 'BLOCK_NUMBER', data: null };
}
if (blockIdentifier === 'pending') {
return { type: 'BLOCK_NUMBER', data: 'pending' };
}
if (typeof blockIdentifier === 'string') {
throw new Error(`Invalid block identifier: ${blockIdentifier}`);
}
Expand All @@ -69,8 +69,7 @@ export function getBlockIdentifier(blockIdentifier: BlockIdentifier): BlockIdent
*
* [Reference](https://github.com/starkware-libs/cairo-lang/blob/fc97bdd8322a7df043c87c371634b26c15ed6cee/src/starkware/starknet/services/api/feeder_gateway/feeder_gateway_client.py#L164-L173)
*
* @param blockNumber
* @param blockHash
* @param blockIdentifier
* @returns block identifier for API request
*/
export function getFormattedBlockIdentifier(blockIdentifier: BlockIdentifier = null): string {
Expand Down
4 changes: 3 additions & 1 deletion src/types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ export type Endpoints = {
RESPONSE: CallContractResponse;
};
estimate_fee: {
QUERY: never;
QUERY: {
blockIdentifier: BlockIdentifier;
};
REQUEST: CallContractTransaction;
RESPONSE: EstimateFeeResponse;
};
Expand Down

0 comments on commit 719dda5

Please sign in to comment.