Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

Commit

Permalink
Now handling accountinfo via default parser that Hedera SDK gives us
Browse files Browse the repository at this point in the history
  • Loading branch information
kpachhai committed Sep 25, 2023
1 parent f28acf4 commit ed09a0e
Show file tree
Hide file tree
Showing 10 changed files with 121 additions and 78 deletions.
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/tuum-tech/hedera-pulse.git"
},
"source": {
"shasum": "4HzdG2v/QPI7U/K81PfXpwj1SYIs6caC/g7U0mOwods=",
"shasum": "3Z/5TE7OM8ZF3m4WVbq+Byn/sl+KPlBhL7+4vYktYlQ=",
"location": {
"npm": {
"filePath": "dist/snap.js",
Expand Down
3 changes: 3 additions & 0 deletions packages/snap/src/rpc/account/getAccountBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export async function getAccountBalance(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.accountState[metamaskAddress].accountInfo.balance!.hbars =
await hederaClient.getAccountBalance();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.accountState[metamaskAddress].accountInfo.balance!.timestamp =
new Date().toISOString();
await updateSnapState(snap, state);
} catch (error: any) {
console.error(
Expand Down
23 changes: 11 additions & 12 deletions packages/snap/src/rpc/account/getAccountInfo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AccountInfoJson } from '@hashgraph/sdk/lib/account/AccountInfo';
import _ from 'lodash';
import { HederaAccountInfo } from 'src/services/hedera';
import { createHederaClient } from '../../snap/account';
import { updateSnapState } from '../../snap/state';
import { PulseSnapParams } from '../../types/state';
Expand All @@ -14,12 +14,12 @@ import { PulseSnapParams } from '../../types/state';
export async function getAccountInfo(
pulseSnapParams: PulseSnapParams,
accountId?: string,
): Promise<any> {
): Promise<AccountInfoJson> {
const { state } = pulseSnapParams;

const { metamaskAddress, hederaAccountId, network } = state.currentAccount;

let accountInfo = {};
let accountInfo = {} as AccountInfoJson;

try {
const hederaClient = await createHederaClient(
Expand All @@ -28,23 +28,22 @@ export async function getAccountInfo(
network,
);

let response: HederaAccountInfo;
if (accountId && !_.isEmpty(accountId)) {
response = await hederaClient.getAccountInfo(accountId);
accountInfo = await hederaClient.getAccountInfo(accountId);
} else {
response = await hederaClient.getAccountInfo(hederaAccountId);
accountInfo = await hederaClient.getAccountInfo(hederaAccountId);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.accountState[metamaskAddress].accountInfo.balance!.hbars = Number(
response.balance.toString().replace(' ℏ', ''),
accountInfo.balance.toString().replace(' ℏ', ''),
);

// Let's massage the info we want rather than spitting out everything
state.accountState[metamaskAddress].accountInfo.extraData = JSON.parse(
JSON.stringify(response),
);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.accountState[metamaskAddress].accountInfo.balance!.timestamp =
new Date().toISOString();

state.accountState[metamaskAddress].accountInfo.extraData = accountInfo;
await updateSnapState(snap, state);
}
accountInfo = JSON.parse(JSON.stringify(response));
} catch (error: any) {
console.error(`Error while trying to get account info: ${String(error)}`);
throw new Error(`Error while trying to get account info: ${String(error)}`);
Expand Down
91 changes: 44 additions & 47 deletions packages/snap/src/services/hedera.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
import type {
AccountId,
CustomFee,
Hbar,
HbarAllowance,
Key,
LedgerId,
LiveHash,
PrivateKey,
PublicKey,
Timestamp,
TokenAllowance,
TokenNftAllowance,
} from '@hashgraph/sdk';
import TokenRelationshipMap from '@hashgraph/sdk/lib/account/TokenRelationshipMap';
import Duration from '@hashgraph/sdk/lib/Duration';
import { Long } from '@hashgraph/sdk/lib/long';
import StakingInfo from '@hashgraph/sdk/lib/StakingInfo';
import { BigNumber } from 'bignumber.js';

import { AccountInfoJson } from '@hashgraph/sdk/lib/account/AccountInfo';
import { Wallet } from '../domain/wallet/abstract';

export type SimpleTransfer = {
Expand All @@ -36,6 +28,7 @@ export type Token = {
export type AccountBalance = {
// balance here in hbars
hbars: number;
timestamp: string;
tokens: Map<string, TokenBalance>; // Map of TOKEN -> decimals
};

Expand All @@ -45,19 +38,45 @@ export type TokenBalance = {
decimals: number;
};

export type TxTransfer = {
export type TxRecordTransfer = {
accountId: string;
amount: string;
isApproved: boolean;
};

export type TxReceiptExchangeRate = {
hbars: number;
cents: number;
expirationTime: string;
exchangeRateInCents: number;
};

export type TxReceipt = {
status: string;
accountId: string;
fileId: string;
contractId: string;
topicId: string;
tokenId: string;
scheduleId: string;
exchangeRate: TxReceiptExchangeRate;
topicSequenceNumber: string;
topicRunningHash: string;
totalSupply: string;
scheduledTransactionId: string;
serials: object;
duplicates: object;
children: object;
};

export type TxRecord = {
receipt: object;
transactionHash: string;
consensusTimestamp: string;
transactionId: string;
transactionMemo: string;
transactionFee: string;
transfers: TxTransfer[];
transfers: TxRecordTransfer[];
contractFunctionResult: object | null;
tokenTransfers: object;
tokenTransfersList: object;
Expand All @@ -67,10 +86,12 @@ export type TxRecord = {
automaticTokenAssociations: object;
parentConsensusTimestamp: string;
aliasKey: string;
duplicates: object;
children: object;
ethereumHash: string;
paidStakingRewards: TxTransfer[];
paidStakingRewards: TxRecordTransfer[];
prngBytes: string;
prngNumber: string | null;
prngNumber: string;
evmAddress: string;
};

Expand All @@ -85,7 +106,7 @@ export type HederaService = {
accountId: AccountId;
}): Promise<SimpleHederaClient | null>;

getNodeStakingInfo(): Promise<NetworkNodeStakingInfo[]>;
getNodeStakingInfo(): Promise<MirrorStakingInfo[]>;

getMirrorAccountInfo(
idOrAliasOrEvmAddress: string,
Expand All @@ -104,7 +125,7 @@ export type SimpleHederaClient = {
// get the associated account ID
getAccountId(): AccountId;

getAccountInfo(accountId: string): Promise<HederaAccountInfo>;
getAccountInfo(accountId: string): Promise<AccountInfoJson>;

// returns the account balance in HBARs
getAccountBalance(): Promise<number>;
Expand All @@ -118,7 +139,7 @@ export type SimpleHederaClient = {
}): Promise<TxRecord>;
};

export type NetworkNodeStakingInfo = {
export type MirrorStakingInfo = {
description: string;
node_id: number;
node_account_id: string;
Expand All @@ -141,15 +162,15 @@ export type MirrorAccountInfo = {
auto_renew_period: Long;
balance: {
balance: number;
timestamp: Timestamp;
timestamp: string;
tokens: [];
};
created_timestamp: Timestamp;
created_timestamp: string;
decline_reward: boolean;
deleted: boolean;
ethereum_nonce: Long;
evm_address: string;
expiry_timestamp: Timestamp;
expiry_timestamp: string;
key: {
_type: string;
key: string;
Expand All @@ -162,6 +183,9 @@ export type MirrorAccountInfo = {
staked_node_id?: number;
stake_period_start?: number;
transactions: [];
links: {
next: string;
};
};

export type MirrorTokenInfo = {
Expand All @@ -172,7 +196,7 @@ export type MirrorTokenInfo = {
custom_fees: CustomFee;
decimals: string;
deleted: boolean;
expiry_timestamp: BigNumber;
expiry_timestamp: string;
fee_schedule_key: Key;
freeze_default: boolean;
initial_supply: string;
Expand All @@ -190,30 +214,3 @@ export type MirrorTokenInfo = {
type: string;
wipe_key: Key;
};

export type HederaAccountInfo = {
accountId: AccountId;
contractAccountId?: string;
isDeleted: boolean;
proxyAccountId?: object;
proxyReceived: Hbar;
key: Key;
balance: Hbar;
sendRecordThreshold: Hbar;
receiveRecordThreshold: Hbar;
isReceiverSignatureRequired: boolean;
expirationTime: Timestamp;
autoRenewPeriod: Duration;
liveHashes: LiveHash[];
tokenRelationships: TokenRelationshipMap;
accountMemo: string;
ownedNfts: Long;
maxAutomaticTokenAssociations: Long;
aliasKey: PublicKey;
ledgerId: LedgerId;
hbarAllowances: HbarAllowance[];
tokenAllowances: TokenAllowance[];
nftAllowances: TokenNftAllowance[];
ethereumNonce?: Long;
stakingInfo?: StakingInfo;
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { AccountInfo, AccountInfoQuery, type Client } from '@hashgraph/sdk';

import { HederaAccountInfo } from '../../../hedera';
import { AccountInfoJson } from '@hashgraph/sdk/lib/account/AccountInfo';

/**
* Retrieve the account info.
Expand All @@ -11,12 +10,12 @@ import { HederaAccountInfo } from '../../../hedera';
export async function getAccountInfo(
client: Client,
accountId: string,
): Promise<HederaAccountInfo> {
): Promise<AccountInfoJson> {
// Create the account info query
const query = new AccountInfoQuery().setAccountId(accountId);

// Sign with client operator private key and submit the query to a Hedera network
const accountInfo: AccountInfo = await query.execute(client);

return accountInfo as unknown as HederaAccountInfo;
return accountInfo.toJSON();
}
4 changes: 2 additions & 2 deletions packages/snap/src/services/impl/hedera/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import {
type PublicKey,
} from '@hashgraph/sdk';

import { AccountInfoJson } from '@hashgraph/sdk/lib/account/AccountInfo';
import {
AccountBalance,
HederaAccountInfo,
SimpleHederaClient,
SimpleTransfer,
TxRecord,
Expand Down Expand Up @@ -42,7 +42,7 @@ export class SimpleHederaClientImpl implements SimpleHederaClient {
return this._client.operatorAccountId!;
}

async getAccountInfo(accountId: string): Promise<HederaAccountInfo> {
async getAccountInfo(accountId: string): Promise<AccountInfoJson> {
return getAccountInfo(this._client, accountId);
}

Expand Down
43 changes: 37 additions & 6 deletions packages/snap/src/services/impl/hedera/client/transferCrypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import {
AccountBalance,
SimpleTransfer,
TokenBalance,
TxReceipt,
TxReceiptExchangeRate,
TxRecord,
TxTransfer,
TxRecordTransfer,
} from '../../../hedera';

/**
Expand Down Expand Up @@ -85,8 +87,6 @@ export async function transferCrypto(

const record: TransactionRecord = await txResponse.getVerboseRecord(client);

console.log('record: ', JSON.stringify(record, null, 4));

const uint8ArrayToHex = (data: Uint8Array | null | undefined) => {
if (!data) {
return '';
Expand All @@ -97,20 +97,49 @@ export async function transferCrypto(
);
};

const transfers: TxTransfer[] = record.transfers.map((transfer) => ({
const transfers: TxRecordTransfer[] = record.transfers.map((transfer) => ({
accountId: transfer.accountId.toString(),
amount: transfer.amount.toString(),
isApproved: transfer.isApproved,
}));

const paidStakingRewards: TxTransfer[] = record.paidStakingRewards.map(
const paidStakingRewards: TxRecordTransfer[] = record.paidStakingRewards.map(
(reward) => ({
accountId: reward.accountId.toString(),
amount: reward.amount.toString(),
isApproved: reward.isApproved,
}),
);
return {
receipt: {
status: record.receipt.status.toString(),
accountId: record.receipt.accountId
? record.receipt.accountId.toString()
: '',
fileId: record.receipt.fileId ? record.receipt.fileId : '',
contractId: record.receipt.contractId ? record.receipt.contractId : '',
topicId: record.receipt.topicId ? record.receipt.topicId : '',
tokenId: record.receipt.tokenId ? record.receipt.tokenId : '',
scheduleId: record.receipt.scheduleId ? record.receipt.scheduleId : '',
exchangeRate: record.receipt.exchangeRate
? (JSON.parse(
JSON.stringify(record.receipt.exchangeRate),
) as TxReceiptExchangeRate)
: ({} as TxReceiptExchangeRate),
topicSequenceNumber: record.receipt.topicSequenceNumber
? String(record.receipt.topicSequenceNumber)
: '',
topicRunningHash: uint8ArrayToHex(record.receipt.topicRunningHash),
totalSupply: record.receipt.totalSupply
? String(record.receipt.totalSupply)
: '',
scheduledTransactionId: record.receipt.scheduledTransactionId
? record.receipt.scheduledTransactionId.toString()
: '',
serials: JSON.parse(JSON.stringify(record.receipt.serials)),
duplicates: JSON.parse(JSON.stringify(record.receipt.duplicates)),
children: JSON.parse(JSON.stringify(record.receipt.children)),
} as TxReceipt,
transactionHash: uint8ArrayToHex(record.transactionHash),
consensusTimestamp: record.consensusTimestamp.toDate().toISOString(),
transactionId: record.transactionId.toString(),
Expand All @@ -134,10 +163,12 @@ export async function transferCrypto(
? record.parentConsensusTimestamp.toDate().toISOString()
: '',
aliasKey: record.aliasKey ? record.aliasKey.toStringRaw() : '',
duplicates: JSON.parse(JSON.stringify(record.duplicates)),
children: JSON.parse(JSON.stringify(record.children)),
ethereumHash: uint8ArrayToHex(record.ethereumHash),
paidStakingRewards,
prngBytes: uint8ArrayToHex(record.prngBytes),
prngNumber: record.prngNumber,
prngNumber: record.prngNumber ? record.prngNumber.toString() : '',
evmAddress: uint8ArrayToHex(record.evmAddress?.toBytes()),
} as TxRecord;
}
Loading

0 comments on commit ed09a0e

Please sign in to comment.