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 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
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
19 changes: 15 additions & 4 deletions packages/relay/src/lib/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ export class EthImpl implements Eth {
static defaultGasUsedRatio = EthImpl.numberTo0x(0.5);
static feeHistoryZeroBlockCountResponse = { gasUsedRatio: null, oldestBlock: EthImpl.zeroHex };
static feeHistoryEmptyResponse = { baseFeePerGas: [], gasUsedRatio: [], reward: [], oldestBlock: EthImpl.zeroHex };
static redirectBytecodePrefix = '6080604052348015600f57600080fd5b506000610167905077618dc65e';
static redirectBytecodePostfix = '600052366000602037600080366018016008845af43d806000803e8160008114605857816000f35b816000fdfea2646970667358221220d8378feed472ba49a0005514ef7087017f707b45fb9bf56bb81bb93ff19a238b64736f6c634300080b0033';


// endpoint metric callerNames
static ethCall = 'eth_call';
Expand Down Expand Up @@ -580,11 +583,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 +1017,10 @@ export class EthImpl implements Eth {
return value === EthImpl.emptyHex ? null : value;
}

private static redirectBytecodeAddressReplace(address: string): string {
return `${this.redirectBytecodePrefix}${address.slice(2)}${this.redirectBytecodePostfix}`;
}

/**
* Internal helper method that removes the leading 0x if there is one.
* @param input
Expand Down
70 changes: 70 additions & 0 deletions packages/relay/tests/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,76 @@ const mockData = {
}
},

tokenId: '0.0.13312',
token: {
"admin_key": {
"_type": "ProtobufEncoded",
"key": 10101
},
"auto_renew_account": "0.1.2",
"auto_renew_period": null,
"created_timestamp": "1234567890.000000001",
"deleted": false,
"decimals": 1000,
"expiry_timestamp": null,
"freeze_default": false,
"freeze_key": {
"_type": "ProtobufEncoded",
"key": 10101
},
"initial_supply": 1000000,
"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.13312",
"total_supply": 1000000,
"treasury_account_id": "0.1.2",
"type": "FUNGIBLE_COMMON",
"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.8"
}
],
"fractional_fees": [
{
"amount": {
"numerator": 12,
"denominator": 29
},
"collector_account_id": "0.1.6",
"denominating_token_id": "0.10.9",
"maximum": 120,
"minimum": 30,
"net_of_transfers": true
}
]
}
},

notFound: {
"_status": {
"messages": [
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
35 changes: 34 additions & 1 deletion packages/relay/tests/lib/mirrorNodeClient.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,22 @@ describe('MirrorNodeClient', async function () {
expect(result).to.be.null;
});

it('`getTokenById`', async () => {
mock.onGet(`tokens/${mockData.tokenId}`).reply(200, mockData.token);

const result = await mirrorNodeInstance.getTokenById(mockData.tokenId);
expect(result).to.exist;
expect(result.token_id).equal('0.0.13312');
});

it('`getTokenById` not found', async () => {
const tokenId = '0.0.132';
mock.onGet(`accounts/${tokenId}`).reply(404, mockData.notFound);

const result = await mirrorNodeInstance.getTokenById(tokenId);
expect(result).to.be.null;
});

const detailedContractResult = {
'access_list': '0x',
'amount': 2000000000,
Expand Down Expand Up @@ -532,6 +548,7 @@ describe('MirrorNodeClient', async function () {
it('returns `contract` when CONTRACTS endpoint returns a result', async() => {
mock.onGet(`contracts/${mockData.contractEvmAddress}`).reply(200, mockData.contract);
mock.onGet(`accounts/${mockData.contractEvmAddress}`).reply(200, mockData.account);
mock.onGet(`tokens/${mockData.tokenId}`).reply(404, mockData.notFound);

const entityType = await mirrorNodeInstance.resolveEntityType(mockData.contractEvmAddress);
expect(entityType).to.exist;
Expand All @@ -542,9 +559,10 @@ describe('MirrorNodeClient', async function () {
expect(entityType.entity.contract_id).to.eq(mockData.contract.contract_id);
});

it('returns `account` when CONTRACTS endpoint returns 404 and ACCOUNTS endpoint returns a result', async() => {
it('returns `account` when CONTRACTS and TOKENS endpoint returns 404 and ACCOUNTS endpoint returns a result', async() => {
mock.onGet(`contracts/${mockData.contractEvmAddress}`).reply(404, mockData.notFound);
mock.onGet(`accounts/${mockData.contractEvmAddress}`).reply(200, mockData.account);
mock.onGet(`tokens/${mockData.tokenId}`).reply(404, mockData.notFound);

const entityType = await mirrorNodeInstance.resolveEntityType(mockData.contractEvmAddress);
expect(entityType).to.exist;
Expand All @@ -555,9 +573,24 @@ describe('MirrorNodeClient', async function () {
expect(entityType.entity.account).to.eq(mockData.account.account);
});

it('returns `token` when CONTRACTS and ACCOUNTS endpoints returns 404 and TOKEN endpoint returns a result', async() => {
mock.onGet(`contracts/${mockData.contractEvmAddress}`).reply(404, mockData.notFound);
mock.onGet(`accounts/${mockData.contractEvmAddress}`).reply(404, mockData.notFound);
mock.onGet(`tokens/${mockData.tokenId}`).reply(200, mockData.token);

const entityType = await mirrorNodeInstance.resolveEntityType(mockData.tokenId);
expect(entityType).to.exist;
expect(entityType).to.have.property('type');
expect(entityType).to.have.property('entity');
expect(entityType.type).to.eq('token');
expect(entityType.entity).to.have.property('token');
expect(entityType.entity.token_id).to.eq(mockData.tokenId);
});

it('returns null when CONTRACTS and ACCOUNTS endpoints return 404', async() => {
mock.onGet(`contracts/${mockData.contractEvmAddress}`).reply(404, mockData.notFound);
mock.onGet(`accounts/${mockData.contractEvmAddress}`).reply(404, mockData.notFound);
mock.onGet(`tokens/${mockData.tokenId}`).reply(404, mockData.notFound);

const entityType = await mirrorNodeInstance.resolveEntityType(mockData.contractEvmAddress);
expect(entityType).to.be.null;
Expand Down
Loading