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

eth_getCode to return the redirect bytecode for HTS tokens #598

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
15 changes: 15 additions & 0 deletions packages/relay/src/lib/clients/mirrorNodeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export class MirrorNodeClient {
private static GET_CONTRACT_RESULTS_ENDPOINT = 'contracts/results';
private static GET_NETWORK_EXCHANGERATE_ENDPOINT = 'network/exchangerate';
private static GET_NETWORK_FEES_ENDPOINT = 'network/fees';
private static GET_TOKENS_ENDPOINT = 'tokens';

private static ORDER = {
ASC: 'asc',
Expand Down Expand Up @@ -356,6 +357,13 @@ export class MirrorNodeClient {
.replace(MirrorNodeClient.TIMESTAMP_PLACEHOLDER, timestamp);
}

public async getTokenById(tokenId: string, requestId?: string) {
Nana-EC marked this conversation as resolved.
Show resolved Hide resolved
return this.request(`${MirrorNodeClient.GET_TOKENS_ENDPOINT}/${tokenId}`,
MirrorNodeClient.GET_TOKENS_ENDPOINT,
[400, 404],
requestId);
}

public async getLatestContractResultsByAddress(address: string, blockEndTimestamp: string | undefined, limit: number) {
// retrieve the timestamp of the contract
const contractResultsParams: IContractResultsParams = blockEndTimestamp
Expand Down Expand Up @@ -418,6 +426,13 @@ export class MirrorNodeClient {
entity: accountResult
};
}
const tokenResult = await this.getTokenById(`0.0.${parseInt(entityIdentifier, 16)}`, requestId);
Nana-EC marked this conversation as resolved.
Show resolved Hide resolved
if (tokenResult) {
return {
type: constants.TYPE_TOKEN,
entity: tokenResult
}
}

return null;
}
Expand Down
1 change: 1 addition & 0 deletions packages/relay/src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export default {

TYPE_CONTRACT: 'contract',
TYPE_ACCOUNT: 'account',
TYPE_TOKEN: 'token',

DEFAULT_FEE_HISTORY_MAX_RESULTS: 10,
ORDER,
Expand Down
16 changes: 12 additions & 4 deletions packages/relay/src/lib/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -580,11 +580,15 @@ export class EthImpl implements Eth {
}

try {
const contract = await this.mirrorNodeClient.getContract(address, requestId);
if (contract && contract.runtime_bytecode && contract.runtime_bytecode !== EthImpl.emptyHex) {
return contract.runtime_bytecode;
const result = await this.mirrorNodeClient.resolveEntityType(address, requestId);

if (result && result?.type === constants.TYPE_TOKEN) {
return EthImpl.redirectBytecodeAddressReplace(address);
}
else {
else if (result && result?.type === constants.TYPE_CONTRACT && result?.entity.runtime_bytecode !== EthImpl.emptyHex) {
return result?.entity.runtime_bytecode;
}
else{
const bytecode = await this.sdkClient.getContractByteCode(0, 0, address, EthImpl.ethGetCode, requestId);
return EthImpl.prepend0x(Buffer.from(bytecode).toString('hex'));
}
Expand Down Expand Up @@ -1010,6 +1014,10 @@ export class EthImpl implements Eth {
return value === EthImpl.emptyHex ? null : value;
}

private static redirectBytecodeAddressReplace(address: string): string {
return `6080604052348015600f57600080fd5b506000610167905077618dc65e${address.slice(2)}600052366000602037600080366018016008845af43d806000803e8160008114605857816000f35b816000fdfea2646970667358221220d8378feed472ba49a0005514ef7087017f707b45fb9bf56bb81bb93ff19a238b64736f6c634300080b0033`
Nana-EC marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Internal helper method that removes the leading 0x if there is one.
* @param input
Expand Down
85 changes: 85 additions & 0 deletions packages/relay/tests/lib/eth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ describe('Eth calls using MirrorNode', async function () {
const blockTimestampHex = EthImpl.numberTo0x(Number(blockTimestamp));
const firstTransactionTimestampSeconds = '1653077547';
const contractAddress1 = '0x000000000000000000000000000000000000055f';
const htsTokenAddress = '0x0000000000000000000000000000000002dca431';
const contractTimestamp1 = `${firstTransactionTimestampSeconds}.983983199`;
const contractHash1 = '0x4a563af33c4871b51a8b108aa2fe1dd5280a30dfb7236170ae5e5e7957eb6392';
const contractHash2 = '0x4a563af33c4871b51a8b108aa2fe1dd5280a30dfb7236170ae5e5e7957eb6393';
Expand Down Expand Up @@ -417,6 +418,73 @@ describe('Eth calls using MirrorNode', async function () {
"runtime_bytecode": mirrorNodeDeployedBytecode
};

const defaultHTSToken =
{
"admin_key": null,
"auto_renew_account": "0.1.2",
"auto_renew_period": null,
"created_timestamp": "1234567890.000000001",
"deleted": false,
"decimals": 0,
"expiry_timestamp": null,
"freeze_default": false,
"freeze_key": {
"_type": "ProtobufEncoded",
"key": 10101
},
"initial_supply": 0,
"kyc_key": {
"_type": "ProtobufEncoded",
"key": 10101
},
"max_supply": 9223372036854776000,
"memo": "token memo",
"modified_timestamp": "1234567890.000000001",
"name": "Token name",
"pause_key": {
"_type": "ProtobufEncoded",
"key": 10101
},
"pause_status": "UNPAUSED",
"supply_key": {
"_type": "ProtobufEncoded",
"key": 10101
},
"supply_type": "INFINITE",
"symbol": "ORIGINALRDKSE",
"token_id": "0.0.48014385",
"total_supply": 1000000,
"treasury_account_id": "0.1.2",
"type": "NON_FUNGIBLE_UNIQUE",
"wipe_key": {
"_type": "ProtobufEncoded",
"key": 10101
},
"custom_fees": {
"created_timestamp": "1234567890.000000001",
"fixed_fees": [
{
"amount": 100,
"collector_account_id": "0.1.5",
"denominating_token_id": "0.10.6"
}
],
"royalty_fees": [
{
"amount": {
"numerator": 15,
"denominator": 37
},
"collector_account_id": "0.1.6",
"fallback_fee": {
"amount": 100,
"denominating_token_id": "0.10.7"
}
}
]
}
}


this.afterEach(() => {
mock.resetHandlers();
Expand Down Expand Up @@ -1141,6 +1209,8 @@ describe('Eth calls using MirrorNode', async function () {
describe('eth_getCode', async function() {
it('should return cached value', async () => {
mock.onGet(`contracts/${contractAddress1}`).reply(404, defaultContract);
mock.onGet(`accounts/${contractAddress1}`).reply(404, null);
mock.onGet(`tokens/0.0.${parseInt(contractAddress1, 16)}`).reply(404, null);
sdkClientStub.getContractByteCode.throws(new SDKClientError({status: {
_code: 16
}}));
Expand All @@ -1154,6 +1224,8 @@ describe('Eth calls using MirrorNode', async function () {

it('should return the runtime_bytecode from the mirror node', async () => {
mock.onGet(`contracts/${contractAddress1}`).reply(200, defaultContract);
mock.onGet(`accounts/${contractAddress1}`).reply(404, null);
mock.onGet(`tokens/0.0.${parseInt(contractAddress1, 16)}`).reply(404, null);
sdkClientStub.getContractByteCode.returns(Buffer.from(deployedBytecode.replace('0x', ''), 'hex'));

const res = await ethImpl.getCode(contractAddress1, null);
Expand All @@ -1162,6 +1234,8 @@ describe('Eth calls using MirrorNode', async function () {

it('should return the bytecode from SDK if Mirror Node returns 404', async () => {
mock.onGet(`contracts/${contractAddress1}`).reply(404, defaultContract);
mock.onGet(`accounts/${contractAddress1}`).reply(404, null);
mock.onGet(`tokens/0.0.${parseInt(contractAddress1, 16)}`).reply(404, null);
sdkClientStub.getContractByteCode.returns(Buffer.from(deployedBytecode.replace('0x', ''), 'hex'));
const res = await ethImpl.getCode(contractAddress1, null);
expect(res).to.equal(deployedBytecode);
Expand All @@ -1172,10 +1246,21 @@ describe('Eth calls using MirrorNode', async function () {
...defaultContract,
runtime_bytecode: EthImpl.emptyHex
});
mock.onGet(`accounts/${contractAddress1}`).reply(404, null);
mock.onGet(`tokens/0.0.${parseInt(contractAddress1, 16)}`).reply(404, null);
sdkClientStub.getContractByteCode.returns(Buffer.from(deployedBytecode.replace('0x', ''), 'hex'));
const res = await ethImpl.getCode(contractAddress1, null);
expect(res).to.equal(deployedBytecode);
});

it('should return redirect bytecode for HTS token', async () => {
mock.onGet(`contracts/${htsTokenAddress}`).reply(404, null);
mock.onGet(`accounts/${htsTokenAddress}`).reply(404, null);
mock.onGet(`tokens/0.0.${parseInt(htsTokenAddress, 16)}`).reply(200, defaultHTSToken);
const redirectBytecode = `6080604052348015600f57600080fd5b506000610167905077618dc65e${htsTokenAddress.slice(2)}600052366000602037600080366018016008845af43d806000803e8160008114605857816000f35b816000fdfea2646970667358221220d8378feed472ba49a0005514ef7087017f707b45fb9bf56bb81bb93ff19a238b64736f6c634300080b0033`;
const res = await ethImpl.getCode(htsTokenAddress, null);
expect(res).to.equal(redirectBytecode);
});
});

describe('eth_getLogs', async function () {
Expand Down
33 changes: 33 additions & 0 deletions packages/server/tests/acceptance/rpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { AliasAccount } from '../clients/servicesClient';
import Assertions from '../helpers/assertions';
import { Utils } from '../helpers/utils';
import { ContractFunctionParameters } from '@hashgraph/sdk';
import TokenCreateJson from '../contracts/TokenCreateContract.json';

// local resources
import parentContractJson from '../contracts/Parent.json';
Expand Down Expand Up @@ -77,6 +78,7 @@ describe('@api RPC Server Acceptance Tests', function () {
accounts[0] = await servicesNode.createAliasAccount(15);
accounts[1] = await servicesNode.createAliasAccount(15);
accounts[2] = await servicesNode.createAliasAccount(30);
accounts[3] = await servicesNode.createAliasAccount(60, relay.provider);
contractId = await accounts[0].client.createParentContract(parentContractJson);

const params = new ContractFunctionParameters().addUint256(1);
Expand Down Expand Up @@ -999,13 +1001,44 @@ describe('@api RPC Server Acceptance Tests', function () {
describe('eth_getCode', () => {

let basicContract;
let mainContractAddress: string;
let NftHTSTokenContractAddress: string;
let redirectBytecode: string;

async function deploymainContract() {
const mainFactory = new ethers.ContractFactory(TokenCreateJson.abi, TokenCreateJson.bytecode, accounts[3].wallet);
const mainContract = await mainFactory.deploy({gasLimit: 15000000});
const { contractAddress } = await mainContract.deployTransaction.wait();

return contractAddress;
}

async function createNftHTSToken() {
const mainContract = new ethers.Contract(mainContractAddress, TokenCreateJson.abi, accounts[3].wallet);
const tx = await mainContract.createNonFungibleTokenPublic(accounts[3].wallet.address, {
value: ethers.BigNumber.from('10000000000000000000'),
gasLimit: 10000000
});
const { tokenAddress } = (await tx.wait()).events.filter(e => e.event = 'CreatedToken')[0].args;

return tokenAddress;
}

before(async () => {
basicContract = await servicesNode.deployContract(basicContractJson);
mainContractAddress = await deploymainContract();
NftHTSTokenContractAddress = await createNftHTSToken();
// Wait for creation to propagate
await mirrorNode.get(`/contracts/${basicContract.contractId}`);
});

it('should execute "eth_getCode" for hts token', async function () {
const tokenAddress = NftHTSTokenContractAddress.slice(2);
redirectBytecode = `6080604052348015600f57600080fd5b506000610167905077618dc65e${tokenAddress}600052366000602037600080366018016008845af43d806000803e8160008114605857816000f35b816000fdfea2646970667358221220d8378feed472ba49a0005514ef7087017f707b45fb9bf56bb81bb93ff19a238b64736f6c634300080b0033`
const res = await relay.call('eth_getCode', [NftHTSTokenContractAddress]);
expect(res).to.equal(redirectBytecode);
});

it('@release should execute "eth_getCode" for contract evm_address', async function () {
const evmAddress = basicContract.contractId.toSolidityAddress();
const res = await relay.call('eth_getCode', [evmAddress]);
Expand Down