@pioneer-platform/pioneer-sdk 0.0.81 → 4.13.30

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.
@@ -0,0 +1,30 @@
1
+ export const osmosisTransferTemplate = (params: {
2
+ account_number: string;
3
+ chain_id: string;
4
+ fee: { gas: string; amount: any[] };
5
+ from_address: string;
6
+ to_address: string;
7
+ asset: string;
8
+ amount: string;
9
+ memo: string;
10
+ sequence: string;
11
+ }) => ({
12
+ signerAddress: params.from_address,
13
+ signDoc: {
14
+ account_number: params.account_number,
15
+ chain_id: params.chain_id,
16
+ fee: params.fee,
17
+ msgs: [
18
+ {
19
+ value: {
20
+ amount: [{ denom: params.asset, amount: params.amount }],
21
+ to_address: params.to_address,
22
+ from_address: params.from_address,
23
+ },
24
+ type: 'cosmos-sdk/MsgSend',
25
+ },
26
+ ],
27
+ memo: params.memo,
28
+ sequence: params.sequence,
29
+ },
30
+ });
@@ -0,0 +1,60 @@
1
+ export const thorchainTransferTemplate = (params: {
2
+ account_number: string;
3
+ chain_id: string;
4
+ fee: { gas: string; amount: any[] };
5
+ from_address: string;
6
+ to_address: string;
7
+ asset: string;
8
+ amount: string;
9
+ memo: string;
10
+ sequence: string;
11
+ }) => ({
12
+ signerAddress: params.from_address,
13
+ signDoc: {
14
+ account_number: params.account_number,
15
+ chain_id: params.chain_id,
16
+ fee: params.fee,
17
+ msgs: [
18
+ {
19
+ value: {
20
+ amount: [{ denom: params.asset, amount: params.amount }],
21
+ to_address: params.to_address,
22
+ from_address: params.from_address,
23
+ },
24
+ type: 'cosmos-sdk/MsgSend' as const,
25
+ },
26
+ ],
27
+ memo: params.memo,
28
+ sequence: params.sequence,
29
+ },
30
+ });
31
+
32
+ export const thorchainDepositTemplate = (params: {
33
+ account_number: string;
34
+ chain_id: string;
35
+ fee: { gas: string; amount: any[] };
36
+ from_address: string;
37
+ asset: string;
38
+ amount: string;
39
+ memo: string;
40
+ sequence: string;
41
+ }) => ({
42
+ signerAddress: params.from_address,
43
+ signDoc: {
44
+ account_number: params.account_number,
45
+ chain_id: params.chain_id,
46
+ fee: params.fee,
47
+ msgs: [
48
+ {
49
+ value: {
50
+ coins: [{ asset: 'THOR.RUNE', amount: params.amount }],
51
+ memo: params.memo,
52
+ signer: params.from_address,
53
+ },
54
+ type: 'thorchain/MsgDeposit',
55
+ },
56
+ ],
57
+ memo: params.memo,
58
+ sequence: params.sequence,
59
+ },
60
+ });
@@ -0,0 +1,181 @@
1
+ import { caipToNetworkId, networkIdToCaip } from '@pioneer-platform/pioneer-caip';
2
+
3
+ const TAG = ' | build-dashboard | ';
4
+
5
+ // Build dashboard from cached balances (no Pioneer API calls)
6
+ export function buildDashboardFromBalances(balances: any[], blockchains: string[], assetsMap: Map<string, any>) {
7
+ console.log(TAG, '[DASHBOARD] Building dashboard from cached balances...');
8
+
9
+ const dashboardData: {
10
+ networks: {
11
+ networkId: string;
12
+ totalValueUsd: number;
13
+ gasAssetCaip: string | null;
14
+ gasAssetSymbol: string | null;
15
+ icon: string | null;
16
+ color: string | null;
17
+ totalNativeBalance: string;
18
+ }[];
19
+ totalValueUsd: number;
20
+ networkPercentages: { networkId: string; percentage: number }[];
21
+ } = {
22
+ networks: [],
23
+ totalValueUsd: 0,
24
+ networkPercentages: [],
25
+ };
26
+
27
+ let totalPortfolioValue = 0;
28
+ const networksTemp: {
29
+ networkId: string;
30
+ totalValueUsd: number;
31
+ gasAssetCaip: string | null;
32
+ gasAssetSymbol: string | null;
33
+ icon: string | null;
34
+ color: string | null;
35
+ totalNativeBalance: string;
36
+ }[] = [];
37
+
38
+ console.log(TAG, 'balances: ', balances);
39
+
40
+ // Calculate totals for each blockchain
41
+ for (const blockchain of blockchains) {
42
+ const filteredBalances = balances.filter((b) => {
43
+ const networkId = caipToNetworkId(b.caip);
44
+ return (
45
+ networkId === blockchain ||
46
+ (blockchain === 'eip155:*' && networkId.startsWith('eip155:'))
47
+ );
48
+ });
49
+
50
+ // Deduplicate balances based on caip + pubkey combination
51
+ const balanceMap = new Map();
52
+
53
+ // Special handling for Bitcoin to work around API bug
54
+ const isBitcoin = blockchain.includes('bip122:000000000019d6689c085ae165831e93');
55
+ if (isBitcoin) {
56
+ console.log(TAG, 'Bitcoin network detected - checking for duplicate balances');
57
+ // Group Bitcoin balances by value to detect duplicates
58
+ const bitcoinByValue = new Map();
59
+ filteredBalances.forEach((balance) => {
60
+ const valueKey = `${balance.balance}_${balance.valueUsd}`;
61
+ if (!bitcoinByValue.has(valueKey)) {
62
+ bitcoinByValue.set(valueKey, []);
63
+ }
64
+ bitcoinByValue.get(valueKey).push(balance);
65
+ });
66
+
67
+ // Check if all three address types have the same non-zero balance (API bug)
68
+ for (const [valueKey, balances] of bitcoinByValue.entries()) {
69
+ if (balances.length === 3 && parseFloat(balances[0].valueUsd || '0') > 0) {
70
+ console.log(
71
+ TAG,
72
+ 'BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub',
73
+ );
74
+ // Keep only the xpub (or first one if no xpub)
75
+ const xpubBalance = balances.find((b) => b.pubkey?.startsWith('xpub')) || balances[0];
76
+ const key = `${xpubBalance.caip}_${xpubBalance.pubkey || 'default'}`;
77
+ balanceMap.set(key, xpubBalance);
78
+ } else {
79
+ // Add all balances normally
80
+ balances.forEach((balance) => {
81
+ const key = `${balance.caip}_${balance.pubkey || 'default'}`;
82
+ balanceMap.set(key, balance);
83
+ });
84
+ }
85
+ }
86
+ } else {
87
+ // Standard deduplication for non-Bitcoin networks
88
+ filteredBalances.forEach((balance) => {
89
+ const key = `${balance.caip}_${balance.pubkey || 'default'}`;
90
+ // Only keep the first occurrence or the one with higher value
91
+ if (
92
+ !balanceMap.has(key) ||
93
+ parseFloat(balance.valueUsd || '0') > parseFloat(balanceMap.get(key).valueUsd || '0')
94
+ ) {
95
+ balanceMap.set(key, balance);
96
+ }
97
+ });
98
+ }
99
+
100
+ const networkBalances = Array.from(balanceMap.values());
101
+
102
+ // Ensure we're working with numbers for calculations
103
+ const networkTotal = networkBalances.reduce((sum, balance, idx) => {
104
+ const valueUsd =
105
+ typeof balance.valueUsd === 'string'
106
+ ? parseFloat(balance.valueUsd)
107
+ : balance.valueUsd || 0;
108
+
109
+ if (blockchain.includes('bip122:000000000019d6689c085ae165831e93')) {
110
+ console.log(
111
+ TAG,
112
+ `[BITCOIN DEBUG ${idx}] pubkey:`,
113
+ balance.pubkey?.substring(0, 10) + '...',
114
+ '| balance:',
115
+ balance.balance,
116
+ '| valueUsd:',
117
+ balance.valueUsd,
118
+ '→ parsed:',
119
+ valueUsd,
120
+ '| running sum:',
121
+ sum + valueUsd,
122
+ );
123
+ }
124
+
125
+ return sum + valueUsd;
126
+ }, 0);
127
+
128
+ // Get native asset for this blockchain
129
+ const nativeAssetCaip = networkIdToCaip(blockchain);
130
+ const gasAsset = networkBalances.find((b) => b.caip === nativeAssetCaip);
131
+
132
+ // Calculate total native balance (sum of all balances for the native asset)
133
+ const totalNativeBalance = networkBalances
134
+ .filter((b) => b.caip === nativeAssetCaip)
135
+ .reduce((sum, balance) => {
136
+ const balanceNum =
137
+ typeof balance.balance === 'string'
138
+ ? parseFloat(balance.balance)
139
+ : balance.balance || 0;
140
+ return sum + balanceNum;
141
+ }, 0)
142
+ .toString();
143
+
144
+ // Get colors from assetMap since balances don't have them
145
+ const assetInfo = nativeAssetCaip ? assetsMap.get(nativeAssetCaip) : null;
146
+
147
+ networksTemp.push({
148
+ networkId: blockchain,
149
+ totalValueUsd: networkTotal,
150
+ gasAssetCaip: nativeAssetCaip || null,
151
+ gasAssetSymbol: gasAsset?.ticker || gasAsset?.symbol || assetInfo?.symbol || null,
152
+ icon: gasAsset?.icon || assetInfo?.icon || null,
153
+ color: gasAsset?.color || assetInfo?.color || null,
154
+ totalNativeBalance,
155
+ });
156
+
157
+ totalPortfolioValue += networkTotal;
158
+ }
159
+
160
+ // Sort networks by USD value and assign to dashboard
161
+ dashboardData.networks = networksTemp.sort((a, b) => b.totalValueUsd - a.totalValueUsd);
162
+ dashboardData.totalValueUsd = totalPortfolioValue;
163
+
164
+ // Calculate network percentages for pie chart
165
+ dashboardData.networkPercentages = dashboardData.networks
166
+ .map((network) => ({
167
+ networkId: network.networkId,
168
+ percentage:
169
+ totalPortfolioValue > 0
170
+ ? Number(((network.totalValueUsd / totalPortfolioValue) * 100).toFixed(2))
171
+ : 0,
172
+ }))
173
+ .filter((entry) => entry.percentage > 0); // Remove zero percentages
174
+
175
+ console.log(
176
+ `[FAST DASHBOARD] ✅ Built dashboard: ${
177
+ dashboardData.networks.length
178
+ } networks, $${totalPortfolioValue.toFixed(2)} total`,
179
+ );
180
+ return dashboardData;
181
+ }
@@ -0,0 +1,12 @@
1
+ // Helper function to format time differences
2
+ export function formatTime(durationMs: number): string {
3
+ let seconds = Math.floor((durationMs / 1000) % 60);
4
+ let minutes = Math.floor((durationMs / (1000 * 60)) % 60);
5
+ let hours = Math.floor((durationMs / (1000 * 60 * 60)) % 24);
6
+
7
+ let formatted = '';
8
+ if (hours > 0) formatted += `${hours}h `;
9
+ if (minutes > 0 || hours > 0) formatted += `${minutes}m `;
10
+ formatted += `${seconds}s`;
11
+ return formatted.trim();
12
+ }
@@ -0,0 +1,64 @@
1
+ // Utility function to detect if kkapi is available with smart environment detection
2
+ export async function detectKkApiAvailability(forceLocalhost?: boolean): Promise<{
3
+ isAvailable: boolean;
4
+ baseUrl: string;
5
+ basePath: string;
6
+ }> {
7
+ const tag = ' | detectKkApiAvailability | ';
8
+
9
+ try {
10
+ // Smart detection: Check environment (Tauri, browser, or Node.js)
11
+ const isTauri = typeof window !== 'undefined' && '__TAURI__' in window;
12
+ const isBrowser = typeof window !== 'undefined';
13
+ const isNodeJS = typeof process !== 'undefined' && process.versions && process.versions.node;
14
+ const isLocalhost = isBrowser && window.location.hostname === 'localhost';
15
+
16
+ // If in Tauri, use kkapi:// (will be proxied by Tauri)
17
+ if (isTauri) {
18
+ return {
19
+ isAvailable: true,
20
+ baseUrl: 'kkapi://',
21
+ basePath: 'kkapi://spec/swagger.json',
22
+ };
23
+ }
24
+
25
+ // In Node.js test environment or localhost browser, test if localhost:1646 is available
26
+ // Force localhost if flag is set
27
+ const shouldTestLocalhost = forceLocalhost || isLocalhost || isNodeJS;
28
+
29
+ if (shouldTestLocalhost) {
30
+ const testEnv = isNodeJS ? 'Node.js test environment' : 'development browser';
31
+ try {
32
+ const httpResponse = await fetch('http://localhost:1646/api/v1/health', {
33
+ method: 'GET',
34
+ signal: AbortSignal.timeout(1000), // 1 second timeout for localhost
35
+ });
36
+
37
+ if (httpResponse.ok) {
38
+ return {
39
+ isAvailable: true,
40
+ baseUrl: 'http://localhost:1646',
41
+ basePath: 'http://localhost:1646/spec/swagger.json',
42
+ };
43
+ }
44
+ } catch (httpError: any) {
45
+ console.error('❌ [KKAPI DETECTION] HTTP localhost:1646 not available:', httpError.message);
46
+ }
47
+ }
48
+
49
+ // Fallback for production non-Tauri or when vault server is not running
50
+ console.warn('⚠️ [KKAPI DETECTION] Using fallback config (vault may not be available)');
51
+ return {
52
+ isAvailable: false,
53
+ baseUrl: 'http://localhost:1646',
54
+ basePath: 'http://localhost:1646/spec/swagger.json',
55
+ };
56
+ } catch (error) {
57
+ console.error('❌ [KKAPI DETECTION] Error during detection:', error);
58
+ return {
59
+ isAvailable: false,
60
+ baseUrl: 'http://localhost:1646',
61
+ basePath: 'http://localhost:1646/spec/swagger.json',
62
+ };
63
+ }
64
+ }
@@ -0,0 +1,75 @@
1
+ // Helper functions for pubkey management and deduplication
2
+
3
+ // Helper method to generate unique key for a pubkey
4
+ export function getPubkeyKey(pubkey: any): string {
5
+ return `${pubkey.pubkey}_${pubkey.pathMaster}`;
6
+ }
7
+
8
+ // Helper method to deduplicate pubkeys array
9
+ export function deduplicatePubkeys(pubkeys: any[]): any[] {
10
+ const seen = new Set<string>();
11
+ const deduped = pubkeys.filter((pubkey) => {
12
+ const key = getPubkeyKey(pubkey);
13
+ if (seen.has(key)) {
14
+ return false;
15
+ }
16
+ seen.add(key);
17
+ return true;
18
+ });
19
+ return deduped;
20
+ }
21
+
22
+ // Helper method to validate a pubkey has required fields
23
+ export function validatePubkey(pubkey: any): boolean {
24
+ return !!(pubkey.pubkey && pubkey.pathMaster);
25
+ }
26
+
27
+ // Class for managing pubkey collection with deduplication
28
+ export class PubkeyManager {
29
+ private pubkeys: any[] = [];
30
+ private pubkeySet: Set<string> = new Set();
31
+
32
+ // Helper method to validate and add a single pubkey
33
+ addPubkey(pubkey: any): boolean {
34
+ // Validate pubkey has required fields
35
+ if (!validatePubkey(pubkey)) {
36
+ return false;
37
+ }
38
+
39
+ const key = getPubkeyKey(pubkey);
40
+
41
+ // Check if already exists
42
+ if (this.pubkeySet.has(key)) {
43
+ return false;
44
+ }
45
+
46
+ // Add to both array and set
47
+ this.pubkeys.push(pubkey);
48
+ this.pubkeySet.add(key);
49
+ return true;
50
+ }
51
+
52
+ // Helper method to set pubkeys array with deduplication
53
+ setPubkeys(newPubkeys: any[]): void {
54
+ // Clear existing
55
+ this.pubkeys = [];
56
+ this.pubkeySet.clear();
57
+
58
+ // Add each pubkey with validation
59
+ let added = 0;
60
+ for (const pubkey of newPubkeys) {
61
+ if (this.addPubkey(pubkey)) {
62
+ added++;
63
+ }
64
+ }
65
+ }
66
+
67
+ getPubkeys(): any[] {
68
+ return this.pubkeys;
69
+ }
70
+
71
+ clear(): void {
72
+ this.pubkeys = [];
73
+ this.pubkeySet.clear();
74
+ }
75
+ }
package/lib/index.d.ts DELETED
@@ -1,66 +0,0 @@
1
- export interface SendToAddress {
2
- blockchain: string;
3
- asset: string;
4
- amount: number;
5
- address: string;
6
- memo?: string;
7
- noBroadcast?: boolean;
8
- }
9
- export interface config {
10
- spec: string;
11
- env: string;
12
- mode: string;
13
- username: string;
14
- addresses?: [];
15
- wallet?: any;
16
- pubkeys?: any;
17
- auth?: string;
18
- paths?: any;
19
- privWallet?: any;
20
- mnemonic?: string;
21
- queryKey?: string;
22
- offline?: boolean;
23
- pioneerApi?: boolean;
24
- }
25
- export interface Invocation {
26
- coin: string;
27
- addressFrom?: string;
28
- addressTo: string;
29
- amount: string;
30
- memo: string;
31
- nonce?: number;
32
- }
33
- export declare class SDK {
34
- private spec;
35
- private pioneerApi;
36
- private init;
37
- private config;
38
- private clients;
39
- private createPairingCode;
40
- private queryKey;
41
- private service;
42
- private isTestnet;
43
- private getUserParams;
44
- private sendToAddress;
45
- private url;
46
- private events;
47
- private wss;
48
- private username;
49
- private blockchains;
50
- private startSocket;
51
- private isPaired;
52
- private context;
53
- private info;
54
- private wallets;
55
- private totalValueUsd;
56
- private getUserInfo;
57
- private getWalletInfo;
58
- private setContext;
59
- private getInvocations;
60
- private invocationContext;
61
- private assetContext;
62
- private assetBalanceUsdValueContext;
63
- private assetBalanceNativeContext;
64
- private getInvocation;
65
- constructor(spec: string, config: any, isTestnet?: boolean);
66
- }