Skip to content

Commit

Permalink
feat: implemented transaction estimation method
Browse files Browse the repository at this point in the history
Signed-off-by: tipusinghaw <[email protected]>
  • Loading branch information
tipusinghaw committed Feb 1, 2024
1 parent dfa678f commit c9fc71e
Show file tree
Hide file tree
Showing 3 changed files with 156 additions and 13 deletions.
20 changes: 10 additions & 10 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

96 changes: 95 additions & 1 deletion src/schema-manager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { Contract, JsonRpcProvider, SigningKey, Wallet } from 'ethers'
import {
Contract,
JsonRpcProvider,
SigningKey,
Wallet,
Network
} from 'ethers'
import { parseDid, validateDid } from './utils/did'
import { v4 as uuidv4 } from 'uuid'
import SchemaRegistryAbi from './abi/SchemaRegistry.json'
Expand Down Expand Up @@ -34,6 +40,17 @@ export type ResourcePayload = {
nextVersionId: string | null
}

export type EstimatedTxDetails = {
transactionFee: string
gasLimit: string
gasPrice: string
maxFeePerGas: number
maxPriorityFeePerGas: number
network: string
chainId: string
method: string
}

export class PolygonSchema {
private didRegistry: Contract
private schemaRegistry: Contract
Expand Down Expand Up @@ -216,4 +233,81 @@ export class PolygonSchema {
throw error
}
}

public async estimateTxFee(
contractAddress: string,
method: string,
argument: string[],
rpcUrl: string,
): Promise<EstimatedTxDetails | null> {
try {
const provider = new JsonRpcProvider(rpcUrl);
const contract = new Contract(
contractAddress,
SchemaRegistryAbi,
provider,
);

// Encode function data
const encodedFunction = await contract.interface.encodeFunctionData(
method,
argument,
);

// Check if encodedFunction is null or empty
if (!encodedFunction) {
throw new Error('Error while getting encoded function details');
}

// Estimate gas limit
const gasLimit = await provider.estimateGas({
to: contractAddress,
data: encodedFunction,
});

// Convert gas limit to Gwei
const gasLimitGwei = parseFloat(String(gasLimit)) / 1e9;

// Get gas price details
const gasPriceDetails = await provider.getFeeData();

// Check if gas price details are available
if (!gasPriceDetails || !gasPriceDetails.gasPrice) {
throw new Error('Gas price details not found!');
}

// Convert gas price to Gwei
const gasPriceGwei = parseFloat(String(gasPriceDetails.gasPrice)) / 1e9;

// Get network details
const networkDetails: Network = await provider.getNetwork();

// Check if network details are available
if (!networkDetails) {
throw new Error('Network details not found!');
}

// Calculate transaction fee
const transactionFee = gasLimitGwei * gasPriceGwei;

// Create EstimatedTxDetails object
const estimatedTxDetails: EstimatedTxDetails = {
transactionFee: String(transactionFee),
gasLimit: String(gasLimitGwei),
gasPrice: String(gasPriceGwei),
maxFeePerGas: parseFloat(String(gasPriceDetails.maxFeePerGas)) / 1e9,
maxPriorityFeePerGas:
parseFloat(String(gasPriceDetails.maxPriorityFeePerGas)) / 1e9,
network: String(networkDetails.name),
chainId: String(networkDetails.chainId),
method,
};

return estimatedTxDetails;
} catch (error) {
console.error('Error calculating transaction fee:', error);
return null;
}
}

}
53 changes: 51 additions & 2 deletions tests/schema-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ import { describe, it, before } from 'node:test'
import assert from 'node:assert'
import { arrayHasKeys } from './utils/array'
import { PolygonSchema } from '../src/schema-manager'
import { SigningKey } from 'ethers'

const NETWORK_URL = testContractDetails.networkUrl
const DID_REGISTRAR_CONTRACT_ADDRESS = testContractDetails.contractAddress
const SCHEMA_MANAGER_CONTRACT_ADDRESS =
testContractDetails.schemaManagerContract

describe('Registrar', () => {
describe('Schema Manager', () => {
let polygonSchemaManager: PolygonSchema
let polygonDID: string

Expand All @@ -25,7 +26,7 @@ describe('Registrar', () => {
didRegistrarContractAddress: DID_REGISTRAR_CONTRACT_ADDRESS,
schemaManagerContractAddress: SCHEMA_MANAGER_CONTRACT_ADDRESS,
rpcUrl: NETWORK_URL,
privateKey: testDidDetails.privateKey,
signingKey: new SigningKey(`0x${testDidDetails.privateKey}`),
serverUrl: fileServerUrl,
fileServerToken: fileServerAccessToken,
})
Expand Down Expand Up @@ -119,4 +120,52 @@ describe('Registrar', () => {
assert.strictEqual(schemaDetail.resourceType, 'W3C-schema')
})
})

describe('test estimate transaction', () => {
let transactionDetails: any

before(async () => {
transactionDetails = await polygonSchemaManager.estimateTxFee(
testContractDetails.schemaManagerContract,
'createSchema',
[
'0x13cd23928Ae515b86592C630f56C138aE4c7B79a',
'68768734687ytruwytuqyetrywqt',
'ertyuioiuytyuiuyt',
],
testContractDetails.networkUrl,
)
})

it('should have non-empty values for transaction details', () => {
assert.ok(transactionDetails)

assert.ok(transactionDetails.transactionFee)
assert.notStrictEqual(
transactionDetails.transactionFee,
'' || null || undefined,
)

assert.ok(transactionDetails.gasLimit)
assert.notStrictEqual(
transactionDetails.gasLimit,
'' || null || undefined,
)

assert.ok(transactionDetails.gasPrice)
assert.notStrictEqual(
transactionDetails.gasPrice,
'' || null || undefined,
)

assert.ok(transactionDetails.network)
assert.notStrictEqual(transactionDetails.network, '' || null || undefined)

assert.ok(transactionDetails.chainId)
assert.notStrictEqual(transactionDetails.chainId, '' || null || undefined)

assert.ok(transactionDetails.method)
assert.notStrictEqual(transactionDetails.method, '' || null || undefined)
})
})
})

0 comments on commit c9fc71e

Please sign in to comment.