@pioneer-platform/helpers 0.0.0-development.112

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 THORSwap
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "dependencies": {
3
+ "@pioneer-platform/swapkit-entities": "1.0.0-development.120",
4
+ "@pioneer-platform/types": "1.0.0-development.106"
5
+ },
6
+ "description": "THORSwap Lib - Helper library for THORSwap",
7
+ "devDependencies": {
8
+ "@ethersproject/bignumber": "5.7.0",
9
+ "@vitest/coverage-istanbul": "0.34.3",
10
+ "bignumber.js": "9.1.2",
11
+ "vite": "4.4.9",
12
+ "vitest": "0.34.3",
13
+ "@internal/config": "0.0.1-development.3"
14
+ },
15
+ "eslintConfig": {
16
+ "extends": "../eslint-config-thorswap"
17
+ },
18
+ "files": [
19
+ "src/"
20
+ ],
21
+ "homepage": "https://github.com/thorswap/SwapKit",
22
+ "license": "MIT",
23
+ "main": "./src/index.ts",
24
+ "name": "@pioneer-platform/helpers",
25
+ "peerDependencies": {
26
+ "@ethersproject/bignumber": "^5.7.0",
27
+ "bignumber.js": "^9.1.2"
28
+ },
29
+ "type": "module",
30
+ "version": "0.0.0-development.112",
31
+ "scripts": {
32
+ "build": "vite build",
33
+ "clean": "rm -rf dist .turbo node_modules",
34
+ "lint": "eslint --ext .ts,.tsx --fix; tsc --noEmit",
35
+ "test": "vitest --run",
36
+ "test:coverage": "vitest run --coverage"
37
+ }
38
+ }
@@ -0,0 +1,33 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { assetFromString, assetToString } from '../asset.ts';
3
+ import { Chain } from '@pioneer-platform/types';
4
+
5
+ describe('assetToString', () => {
6
+ it('should return the correct string representation of an asset', () => {
7
+ const asset = { chain: Chain.Ethereum, symbol: 'USDT' };
8
+ expect(assetToString(asset)).toBe('ETH.USDT');
9
+
10
+ const synthAsset = { chain: Chain.THORChain, symbol: 'BNB/BNB' };
11
+ expect(assetToString(synthAsset)).toBe('THOR.BNB/BNB');
12
+ });
13
+ });
14
+
15
+ describe('assetFromString', () => {
16
+ it('should return the correct asset object from a string', () => {
17
+ const assetString = 'ETH.USDT';
18
+ const expectedAsset = { chain: Chain.Ethereum, symbol: 'USDT', ticker: 'USDT', synth: false };
19
+ expect(assetFromString(assetString)).toEqual(expectedAsset);
20
+ });
21
+
22
+ it('should return the correct asset object from a synth string', () => {
23
+ const assetString = 'THOR.BNB/BNB';
24
+ const expectedAsset = { chain: Chain.THORChain, symbol: 'BNB/BNB', ticker: 'BNB/BNB', synth: true };
25
+ expect(assetFromString(assetString)).toEqual(expectedAsset);
26
+ });
27
+
28
+ it('should return the correct asset object from a string with a hyphen', () => {
29
+ const assetString = 'ETH.USDT-0XA3910454BF2CB59B8B3A401589A3BACC5CA42306';
30
+ const expectedAsset = { chain: Chain.Ethereum, symbol: 'USDT-0XA3910454BF2CB59B8B3A401589A3BACC5CA42306', ticker: 'USDT', synth: false };
31
+ expect(assetFromString(assetString)).toEqual(expectedAsset);
32
+ });
33
+ });
@@ -0,0 +1,16 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { derivationPathToString } from '../derivationPath.ts';
3
+
4
+ describe('derivationPathToString', () => {
5
+ it('should return the correct string for a full path', () => {
6
+ const path = [1, 2, 3, 4, 5];
7
+ const result = derivationPathToString(path);
8
+ expect(result).toEqual("1'/2'/3'/4/5");
9
+ });
10
+
11
+ it('should return the correct string for a short path', () => {
12
+ const path = [1, 2, 3, 4];
13
+ const result = derivationPathToString(path);
14
+ expect(result).toEqual("1'/2'/3'/4");
15
+ });
16
+ });
package/src/amount.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { BigNumber, BigNumberish } from '@ethersproject/bignumber';
2
+ import type { AmountWithBaseDenom } from '@pioneer-platform/types';
3
+
4
+ type Value = BigNumberish | AmountWithBaseDenom;
5
+
6
+ const isBigNumberValue = (v: unknown): v is BigNumberish =>
7
+ typeof v === 'string' || typeof v === 'number' || v instanceof BigNumber;
8
+
9
+ export const baseAmount = (value?: BigNumberish, decimal: number = 8): AmountWithBaseDenom => {
10
+ const amount = BigNumber.from(value || 0);
11
+
12
+ return {
13
+ amount: () => amount,
14
+ plus: (v: Value, d: number = decimal) =>
15
+ baseAmount(amount.add(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()), d),
16
+ minus: (v: Value, d: number = decimal) =>
17
+ baseAmount(amount.sub(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()), d),
18
+ times: (v: Value, d: number = decimal) =>
19
+ baseAmount(amount.mul(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()), d),
20
+ div: (v: Value, d: number = decimal) =>
21
+ baseAmount(amount.div(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()), d),
22
+ lt: (v: Value) => amount.lt(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()),
23
+ lte: (v: Value) => amount.lte(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()),
24
+ gt: (v: Value) => amount.gt(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()),
25
+ gte: (v: Value) => amount.gte(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()),
26
+ eq: (v: Value) => amount.eq(isBigNumberValue(v) ? v : (v as AmountWithBaseDenom).amount()),
27
+ decimal,
28
+ };
29
+ };
package/src/asset.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Chain } from '@pioneer-platform/types';
2
+
3
+ export const assetToString = ({ chain, symbol }: { chain: Chain; symbol: string }) =>
4
+ `${chain}.${symbol}`;
5
+
6
+ export const assetFromString = (assetString: string) => {
7
+ const [chain, ...symbolArray] = assetString.split('.') as [Chain, ...(string | undefined)[]];
8
+ const synth = assetString.includes('/');
9
+ const symbol = symbolArray.join('.');
10
+ const ticker = symbol?.split('-')?.[0];
11
+
12
+ return { chain, symbol, ticker, synth };
13
+ };
@@ -0,0 +1,5 @@
1
+ export const derivationPathToString = ([network, chainId, account, change, index]: number[]) => {
2
+ const shortPath = typeof index !== 'number';
3
+
4
+ return `${network}'/${chainId}'/${account}'/${change}${shortPath ? '' : `/${index}`}`;
5
+ };
@@ -0,0 +1,62 @@
1
+ const errorMessages = {
2
+ /**
3
+ * Core
4
+ */
5
+ core_wallet_connection_not_found: 10001,
6
+ core_estimated_max_spendable_chain_not_supported: 10002,
7
+ core_extend_error: 10003,
8
+ core_inbound_data_not_found: 10004,
9
+ core_approve_asset_address_or_from_not_found: 10005,
10
+ core_chain_halted: 10099,
11
+ /**
12
+ * Core - Wallet Connection
13
+ */
14
+ core_wallet_xdefi_not_installed: 10101,
15
+ core_wallet_evmwallet_not_installed: 10102,
16
+ core_wallet_walletconnect_not_installed: 10103,
17
+ core_wallet_keystore_not_installed: 10104,
18
+ core_wallet_ledger_not_installed: 10105,
19
+ core_wallet_trezor_not_installed: 10106,
20
+ core_wallet_keplr_not_installed: 10107,
21
+ core_wallet_okx_not_installed: 10108,
22
+ /**
23
+ * Core - Swap
24
+ */
25
+ core_swap_invalid_params: 10200,
26
+ core_swap_route_not_complete: 10201,
27
+ core_swap_asset_not_recognized: 10202,
28
+ core_swap_contract_not_found: 10203,
29
+ core_swap_route_transaction_not_found: 10204,
30
+ core_swap_contract_not_supported: 10205,
31
+ core_swap_transaction_error: 10206,
32
+ core_swap_quote_mode_not_supported: 10207,
33
+ /**
34
+ * Core - Transaction
35
+ */
36
+ core_transaction_deposit_error: 10301,
37
+ core_transaction_create_liquidity_rune_error: 10302,
38
+ core_transaction_create_liquidity_asset_error: 10303,
39
+ core_transaction_create_liquidity_invalid_params: 10304,
40
+ core_transaction_add_liquidity_invalid_params: 10305,
41
+ core_transaction_add_liquidity_no_rune_address: 10306,
42
+ core_transaction_add_liquidity_rune_error: 10307,
43
+ core_transaction_add_liquidity_asset_error: 10308,
44
+ core_transaction_withdraw_error: 10309,
45
+ core_transaction_deposit_to_pool_error: 10310,
46
+
47
+ /**
48
+ * Wallets
49
+ */
50
+ wallet_ledger_connection_error: 2001,
51
+ } as const;
52
+
53
+ type Keys = keyof typeof errorMessages;
54
+
55
+ export class SwapKitError extends Error {
56
+ constructor(errorKey: Keys, sourceError?: any) {
57
+ console.error(sourceError);
58
+
59
+ super(errorKey, { cause: { code: errorMessages[errorKey], message: errorKey } });
60
+ Object.setPrototypeOf(this, SwapKitError.prototype);
61
+ }
62
+ }
@@ -0,0 +1 @@
1
+ export * from './SwapKitError.ts';
package/src/fees.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type AmountWithBaseDenom, FeeOption } from '@pioneer-platform/types';
2
+
3
+ export const singleFee = (fee: AmountWithBaseDenom): Record<FeeOption, AmountWithBaseDenom> => ({
4
+ [FeeOption.Average]: fee,
5
+ [FeeOption.Fast]: fee,
6
+ [FeeOption.Fastest]: fee,
7
+ });
8
+
9
+ export const gasFeeMultiplier: Record<FeeOption, number> = {
10
+ [FeeOption.Average]: 1.2,
11
+ [FeeOption.Fast]: 1.5,
12
+ [FeeOption.Fastest]: 2,
13
+ };
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './amount.ts';
2
+ export * from './asset.ts';
3
+ export * from './derivationPath.ts';
4
+ export * from './exceptions/index.ts';
5
+ export * from './fees.ts';
6
+ export * from './request.ts';
package/src/request.ts ADDED
@@ -0,0 +1,34 @@
1
+ export const getRequest = async <T>(
2
+ url: string,
3
+ params?: { [key in string]?: any },
4
+ ): Promise<T> => {
5
+ const queryParams = Object.entries(params || {}).reduce((acc, [key, value]) => {
6
+ if (value) {
7
+ acc[key] = value;
8
+ }
9
+
10
+ return acc;
11
+ }, {} as { [key in string]: any });
12
+
13
+ const response = await fetch(
14
+ `${url}${params ? `?${new URLSearchParams(queryParams).toString()}` : ''}`,
15
+ { method: 'GET', mode: 'cors', credentials: 'omit' },
16
+ );
17
+
18
+ return response.json();
19
+ };
20
+
21
+ export const postRequest = async <T>(
22
+ url: string,
23
+ data: string,
24
+ headers?: Record<string, string>,
25
+ parseAsString = false,
26
+ ): Promise<T> => {
27
+ const response = await fetch(`${url}`, {
28
+ method: 'POST',
29
+ headers,
30
+ body: data,
31
+ });
32
+
33
+ return parseAsString ? response.text() : response.json();
34
+ };