@transak/hedera-transak 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # hedera-transak
2
+ This repository contains the Hedera Transak integration.
@@ -0,0 +1,2 @@
1
+ import { Network } from './types';
2
+ export declare const networks: Record<string, Network>;
package/lib/config.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.networks = void 0;
4
+ exports.networks = {
5
+ main: {
6
+ transactionLink: hash => `https://hederaexplorer.io/search-details/transaction/${hash}`,
7
+ walletLink: address => `https://hederaexplorer.io/search-details/account/${address}`,
8
+ networkName: 'mainnet',
9
+ },
10
+ testnet: {
11
+ transactionLink: hash => `https://testnet.hederaexplorer.io/search-details/transaction/${hash}`,
12
+ walletLink: address => `https://testnet.hederaexplorer.io/search-details/account/${address}`,
13
+ networkName: 'testnet',
14
+ },
15
+ };
16
+ module.exports = { networks: exports.networks };
package/lib/index.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { GetTransactionResult, SendTransactionResult, SendTransactionParams } from './types';
2
+ /**
3
+ * Get the tokenAssociate transaction details by token id
4
+ * @param network
5
+ * @param privateKey
6
+ * @param accountId
7
+ * @param tokenId // tokenId
8
+ * @returns
9
+ */
10
+ declare function isTokenAssociated(network: string, privateKey: string, accountId: string, userAccountId: string, tokenId: string): Promise<boolean>;
11
+ /**
12
+ * Get the balance of the transak wallet address
13
+ * @param network
14
+ * @param decimals
15
+ * @param privateKey
16
+ * @param accountId
17
+ * @param tokenId // tokenId
18
+ * @returns
19
+ */
20
+ declare function getBalance(network: string, decimals: number, privateKey: string, accountId: string, tokenId?: string): Promise<number>;
21
+ /**
22
+ * Get the transaction details by transaction id
23
+ * @param txId
24
+ * @param network
25
+ * @param decimals
26
+ * @returns
27
+ */
28
+ declare function getTransaction(txnId: string, network: string, privateKey: string, accountId: string): Promise<GetTransactionResult | null>;
29
+ /**
30
+ * Send the transaction to the Hedera network
31
+ * @param param0
32
+ * @returns
33
+ */
34
+ declare function sendTransaction({ to, amount, network, accountId, privateKey, decimals, tokenId, }: SendTransactionParams): Promise<SendTransactionResult>;
35
+ declare const _default: {
36
+ getTransactionLink: (txId: string, network: string) => string;
37
+ getWalletLink: (walletAddress: string, network: string) => string;
38
+ getTransaction: typeof getTransaction;
39
+ isValidWalletAddress: (address: string) => boolean;
40
+ sendTransaction: typeof sendTransaction;
41
+ getBalance: typeof getBalance;
42
+ isTokenAssociated: typeof isTokenAssociated;
43
+ };
44
+ export = _default;
package/lib/index.js ADDED
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ const config_1 = require("./config");
12
+ const utils_1 = require("./utils");
13
+ const sdk_1 = require("@hashgraph/sdk");
14
+ const validWallet = /^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))(?:-([a-z]{5}))?$/;
15
+ /**
16
+ * Get the network config
17
+ * @param network
18
+ * @returns
19
+ */
20
+ const getNetwork = (network) => (network === 'main' ? config_1.networks[network] : config_1.networks.testnet);
21
+ /**
22
+ * Validate the wallet address
23
+ * @param address
24
+ * @returns
25
+ */
26
+ const isValidWalletAddress = (address) => new RegExp(validWallet).test(address);
27
+ /**
28
+ *
29
+ * @param txId
30
+ * @param network
31
+ * @returns
32
+ */
33
+ const getTransactionLink = (txId, network) => getNetwork(network).transactionLink(txId);
34
+ /**
35
+ * get wallet link for the given address
36
+ * @param walletAddress
37
+ * @param network
38
+ * @returns
39
+ */
40
+ const getWalletLink = (walletAddress, network) => getNetwork(network).walletLink(walletAddress);
41
+ /**
42
+ * create a client instance
43
+ * @param network
44
+ * @returns
45
+ */
46
+ function getClient(network, privateKey, accountId) {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ const config = getNetwork(network);
49
+ // If we weren't able to grab it, we should throw a new error
50
+ if (accountId == null || privateKey == null) {
51
+ throw new Error('variables privateKey and accountId must be present');
52
+ }
53
+ // Create our connection to the Hedera network
54
+ const client = sdk_1.Client.forName(config.networkName); // valid names mainnet, testnet ,previewnet
55
+ client.setOperator(accountId, privateKey);
56
+ return client;
57
+ });
58
+ }
59
+ /**
60
+ * Get the tokenAssociate transaction details by token id
61
+ * @param network
62
+ * @param privateKey
63
+ * @param accountId
64
+ * @param tokenId // tokenId
65
+ * @returns
66
+ */
67
+ function isTokenAssociated(network, privateKey, accountId, userAccountId, tokenId) {
68
+ var _a;
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ const client = yield getClient(network, privateKey, accountId);
71
+ const balance = yield new sdk_1.AccountBalanceQuery()
72
+ .setAccountId(userAccountId) // user's account id
73
+ .execute(client);
74
+ const token = (_a = balance.tokens) === null || _a === void 0 ? void 0 : _a.get(tokenId); // will return null if token is not associated
75
+ return !!token;
76
+ });
77
+ }
78
+ /**
79
+ * Get the balance of the transak wallet address
80
+ * @param network
81
+ * @param decimals
82
+ * @param privateKey
83
+ * @param accountId
84
+ * @param tokenId // tokenId
85
+ * @returns
86
+ */
87
+ function getBalance(network, decimals, privateKey, accountId, tokenId) {
88
+ var _a, _b;
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ const client = yield getClient(network, privateKey, accountId);
91
+ const balance = yield new sdk_1.AccountBalanceQuery()
92
+ .setAccountId(client.operatorAccountId.toString()) // transak's account id
93
+ .execute(client);
94
+ // if token id is present then return the token balance
95
+ if (tokenId) {
96
+ return Number((0, utils_1._toDecimal)(((_b = (_a = balance.tokens) === null || _a === void 0 ? void 0 : _a.get(tokenId)) === null || _b === void 0 ? void 0 : _b.toString()) || '0', decimals));
97
+ }
98
+ // else return the hbar balance
99
+ return Number((0, utils_1._toDecimal)(balance.hbars.toTinybars().toString(), decimals));
100
+ });
101
+ }
102
+ /**
103
+ * Get the transaction details by transaction id
104
+ * @param txId
105
+ * @param network
106
+ * @param decimals
107
+ * @returns
108
+ */
109
+ function getTransaction(txnId, network, privateKey, accountId) {
110
+ var _a, _b, _c;
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ const client = yield getClient(network, privateKey, accountId);
113
+ const TransactionRecord = yield new sdk_1.TransactionRecordQuery()
114
+ .setTransactionId(txnId)
115
+ .setIncludeDuplicates(true)
116
+ .execute(client);
117
+ const from = (_a = TransactionRecord.transactionId.accountId) === null || _a === void 0 ? void 0 : _a.toString();
118
+ return {
119
+ transactionData: TransactionRecord,
120
+ receipt: {
121
+ amount: Math.abs(((_b = TransactionRecord.transfers
122
+ .find(d => d.accountId.toString() === from)) === null || _b === void 0 ? void 0 : _b.amount.toTinybars().toNumber()) || 0),
123
+ date: TransactionRecord.consensusTimestamp.toDate(),
124
+ from: from || '',
125
+ gasCostCryptoCurrency: 'HBAR',
126
+ gasCostInCrypto: TransactionRecord.transactionFee.toBigNumber().toNumber(),
127
+ gasLimit: 1,
128
+ isPending: false,
129
+ isExecuted: true,
130
+ isSuccessful: TransactionRecord.receipt.status.toString() === 'SUCCESS',
131
+ isFailed: TransactionRecord.receipt.status.toString() !== 'SUCCESS',
132
+ isInvalid: TransactionRecord.receipt.status.toString() !== 'SUCCESS',
133
+ network,
134
+ nonce: ((_c = TransactionRecord.transactionId.nonce) === null || _c === void 0 ? void 0 : _c.toNumber()) || 0,
135
+ transactionHash: TransactionRecord.transactionHash.toString(),
136
+ transactionId: TransactionRecord.transactionId.toString(),
137
+ transactionLink: getTransactionLink(TransactionRecord.transactionId.toString(), network),
138
+ },
139
+ };
140
+ });
141
+ }
142
+ /**
143
+ * Send the transaction to the Hedera network
144
+ * @param param0
145
+ * @returns
146
+ */
147
+ function sendTransaction({ to, amount, network, accountId, privateKey, decimals, tokenId, }) {
148
+ var _a, _b;
149
+ return __awaiter(this, void 0, void 0, function* () {
150
+ const client = yield getClient(network, privateKey, accountId);
151
+ // amount in lowest denomination - tinybars in this case
152
+ const amountInCrypto = (0, utils_1._toCrypto)(amount.toString(), decimals);
153
+ const from = client.operatorAccountId.toString(); // transak wallet address
154
+ // Create the transfer transaction
155
+ const transferTransaction = new sdk_1.TransferTransaction();
156
+ if (!tokenId) {
157
+ transferTransaction
158
+ .addHbarTransfer(from, sdk_1.Hbar.fromTinybars(-amountInCrypto.toNumber())) // Sending account
159
+ .addHbarTransfer(to, sdk_1.Hbar.fromTinybars(amountInCrypto.toNumber())); // Receiving account
160
+ }
161
+ if (tokenId) {
162
+ // user needs to associate the token with the account before sending the token
163
+ transferTransaction
164
+ .addTokenTransferWithDecimals(tokenId, from, -amountInCrypto.toNumber(), decimals) // Sending account
165
+ .addTokenTransferWithDecimals(tokenId, to, amountInCrypto.toNumber(), decimals) // Receiving account
166
+ .freezeWith(client)
167
+ .signWithOperator(client);
168
+ }
169
+ const sendTransactionResponse = yield transferTransaction.execute(client);
170
+ const transactionReceipt = yield sendTransactionResponse.getReceipt(client);
171
+ return {
172
+ transactionData: sendTransactionResponse,
173
+ receipt: {
174
+ amount,
175
+ date: ((_a = sendTransactionResponse.transactionId.validStart) === null || _a === void 0 ? void 0 : _a.toDate()) || null,
176
+ from,
177
+ gasCostCryptoCurrency: 'HBAR',
178
+ transactionReceipt,
179
+ network,
180
+ nonce: ((_b = sendTransactionResponse.transactionId.nonce) === null || _b === void 0 ? void 0 : _b.toNumber()) || 0,
181
+ to,
182
+ transactionHash: sendTransactionResponse.transactionHash,
183
+ transactionId: sendTransactionResponse.transactionId.toString(),
184
+ transactionLink: getTransactionLink(sendTransactionResponse.transactionId.toString(), network),
185
+ },
186
+ };
187
+ });
188
+ }
189
+ module.exports = {
190
+ getTransactionLink,
191
+ getWalletLink,
192
+ getTransaction,
193
+ isValidWalletAddress,
194
+ sendTransaction,
195
+ getBalance,
196
+ isTokenAssociated,
197
+ };
package/lib/types.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { TransactionResponse, TransactionRecord, TransactionReceipt } from '@hashgraph/sdk';
2
+ export declare type Network = {
3
+ networkName: string;
4
+ transactionLink: (arg0: string) => string;
5
+ walletLink: (arg0: string) => string;
6
+ };
7
+ export declare type GetTransactionResult = {
8
+ transactionData: TransactionRecord;
9
+ receipt: {
10
+ amount: number;
11
+ date: Date | null;
12
+ from: string;
13
+ gasCostCryptoCurrency: string;
14
+ gasCostInCrypto: number;
15
+ gasLimit: number;
16
+ isPending: boolean;
17
+ isExecuted: boolean;
18
+ isSuccessful: boolean;
19
+ isFailed: boolean;
20
+ isInvalid: boolean;
21
+ network: string;
22
+ nonce: number;
23
+ transactionHash: string;
24
+ transactionId: string;
25
+ transactionLink: string;
26
+ };
27
+ };
28
+ export declare type SendTransactionParams = {
29
+ to: string;
30
+ amount: number;
31
+ network: string;
32
+ decimals: number;
33
+ accountId: string;
34
+ privateKey: string;
35
+ tokenId?: string;
36
+ };
37
+ export declare type SendTransactionResult = {
38
+ transactionData: TransactionResponse;
39
+ receipt: {
40
+ amount: number;
41
+ date: Date | null;
42
+ from: string;
43
+ gasCostCryptoCurrency: string;
44
+ network: string;
45
+ nonce: number;
46
+ to: string;
47
+ transactionHash: Uint8Array;
48
+ transactionLink: string;
49
+ transactionId: string;
50
+ transactionReceipt: TransactionReceipt;
51
+ };
52
+ };
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/utils.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { BigNumber } from '@hashgraph/hethers';
2
+ export declare const _toDecimal: (amount: string, decimals: number) => string;
3
+ export declare const _toCrypto: (amount: string, decimals: number) => BigNumber;
4
+ export declare const _getAccountNumber: (txnId: string) => string;
package/lib/utils.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._getAccountNumber = exports._toCrypto = exports._toDecimal = void 0;
4
+ const hethers_1 = require("@hashgraph/hethers");
5
+ // converts any units to Hbars
6
+ const _toDecimal = (amount, decimals) => {
7
+ // sting to BigNumber
8
+ return hethers_1.hethers.utils.formatUnits(hethers_1.hethers.BigNumber.from(amount), decimals);
9
+ };
10
+ exports._toDecimal = _toDecimal;
11
+ // converts Hbar to tinybar
12
+ const _toCrypto = (amount, decimals) => hethers_1.hethers.utils.parseUnits(amount, decimals);
13
+ exports._toCrypto = _toCrypto;
14
+ const _getAccountNumber = (txnId) => {
15
+ const [accountId, rest] = txnId.split('@');
16
+ return accountId;
17
+ };
18
+ exports._getAccountNumber = _getAccountNumber;
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@transak/hedera-transak",
3
+ "version": "1.0.5",
4
+ "description": "",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "directories": {
8
+ "test": "test"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/Transak/hedera-transak.git"
13
+ },
14
+ "scripts": {
15
+ "test": "jest -c jest.config.js",
16
+ "restricted-publish": "npm publish --access restricted",
17
+ "build": "npx tsc",
18
+ "format": "prettier --write \"src/**/*.ts\"",
19
+ "lint": "tslint -p tsconfig.json",
20
+ "prepare": "npm run build",
21
+ "prepublishOnly": "npm run lint",
22
+ "preversion": "npm run lint",
23
+ "version": "npm run format && git add -A src"
24
+ },
25
+ "keywords": [],
26
+ "author": "",
27
+ "license": "ISC",
28
+ "dependencies": {
29
+ "@ethersproject/abi": "^5.7.0",
30
+ "@ethersproject/basex": "^5.7.0",
31
+ "@ethersproject/random": "^5.7.0",
32
+ "@ethersproject/wordlists": "^5.7.0",
33
+ "@hashgraph/hethers": "^1.2.1",
34
+ "@hashgraph/sdk": "^2.18.1",
35
+ "dotenv": "10.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/jest": "^29.0.0",
39
+ "jest": "^28.0.0",
40
+ "prettier": "^2.7.1",
41
+ "ts-jest": "^28.0.8",
42
+ "ts-node": "^10.4.0",
43
+ "tslint": "^6.1.3",
44
+ "tslint-config-prettier": "^1.18.0",
45
+ "typescript": "^4.5.2"
46
+ },
47
+ "files": [
48
+ "/lib/**/*"
49
+ ]
50
+ }