Skip to content

Commit

Permalink
Merge branch 'main' into snyk-fix-9bcf504af3c2f9ce2fc4a5e749b3370a
Browse files Browse the repository at this point in the history
Signed-off-by: ebadiere <[email protected]>
  • Loading branch information
ebadiere committed Jul 25, 2023
2 parents a334f7f + ae7636a commit 31dc751
Show file tree
Hide file tree
Showing 18 changed files with 1,888 additions and 1,740 deletions.
1 change: 0 additions & 1 deletion dapp-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"dependencies": {
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.11.0",
"@hashgraph/hethers": "^1.2.6",
"@hashgraph/sdk": "^2.29.0",
"@mui/material": "^5.13.6",
"ethers": "^5.6.8",
Expand Down
23 changes: 20 additions & 3 deletions dapp-example/tests/e2e/bootstrap.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
const HederaSDK = require('@hashgraph/sdk');
const ethers = require('ethers');
const hethers = require('@hashgraph/hethers');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const IHRC = require("../../src/contracts/IHRC.json");

const randomUppercaseString = (length = 5) => {
let result = '';
Expand All @@ -18,6 +16,24 @@ const randomUppercaseString = (length = 5) => {
return result;
};

const idToEvmAddress = (id) => {
try {
const [shard, realm, num] = id.split('.');
return [
'0x',
toHex(shard).padStart(8, '0'),
toHex(realm).padStart(16, '0'),
toHex(num).padStart(16, '0')
].join('');
} catch(e) {
throw new Error(`Can not transform id ${id} to evm address`);
}
};

const toHex = (num) => {
return parseInt(num).toString(16);
};

const supportedEnvs = ['previewnet', 'testnet', 'mainnet'];

let client;
Expand Down Expand Up @@ -69,7 +85,7 @@ const createHTSToken = async function() {

const receipt = await tokenCreate.getReceipt(client);
const tokenId = receipt.tokenId.toString();
const tokenAddress = hethers.utils.getAddressFromAccount(tokenId);
const tokenAddress = idToEvmAddress(tokenId);

console.log(`HTS Token Deployed at: ${tokenAddress} with id ${tokenId}`);

Expand Down Expand Up @@ -138,6 +154,7 @@ const deployAndFundContractTransferTx = async function(wallet) {
return contractAddress;
};


(async () => {
let mainPrivateKeyString = process.env.PRIVATE_KEY;
if (mainPrivateKeyString === '') {
Expand Down
2 changes: 2 additions & 0 deletions package-lock.json

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

14 changes: 7 additions & 7 deletions packages/relay/src/lib/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ export class EthImpl implements Eth {
private async getFeeWeibars(callerName: string, requestIdPrefix?: string, timestamp?: string) {
let networkFees;
try {
networkFees = await this.mirrorNodeClient.getNetworkFees(timestamp,undefined, requestIdPrefix);
networkFees = await this.mirrorNodeClient.getNetworkFees(timestamp, undefined, requestIdPrefix);
if (_.isNil(networkFees)) {
this.logger.debug(`${requestIdPrefix} Mirror Node returned no fees. Fallback to network`);
}
Expand Down Expand Up @@ -1106,7 +1106,7 @@ export class EthImpl implements Eth {
let interactingEntity = '';
let originatingAddress = '';
try {
let parsedTx = Precheck.parseTxIfNeeded(transaction);
const parsedTx = Precheck.parseTxIfNeeded(transaction);
interactingEntity = parsedTx.to?.toString() || '';
originatingAddress = parsedTx.from?.toString() || '';
this.logger.trace(`${requestIdPrefix} sendRawTransaction(from=${originatingAddress}, to=${interactingEntity}, transaction=${transaction})`);
Expand Down Expand Up @@ -1469,7 +1469,7 @@ export class EthImpl implements Eth {
this.logger.trace(`${requestIdPrefix} getTransactionReceipt(${hash})`);

const cacheKey = `${constants.CACHE_KEY.ETH_GET_TRANSACTION_RECEIPT}_${hash}`;
let cachedResponse = this.cache.get(cacheKey, EthImpl.ethGetTransactionReceipt, requestIdPrefix);
const cachedResponse = this.cache.get(cacheKey, EthImpl.ethGetTransactionReceipt, requestIdPrefix);
if (cachedResponse) {
this.logger.debug(`${requestIdPrefix} getTransactionReceipt returned cached response: ${cachedResponse}`);
return cachedResponse;
Expand Down Expand Up @@ -1498,7 +1498,7 @@ export class EthImpl implements Eth {
this.logger.debug(`${requestIdPrefix} getTransactionReceipt returned cached synthetic receipt response: ${cachedResponse}`);
this.cache.set(cacheKey, receipt, EthImpl.ethGetTransactionReceipt, constants.CACHE_TTL.ONE_DAY, requestIdPrefix);

return receipt
return receipt;
}

const receiptResponse = await this.mirrorNodeClient.getContractResultWithRetry(hash, requestIdPrefix);
Expand Down Expand Up @@ -1564,7 +1564,7 @@ export class EthImpl implements Eth {
return input.startsWith(EthImpl.emptyHex) ? input : EthImpl.emptyHex + input;
}

static numberTo0x(input: number | BigNumber | BigInt): string {
static numberTo0x(input: number | BigNumber | bigint): string {
return EthImpl.emptyHex + input.toString(16);
}

Expand Down Expand Up @@ -1648,7 +1648,7 @@ export class EthImpl implements Eth {

// Gas limit for `eth_call` is 50_000_000, but the current Hedera network limit is 15_000_000
// With values over the gas limit, the call will fail with BUSY error so we cap it at 15_000_000
let gas = Number.parseInt(gasString);
const gas = Number.parseInt(gasString);
if (gas > constants.BLOCK_GAS_LIMIT) {
this.logger.trace(`${requestIdPrefix} eth_call gas amount (${gas}) exceeds network limit, capping gas to ${constants.BLOCK_GAS_LIMIT}`);
return constants.BLOCK_GAS_LIMIT;
Expand Down Expand Up @@ -1678,7 +1678,7 @@ export class EthImpl implements Eth {
const params = { timestamp: timestampRangeParams };

// get contract results logs using block timestamp range
const logs = await this.getLogsWithParams(null, params, requestIdPrefix)
const logs = await this.getLogsWithParams(null, params, requestIdPrefix);

if (contractResults == null && logs.length == 0) {
// contract result not found
Expand Down
129 changes: 129 additions & 0 deletions packages/relay/tests/assertions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@

import { expect } from 'chai';
import { JsonRpcError } from '../src';
import { EthImpl } from "../src/lib/eth";
import { Block, Transaction} from "../src/lib/model";

export default class RelayAssertions {
static assertRejection = async (error: JsonRpcError, method, checkMessage: boolean, thisObj, args?: any[]): Promise<any> => {
return await expect(method.apply(thisObj, args)).to.eventually.be.rejected.and.satisfy((err) => {
if(!checkMessage) {
return err.code === error.code && err.name === error.name;
}
return err.code === error.code && err.name === error.name && err.message === error.message;
});
};

static assertTransactionReceipt = (receipt, expectedReceipt) => {
expect(receipt).to.exist;
if (receipt == null) return;

expect(this.validateHash(receipt.transactionHash, 64)).to.eq(true);
expect(this.validateHash(receipt.blockHash, 64)).to.eq(true);
expect(this.validateHash(receipt.from, 40)).to.eq(true);
if (receipt.contractAddress) {
expect(this.validateHash(receipt.contractAddress, 40)).to.eq(true);
}
if (receipt.to) {
expect(this.validateHash(receipt.to, 40)).to.eq(true);
}
expect(this.validateHash(receipt.logsBloom, 512)).to.eq(true);
if (receipt.root) {
expect(this.validateHash(receipt.root, 64)).to.eq(true);
}

expect(receipt.transactionHash).to.exist;
expect(receipt.transactionHash).to.eq(expectedReceipt.transactionHash);
expect(receipt.transactionIndex).to.exist;
expect(receipt.blockHash).to.eq(expectedReceipt.blockHash);
expect(receipt.blockNumber).to.eq(expectedReceipt.blockNumber);
expect(receipt.from).to.eq(expectedReceipt.from);
expect(receipt.to).to.eq(expectedReceipt.to);
expect(receipt.cumulativeGasUsed).to.eq(expectedReceipt.cumulativeGasUsed);
expect(receipt.gasUsed).to.eq(expectedReceipt.gasUsed);
expect(receipt.contractAddress).to.eq(expectedReceipt.contractAddress);
expect(receipt.logs).to.deep.eq(expectedReceipt.logs);
expect(receipt.logsBloom).to.eq(expectedReceipt.logsBloom);
expect(receipt.root).to.eq(expectedReceipt.root);
expect(receipt.status).to.eq(expectedReceipt.status);
expect(receipt.effectiveGasPrice).to.eq(expectedReceipt.effectiveGasPrice);
};

static assertTransaction = (tx, expectedTx) => {

expect(tx).to.exist;
if (tx == null) return;

expect(tx.accessList).to.eq(expectedTx.accessList);
expect(tx.blockHash).to.eq(expectedTx.blockHash);
expect(tx.blockNumber).to.eq(expectedTx.blockNumber);
expect(tx.chainId).to.eq(expectedTx.chainId);
expect(tx.from).to.eq(expectedTx.from);
expect(tx.gas).to.eq(expectedTx.gas);
expect(tx.gasPrice).to.eq(expectedTx.gasPrice);
expect(tx.hash).to.eq(expectedTx.hash);
expect(tx.input).to.eq(expectedTx.input);
expect(tx.maxFeePerGas).to.eq(expectedTx.maxFeePerGas);
expect(tx.maxPriorityFeePerGas).to.eq(expectedTx.maxPriorityFeePerGas);
expect(tx.nonce).to.eq(EthImpl.numberTo0x(expectedTx.nonce));
expect(tx.r).to.eq(expectedTx.r);
expect(tx.s).to.eq(expectedTx.s);
expect(tx.to).to.eq(expectedTx.to);
expect(tx.transactionIndex).to.eq(expectedTx.transactionIndex);
expect(tx.type).to.eq(EthImpl.numberTo0x(expectedTx.type));
expect(tx.v).to.eq(EthImpl.numberTo0x(expectedTx.v));
expect(tx.value).to.eq(expectedTx.value);
};

static assertBlock = (block, expectedBlock, txDetails = false) => {
expect(block).to.exist;
expect(block).to.not.be.null;

// verify aggregated info
expect(block.hash).equal(expectedBlock.hash);
expect(block.gasUsed).equal(expectedBlock.gasUsed);
expect(block.number).equal(expectedBlock.number);
expect(block.parentHash).equal(expectedBlock.parentHash);
expect(block.timestamp).equal(expectedBlock.timestamp);
expect(block.transactions.length).equal(expectedBlock.transactions.length);
for (let i = 0; i < expectedBlock.transactions.length; i++) {
if (!txDetails) {
expect(block.transactions[i] as string).equal(expectedBlock.transactions[i]);
}
else {
expect((block.transactions[i] as Transaction).hash).equal(expectedBlock.transactions[i]);
}
}

// verify expected constants
this.verifyBlockConstants(block);
};

static validateHash = (hash: string, len?: number) => {
let regex;
if (len && len > 0) {
regex = new RegExp(`^0x[a-f0-9]{${len}}$`);
} else {
regex = /^0x[a-f0-9]*$/;
}

return !!regex.exec(hash);
};


static verifyBlockConstants = (block: Block) => {
expect(block.gasLimit).equal(EthImpl.numberTo0x(15000000));
expect(block.baseFeePerGas).equal('0x84b6a5c400');
expect(block.difficulty).equal(EthImpl.zeroHex);
expect(block.extraData).equal(EthImpl.emptyHex);
expect(block.miner).equal(EthImpl.zeroAddressHex);
expect(block.mixHash).equal(EthImpl.zeroHex32Byte);
expect(block.nonce).equal(EthImpl.zeroHex8Byte);
expect(block.receiptsRoot).equal(EthImpl.zeroHex32Byte);
expect(block.sha3Uncles).equal(EthImpl.emptyArrayHex);
expect(block.stateRoot).equal(EthImpl.zeroHex32Byte);
expect(block.totalDifficulty).equal(EthImpl.zeroHex);
expect(block.uncles).to.deep.equal([]);
};
}

Loading

0 comments on commit 31dc751

Please sign in to comment.