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

feat: sf-598 estimate gas fee with txn v3 #220

Closed
wants to merge 6 commits into from
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
4 changes: 2 additions & 2 deletions packages/starknet-snap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
"chai-as-promised": "^7.1.1",
"concurrently": "^7.1.0",
"cross-env": "^7.0.3",
"envify": "^4.1.0",
"eslint": "^8.13.0",
"mocha": "^9.2.2",
"nyc": "^15.1.0",
Expand All @@ -54,9 +53,10 @@
"dependencies": {
"@metamask/snaps-sdk": "3.0.1",
"async-mutex": "^0.3.2",
"dotenv": "^16.4.5",
"ethereum-unit-converter": "^0.0.17",
"ethers": "^5.5.1",
"starknet": "^5.14.0",
"starknet": "6.6.6",
"starknet_v4.22.0": "npm:[email protected]"
},
"publishConfig": {
Expand Down
26 changes: 12 additions & 14 deletions packages/starknet-snap/snap.config.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import envify from "envify/custom";
import * as dotenv from "dotenv";
dotenv.config();

module.exports = {
cliOptions: {
dist: 'dist',
outfileName: 'bundle.js',
src: './src/index.ts',
},
bundlerCustomizer: (bundler) => {
bundler.transform(
envify({
SNAP_ENV: process.env.SNAP_ENV,
}),
);
},
};
bundler: "webpack",
environment: {
SNAP_ENV: process.env.SNAP_ENV ?? "prod",
},
input: "./src/index.ts",
server: {
port: 8081,
},
polyfills: true
};
2 changes: 1 addition & 1 deletion packages/starknet-snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/ConsenSys/starknet-snap.git"
},
"source": {
"shasum": "A3cyal6PKAzEQQ3ptdBUK106XMp5jQVh4kydh87u7AA=",
"shasum": "YbuYD0p5mRtllKx98NNZ9YIz+G7QBvd3iW1S6Vc1kjg=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
13 changes: 4 additions & 9 deletions packages/starknet-snap/src/createAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export async function createAccount(params: ApiParams, silentMode = false) {
privateKey,
);
logger.log(`createAccount:\nestimateDeployFee: ${toJson(estimateDeployFee)}`);
if (Number(getBalanceResp.result[0]) < Number(estimateDeployFee.suggestedMaxFee)) {
if (Number(getBalanceResp[0]) < Number(estimateDeployFee.suggestedMaxFee)) {
const gasFeeStr = ethers.utils.formatUnits(estimateDeployFee.suggestedMaxFee.toString(10), 18);
const gasFeeFloat = parseFloat(gasFeeStr).toFixed(6); // 6 decimal places for ether
const gasFeeInEther = Number(gasFeeFloat) === 0 ? '0.000001' : gasFeeFloat;
Expand All @@ -110,14 +110,9 @@ export async function createAccount(params: ApiParams, silentMode = false) {
}
}

const deployResp = await deployAccount(
network,
contractAddress,
contractCallData,
publicKey,
privateKey,
estimateDeployFee?.suggestedMaxFee,
);
const deployResp = await deployAccount(network, contractAddress, contractCallData, publicKey, privateKey, {
maxFee: estimateDeployFee?.suggestedMaxFee,
});

if (deployResp.contract_address && deployResp.transaction_hash) {
const userAccount: AccContract = {
Expand Down
58 changes: 24 additions & 34 deletions packages/starknet-snap/src/estimateFee.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { toJson } from './utils/serializer';
import { Invocations, TransactionType } from 'starknet';
import { Invocations, TransactionType, constants } from 'starknet';
import { validateAndParseAddress } from '../src/utils/starknetUtils';
import { ApiParams, EstimateFeeRequestParams } from './types/snapApi';
import { getNetworkFromChainId } from './utils/snapUtils';
import {
getKeysFromAddress,
getCallDataArray,
estimateFee as estimateFeeUtil,
getAccContractAddressAndCallData,
estimateFeeBulk,
addFeesFromAllTransactions,
isAccountDeployed,
} from './utils/starknetUtils';

import { PROXY_CONTRACT_HASH } from './utils/constants';
import { PRICE_UNIT, PROXY_CONTRACT_HASH } from './utils/constants';
import { logger } from './utils/logger';

export async function estimateFee(params: ApiParams) {
Expand All @@ -40,6 +39,9 @@ export async function estimateFee(params: ApiParams) {
throw new Error(`The given sender address is invalid: ${requestParamsObj.senderAddress}`);
}

const priceUnit = requestParamsObj.priceUnit ?? PRICE_UNIT.WEI;
const txVersion =
priceUnit === PRICE_UNIT.FRI ? constants.TRANSACTION_VERSION.V3 : constants.TRANSACTION_VERSION.V1;
const contractAddress = requestParamsObj.contractAddress;
const contractFuncName = requestParamsObj.contractFuncName;
const contractCallData = getCallDataArray(requestParamsObj.contractCallData);
Expand All @@ -62,12 +64,9 @@ export async function estimateFee(params: ApiParams) {

//Estimate deploy account fee if the signer has not been deployed yet
const accountDeployed = await isAccountDeployed(network, publicKey);
let bulkTransactions: Invocations = [
{
type: TransactionType.INVOKE,
payload: txnInvocation,
},
];

const transactions: Invocations = [];

if (!accountDeployed) {
const { callData } = getAccContractAddressAndCallData(publicKey);
const deployAccountpayload = {
Expand All @@ -77,39 +76,30 @@ export async function estimateFee(params: ApiParams) {
addressSalt: publicKey,
};

bulkTransactions = [
{
type: TransactionType.DEPLOY_ACCOUNT,
payload: deployAccountpayload,
},
{
type: TransactionType.INVOKE,
payload: txnInvocation,
},
];
transactions.push({
type: TransactionType.DEPLOY_ACCOUNT,
payload: deployAccountpayload,
});
}

let estimateFeeResp;

if (accountDeployed) {
// This condition branch will be removed later when starknet.js
// supports estimateFeeBulk in rpc mode
estimateFeeResp = await estimateFeeUtil(network, senderAddress, senderPrivateKey, txnInvocation);
logger.log(`estimateFee:\nestimateFeeUtil estimateFeeResp: ${toJson(estimateFeeResp)}`);
} else {
const estimateBulkFeeResp = await estimateFeeBulk(network, senderAddress, senderPrivateKey, bulkTransactions);
logger.log(`estimateFee:\nestimateFeeBulk estimateBulkFeeResp: ${toJson(estimateBulkFeeResp)}`);
estimateFeeResp = addFeesFromAllTransactions(estimateBulkFeeResp);
}
transactions.push({
type: TransactionType.INVOKE,
payload: txnInvocation,
});

const estimateBulkFeeResp = await estimateFeeBulk(network, senderAddress, senderPrivateKey, transactions, {
version: txVersion,
});
logger.log(`estimateFee:\nestimateFeeBulk estimateBulkFeeResp: ${toJson(estimateBulkFeeResp)}`);

const estimateFeeResp = addFeesFromAllTransactions(estimateBulkFeeResp);

logger.log(`estimateFee:\nestimateFeeResp: ${toJson(estimateFeeResp)}`);

const resp = {
suggestedMaxFee: estimateFeeResp.suggestedMaxFee.toString(10),
overallFee: estimateFeeResp.overall_fee.toString(10),
gasConsumed: estimateFeeResp.gas_consumed?.toString(10) ?? '0',
gasPrice: estimateFeeResp.gas_price?.toString(10) ?? '0',
unit: 'wei',
unit: priceUnit.toLowerCase(),
includeDeploy: !accountDeployed,
};
logger.log(`estimateFee:\nresp: ${toJson(resp)}`);
Expand Down
2 changes: 1 addition & 1 deletion packages/starknet-snap/src/getErc20TokenBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function getErc20TokenBalance(params: ApiParams) {

logger.log(`getErc20Balance:\nresp: ${toJson(resp)}`);

return resp.result[0];
return resp[0];
} catch (err) {
logger.error(`Problem found: ${err}`);
throw err;
Expand Down
2 changes: 1 addition & 1 deletion packages/starknet-snap/src/getValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export async function getValue(params: ApiParams) {

logger.log(`getValue:\nresp: ${toJson(resp)}`);

return resp.result;
return resp;
} catch (err) {
logger.error(`Problem found: ${err}`);
throw err;
Expand Down
2 changes: 2 additions & 0 deletions packages/starknet-snap/src/types/snapApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
DeclareSignerDetails,
typedData,
} from 'starknet';
import { PRICE_UNIT } from '../utils/constants';

export interface ApiParams {
state: SnapState;
Expand Down Expand Up @@ -113,6 +114,7 @@ export interface EstimateFeeRequestParams extends BaseRequestParams {
contractFuncName: string;
contractCallData?: string;
senderAddress: string;
priceUnit?: PRICE_UNIT;
}

export interface EstimateAccountDeployFeeRequestParams extends BaseRequestParams {
Expand Down
7 changes: 6 additions & 1 deletion packages/starknet-snap/src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ export const TRANSFER_SELECTOR_HEX = '0x83afd3f4caedc6eebf44246fe54e38c95e3179a5

export const ACCOUNT_CLASS_HASH_V0 = '0x033434ad846cdd5f23eb73ff09fe6fddd568284a0fb7d1be20ee482f044dabe2'; // from argent-x repo

export enum PRICE_UNIT {
WEI = 'WEI',
FRI = 'FRI',
}

interface IDappConfig {
dev: string;
staging: string;
Expand All @@ -40,7 +45,7 @@ export const STARKNET_TESTNET_NETWORK: Network = {
name: 'Goerli Testnet (deprecated soon)',
chainId: constants.StarknetChainId.SN_GOERLI,
baseUrl: 'https://alpha4.starknet.io',
nodeUrl: 'https://starknet-goerli.infura.io/v3/60c7253fb48147658095fe0460ac9ee9',
nodeUrl: 'https://starknet-goerli.g.alchemy.com/starknet/version/rpc/v0_7/1Bw_6sofLIpDzAROgFM1KXIISP2jUAVO',
voyagerUrl: 'https://goerli.voyager.online',
accountClassHash: '', // from argent-x repo
};
Expand Down
Loading
Loading