forked from hogyzen12/unruggable
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunruggable.sh
executable file
·2172 lines (1870 loc) · 88.1 KB
/
unruggable.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Global variables
RPC="https://damp-fabled-panorama.solana-mainnet.quiknode.pro/186133957d30cece76e7cd8b04bce0c5795c164e/"
UNRUGGABLE_FOLDER="$HOME/.config/solana/unruggable"
ADDRESS_BOOK_FILE="$HOME/.config/solana/unruggable/addressBook.txt"
NFT_FILE="$HOME/.config/solana/unruggable/nfts.txt"
TOKENS_FILE="$HOME/.config/solana/unruggable/tokens.txt"
UNRUGGABLE_WALLET="$UNRUGGABLE_FOLDER/unruggable.json"
CONFIG_DIR="$HOME/.config/solana/cli"
CONFIG_FILE="$HOME/.config/solana/cli/config.yml"
UNRUGGABLE_STAKING="$UNRUGGABLE_FOLDER/staking_keys"
DEFAULT_KEYS_DIR="$HOME/.config/solana"
SCRIPT_NAME="unruggable"
SCRIPT_PATH="$UNRUGGABLE_FOLDER/$SCRIPT_NAME"
SOLANA_RELEASES_URL="https://github.com/solana-labs/solana/releases/latest/download"
CALYPSO_FOLDER="$HOME/.config/solana/unruggable/calypso"
PANTHEON=("calypso.js" "hermes.js" "hermesSpl.js" "poseidon.js")
# Function to detect the operating system
detect_os() {
case "$(uname -s)" in
Linux*) OS=Linux;;
Darwin*) OS=macOS;;
*) OS="UNKNOWN:${unameOut}"
esac
echo "Operating System Detected: $OS"
}
# Function to detect the operating system
detect_processor() {
ARCH=$(uname -m)
echo "Processor detected: $ARCH"
case "$ARCH" in
"x86_64")
# Intel-based Mac
SOLANA_BINARY="solana-release-x86_64-apple-darwin.tar.bz2"
;;
"arm64")
# Apple Silicon Mac
SOLANA_BINARY="solana-release-aarch64-apple-darwin.tar.bz2"
;;
*)
echo "Unsupported architecture: $ARCH"
exit 1
;;
esac
}
# Function to ensure Homebrew is installed on macOS
ensure_homebrew_installed() {
if ! command -v brew &> /dev/null; then
echo "Homebrew not found. Installing Homebrew..."
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Determine the shell's configuration file. Default to .zshrc for macOS.
local shell_profile="$HOME/.zshrc"
# Check if the shell profile file exists, create if not
if [ ! -f "$shell_profile" ]; then
echo "Creating $shell_profile since it doesn't exist."
touch "$shell_profile"
fi
# Add Homebrew to PATH in the shell's profile
if ! grep -q '/opt/homebrew/bin/brew' "$shell_profile"; then
echo 'Adding Homebrew to PATH in' "$shell_profile"
echo '# Homebrew' >> "$shell_profile"
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$shell_profile"
source $shell_profile
fi
if ! command -v brew &> /dev/null; then
echo "Failed to install Homebrew."
exit 1
fi
else
echo "Homebrew is already installed."
fi
}
# Function to install Node.js version 16 and npm using nvm
install_node_npm() {
# Define NVM_DIR
export NVM_DIR="$HOME/.nvm"
# Source nvm if it's already installed, to make it available in this script
if [ -s "$NVM_DIR/nvm.sh" ]; then
\. "$NVM_DIR/nvm.sh"
\. "$NVM_DIR/bash_completion"
fi
# Check if nvm command is available, install if not
if ! command -v nvm &> /dev/null; then
echo "nvm not found. Installing nvm..."
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
# Source nvm scripts to make it available in the current session
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
fi
# Now check again if nvm is available after installation and sourcing
if ! command -v nvm &> /dev/null; then
echo "nvm installation failed or nvm is not sourced properly."
return 1
fi
# Install Node.js version 16
echo "Installing Node.js..."
nvm install 18
nvm use 18
nvm alias default 18
echo "Node.js and npm have been installed successfully."
}
# Function to check and update the current directory with the latest git version
check_and_update_git() {
# Check if the current directory is a git repository
if git rev-parse --git-dir > /dev/null 2>&1; then
echo "This is a git repository. Checking for updates..."
# Fetch latest changes from the remote repository
git fetch
# Check for differences between the current HEAD and the remote
LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse @{u})
if [ "$LOCAL" != "$REMOTE" ]; then
echo "Updates found. Updating and restarting the script..."
git pull
exec "$0" "$@" # Restart the script
else
echo "Already up to date."
fi
else
echo "This directory is not a git repository."
fi
}
# Function to check and install a package
check_and_install_package() {
local package_name=$1
# Check if the package is installed
if ! command -v $package_name &> /dev/null; then
echo "$package_name could not be found. Attempting to install."
if [[ $OS == "Linux" ]]; then
sudo apt-get update && sudo apt-get install -y $package_name
elif [[ $OS == "macOS" ]]; then
# Ensure Homebrew is installed before attempting to use it
ensure_homebrew_installed
brew install $package_name
fi
# Check again if package installation was successful
if ! command -v $package_name &> /dev/null; then
echo "Failed to install $package_name. Attempting to use local binary."
# Package binaries here/download
# use_local_binary $package_name
else
echo "$package_name installed successfully."
fi
else
echo "$package_name is already installed."
fi
}
# Function to check if Solana CLI is installed
check_solana_cli_installed() {
if ! command -v solana &> /dev/null; then
echo "Solana CLI not found - proceeding to install using the install script."
# Attempt to install using the official Solana install script
if sh -c "$(curl -sSfL https://release.solana.com/v1.18.4/install)"; then
echo "Attempting to add Solana CLI to PATH automatically..."
# Determine which profile file to use based on file existence
if [ -f "$HOME/.zshrc" ]; then
PROFILE_FILE="$HOME/.zshrc"
elif [ -f "$HOME/.bashrc" ]; then
PROFILE_FILE="$HOME/.bashrc"
else
echo "No .zshrc or .bashrc file found. Defaulting to .bashrc and creating it if necessary."
PROFILE_FILE="$HOME/.bashrc"
touch "$HOME/.bashrc" # Create .bashrc if it doesn't exist
fi
# Add Solana to PATH in the determined profile file
if ! grep -q 'solana/install/active_release/bin' "$PROFILE_FILE" 2>/dev/null; then
echo 'export PATH="$HOME/.local/share/solana/install/active_release/bin:$PATH"' >> "$PROFILE_FILE"
echo "Solana CLI path added to $PROFILE_FILE"
fi
# Attempt to automatically add Solana to PATH for the current session
export PATH="$HOME/.local/share/solana/install/active_release/bin:$PATH"
# Reload profile to ensure PATH update takes effect in the current session
source "$PROFILE_FILE" 2>/dev/null || {
echo "Failed to reload $PROFILE_FILE. You may need to open a new terminal or manually source your profile file."
}
echo "Solana CLI installed successfully."
else
echo "Failed to install Solana CLI using the install script. Attempting to install using pre-built binaries..."
# Fallback to pre-built binaries installation
# Determine the correct binary to download based on the OS
case "$OS" in
Linux)
SOLANA_BINARY="solana-release-x86_64-unknown-linux-gnu.tar.bz2"
;;
macOS)
SOLANA_BINARY="solana-release-x86_64-apple-darwin.tar.bz2"
;;
*)
echo "Unsupported OS for automatic Solana CLI installation."
return 1
;;
esac
# Define the base URL for Solana releases
SOLANA_RELEASES_URL="https://github.com/solana-labs/solana/releases/latest/download"
# Download the appropriate binary
echo "Downloading Solana CLI for $OS..."
curl -L "$SOLANA_RELEASES_URL/$SOLANA_BINARY" -o "/tmp/$SOLANA_BINARY"
# Extract the binary
echo "Extracting Solana CLI..."
tar jxf "/tmp/$SOLANA_BINARY" -C "/tmp"
# Move to a more permanent location
echo "Installing Solana CLI..."
mkdir -p "$HOME/.local/bin"
cp -r "/tmp/solana-release/bin/"* "$HOME/.local/bin/"
# Add to PATH if not already present
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
echo "Adding Solana CLI to PATH..."
echo 'export PATH=$PATH:$HOME/.local/bin' >> "$PROFILE_FILE"
export PATH="$PATH:$HOME/.local/bin"
fi
# Clean up
rm -rf "/tmp/$SOLANA_BINARY" "/tmp/solana-release"
# Verify installation
if ! command -v solana &> /dev/null; then
echo "Failed to install Solana CLI."
return 1
fi
echo "Solana CLI installed successfully using pre-built binaries."
fi
else
echo "Solana CLI is installed."
fi
}
# Function to check if SPL Token CLI is installed
check_spl_token_cli_installed() {
if ! command -v spl-token &> /dev/null; then
echo "Error: SPL Token CLI could not be found."
echo "Please install the SPL Token CLI. You can usually install it via 'cargo install spl-token-cli' if you have Rust and Cargo installed."
exit 1
fi
echo "spl-token cli is installed"
}
check_and_create_unruggable_folder() {
if [ ! -d "$UNRUGGABLE_FOLDER" ]; then
mkdir -p "$UNRUGGABLE_FOLDER"
chmod 700 "$UNRUGGABLE_FOLDER"
if [ $? -eq 0 ]; then
echo "Unruggable folder created successfully."
else
echo "Error: Failed to create the folder $UNRUGGABLE_FOLDER."
exit 1
fi
else
echo "Unuruggable folder inited. Check passed."
fi
}
check_and_create_token_files() {
# Check if the nft file exists
if [ ! -f "$NFT_FILE" ]; then
echo "nfts not located. Initializing."
cp nfts.txt "$UNRUGGABLE_FOLDER"
if [ $? -eq 0 ]; then
echo "nft book initialized successfully."
else
echo "Error: Failed to initialize $NFT_FILE."
exit 1
fi
else
echo "NFTs files found. Check passed."
fi
# Read and store the index from the first line of the file
# Parallelising searches with grep to speed it up
declare -a index_keys
declare -a index_ranges
index_line=$(sed -n '1p' $NFT_FILE | sed 's/Index: //')
IFS=';' read -ra ADDR <<< "$index_line"
current_line=2
for i in "${ADDR[@]}"; do
IFS=':' read -r char lines <<< "$i"
if ! [[ $lines =~ ^[0-9]+$ ]]; then
echo "Error: Non-numeric line count '$lines' for character '$char'"
continue
fi
# Calculate the ending line number based on the starting line and number of lines
end_line=$(($current_line + lines - 1))
index_keys+=("$char")
index_ranges+=("$current_line-$end_line")
current_line=$(($end_line + 1)) # Update the starting line for the next character
done
# Check if the token file exists
if [ ! -f "$TOKENS_FILE" ]; then
echo "tokens not located. Initializing."
cp tokens.txt "$UNRUGGABLE_FOLDER"
if [ $? -eq 0 ]; then
echo "token book initialized successfully."
else
echo "Error: Failed to initialize $TOKENS_FILE."
exit 1
fi
else
echo "Token file found. Check passed."
fi
}
check_and_create_calypso_folder() {
# Check if the CALYPSO_FOLDER exists
if [ ! -d "$CALYPSO_FOLDER" ]; then
echo "Calypso folder not found. Initializing."
cd calypso
npm install
cd ..
# Attempt to copy the calypso directory from the source to the target location
cp -r calypso "$CALYPSO_FOLDER"
# Check if the copy operation was successful
if [ $? -eq 0 ]; then
echo "Calypso folder initialized successfully."
else
echo "Error: Failed to initialize the Calypso folder."
exit 1
fi
else
echo "Calypso folder already exists. Check passed."
fi
# Loop through the list of required files
for file in "${PANTHEON[@]}"; do
# Check if each file exists in the CALYPSO_FOLDER
if [ ! -f "$CALYPSO_FOLDER/$file" ]; then
echo "$file not found in Calypso folder. Copying..."
# Attempt to copy the missing file from the source calypso/ directory
cp "calypso/$file" "$CALYPSO_FOLDER/"
# Check if the copy operation was successful
if [ $? -eq 0 ]; then
echo "$file copied successfully."
else
echo "Error: Failed to copy $file to the Calypso folder."
exit 1
fi
else
echo "$file check passed."
fi
done
}
check_and_create_address_book() {
# Check if the address book file exists
if [ ! -f "$ADDRESS_BOOK_FILE" ]; then
echo "Address book not found. Initializing with devs cat treat wallet."
# Initialise the address book
echo "juLesoSmdTcRtzjCzYzRoHrnF8GhVu6KCV7uxq7nJGp dev-cat-snacks" > "$ADDRESS_BOOK_FILE"
if [ $? -eq 0 ]; then
echo "Address book initialized successfully."
else
echo "Error: Failed to initialize the address book at $ADDRESS_BOOK_FILE."
exit 1
fi
else
echo "Address book found. Check passed."
fi
}
# Ensure the script is in the correct directory and executable
ensure_script_location_and_executability() {
if [ "$(basename $0)" != "$SCRIPT_NAME" ]; then
# The script is not in the desired location, so move it
echo "Moving the script to $SCRIPT_PATH and making it executable..."
cp "$0" "$SCRIPT_PATH"
chmod u+x "$SCRIPT_PATH"
echo "Script moved and made executable."
# Detect the operating system
detect_os
# Determine which profile file to update based on OS and potentially shell
PROFILE_FILE="$HOME/.bashrc" # default
if [[ $OS == "macOS" ]]; then
# macOS users might use zsh by default
PROFILE_FILE="$HOME/.zshrc"
fi
# Now create an alias and add it to the profile for persistence
if ! grep -q "alias $SCRIPT_NAME=" "$PROFILE_FILE"; then
echo "Adding alias to $PROFILE_FILE..."
echo "alias $SCRIPT_NAME='$SCRIPT_PATH'" >> "$PROFILE_FILE"
# Source the profile file to make the alias take effect immediately
source "$PROFILE_FILE"
echo "Alias added and sourced. You can now use '$SCRIPT_NAME' command."
else
echo "Alias for '$SCRIPT_NAME' already exists in $PROFILE_FILE."
fi
echo "Unruggable has been succesfully set up."
echo "Open any terminal and simply type unruggable to start the wallet."
#exit 0
fi
}
create_and_set_custom_solana_config() {
# Check if the directory exists, if not create it
if [[ ! -d "$CONFIG_DIR" ]]; then
mkdir -p "$CONFIG_DIR"
echo "Configuration directory created at $CONFIG_DIR."
# Write the new config settings to the config file
echo "Setting Solana config file to unruggable default..."
cat > "$CONFIG_FILE" <<EOF
---
json_rpc_url: $RPC
websocket_url: ''
keypair_path: $UNRUGGABLE_WALLET
address_labels:
'11111111111111111111111111111111': System Program
commitment: confirmed
EOF
fi
config_output=$(solana config get)
# Extract the current RPC URL
current_rpc=$(echo "$config_output" | grep 'RPC URL' | awk '{print $3}')
# Check if the current RPC URL is the default Solana URL
if [[ "$current_rpc" == "https://api.mainnet-beta.solana.com" ]]; then
# Update the RPC URL to the hardcoded value
solana config set --url "$RPC"
echo "RPC URL updated to custom value."
fi
# Check if the UNRUGGABLE_WALLET file exists
if [[ ! -f "$UNRUGGABLE_WALLET" ]]; then
echo "Generating new unruggable wallet starting with 'unr'..."
# Capture the output of solana-keygen grind to find the generated keypair filename
grind_output=$(solana-keygen grind --starts-with "unr":1)
# Extract the filename from the output
keypair_file=$(echo "$grind_output" | grep -o '[^ ]*.json')
# Move the keypair file to the UNRUGGABLE_WALLET location
mv "$keypair_file" "$UNRUGGABLE_WALLET"
# Set the new wallet address in the config
new_wallet_address=$(solana address -k "$UNRUGGABLE_WALLET")
solana config set --keypair "$UNRUGGABLE_WALLET"
echo "New wallet address: $new_wallet_address"
fi
echo "Custom Solana configuration and keypair setup complete."
}
# Function to initialize prices
init_prices() {
local IFS=$'\n' # Set IFS to newline for proper array population
local lines=($(<"$TOKENS_FILE")) # Read entire file into an array
local updated_lines=()
local line_count=${#lines[@]}
local index=0
for line in "${lines[@]}"; do
local mint=$(echo "$line" | cut -d',' -f1)
local name=$(echo "$line" | cut -d',' -f2)
local decimals=$(echo "$line" | cut -d',' -f3)
local price=$(echo "$line" | cut -d',' -f4)
if [[ "$price" == "0" ]]; then
local amount=$(echo "1 * 10^$decimals" | bc)
local price_data=$(curl -s "https://quote-api.jup.ag/v6/quote?inputMint=$mint&outputMint=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&amount=$amount&slippageBps=1")
sleep 0.01
price=$(echo "$price_data" | jq -r '.outAmount' | awk -v dec="$decimals" '{print ($1 / (10^6))}')
fi
# Update the line with the new price
updated_lines[index]="$mint,$name,$decimals,$price"
((index++))
done
# Write updated content back to the file
printf "%s\n" "${updated_lines[@]}" > "$TOKENS_FILE"
}
# Function to run all pre-launch checks
run_pre_launch_checks() {
echo "Performing pre-launch checks..."
echo "Detecting Operating System"
detect_os
detect_processor
install_node_npm
# Check and install curl, jq and qrencode
check_and_install_package "curl"
check_and_install_package "bc"
check_and_install_package "jq"
check_and_install_package "qrencode"
check_and_install_package "git"
# Git updates
check_and_update_git
# Check that solana and spl-token are available
check_solana_cli_installed
check_spl_token_cli_installed
check_and_create_unruggable_folder
check_and_create_address_book
check_and_create_token_files
check_and_create_calypso_folder
ensure_script_location_and_executability
create_and_set_custom_solana_config
init_prices
echo "All checks passed. Launching Unruggable..."
}
# Function to get wallet and staked information
get_wallet_info() {
# Get the current config
config_output=$(solana config get)
# Extract the keypair path
keypair_path=$(echo "$config_output" | grep 'Keypair Path' | awk '{print $3}')
# Get the wallet address
wallet_address=$(solana address -k "$keypair_path")
# Get the balance
balance=$(solana balance "$wallet_address")
# Initialize total staked SOL variable
total_staked_sol=0
# Check if the staking keys directory exists
if [ -d "$UNRUGGABLE_STAKING" ]; then
# Prepare a glob pattern for stake account files
stake_account_files_glob="$UNRUGGABLE_STAKING"/"$wallet_address"*.json
# Check if glob pattern expands to anything (if there are any files)
# This is a workaround to check if a glob pattern matches any file
# We put it in an array and check the array size
stake_account_files=( $stake_account_files_glob )
if [ -e "${stake_account_files[0]}" ]; then
# Loop through each stake account file in the staking keys directory
for stake_account_file in "${stake_account_files[@]}"; do
# Fetch the stake account balance and extract just the numeric part
stake_account_balance=$(solana balance -k "$stake_account_file" | awk '{print $1}')
# Ensure the balance is a valid number before adding
if [[ $stake_account_balance =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
# Add the stake account balance to the total staked SOL
total_staked_sol=$(echo "$total_staked_sol + $stake_account_balance" | bc)
fi
done
fi
fi
echo "$wallet_address $balance $total_staked_sol"
}
# Function to print wallet address in color
print_colored_address() {
local address=$1
# Define an array of colors
local -a colors=(
'\033[0;31m' # Red
'\033[0;32m' # Green
'\033[0;33m' # Yellow
'\033[0;34m' # Blue
'\033[0;35m' # Magenta
'\033[0;36m' # Cyan
'\033[0;37m' # Light gray
'\033[0;91m' # Light red
'\033[0;92m' # Light green
'\033[0;93m' # Light yellow
'\033[0;94m' # Light blue
'\033[0;95m' # Light magenta
'\033[0;96m' # Light cyan
'\033[0;97m' # White
)
local nc='\033[0m' # No Color
local part_length=$(( ${#address} / 4 ))
for (( i=0; i<4; i++ )); do
local part=${address:$((i * part_length)):${part_length}}
local sum=0
# Calculate sum of ASCII values of characters in the part
for (( j=0; j<${#part}; j++ )); do
local ord=$(printf "%d" "'${part:$j:1}")
((sum+=ord))
done
# Use the sum to select a color
local color_index=$((sum % ${#colors[@]}))
local color=${colors[$color_index]}
# Print the part in the selected color
echo -en "${color}${part}${nc}"
done
}
# Function to find the range for a given first character
get_range_for_char() {
local char=$1
for i in "${!index_keys[@]}"; do
if [[ "${index_keys[$i]}" == "$char" ]]; then
echo "${index_ranges[$i]}"
return
fi
done
echo ""
}
# Function to check transaction confirmation
check_transaction_confirmation() {
local transaction_id=$1
local max_attempts=30
local attempt=0
local delay_between_attempts=10 # seconds
echo "Checking transaction status for ID: $transaction_id"
while [ $attempt -lt $max_attempts ]; do
# Increment attempt counter
((attempt++))
# Check transaction confirmation
confirmation_output=$(solana confirm $transaction_id 2>&1)
echo "Attempt $attempt: $confirmation_output"
# Check if the transaction has been confirmed
if echo "$confirmation_output" | grep -q "Confirmed"; then
echo "Transaction $transaction_id confirmed successfully."
return 0
fi
# Check for any explicit failure messages (optional)
if echo "$confirmation_output" | grep -q "Transaction not found"; then
echo "Transaction $transaction_id not found. It may have failed to process."
return 1
fi
# Wait before the next attempt
sleep $delay_between_attempts
done
echo "Failed to confirm transaction $transaction_id after $max_attempts attempts."
return 1
}
receive_sol() {
# Fetch the current wallet address
wallet_address=$(solana address)
echo "Scan the below QR code, or copy the below address"
echo "to receive Solana and or any other SPL token."
echo $wallet_address
#print_colored_address $wallet_address
#echo ""
# Generate and display the QR code
qrencode -t UTF8 "$wallet_address"
echo "Press any key to return to the home screen..."
read -n 1 -s # Wait for user input before returning
}
confirm_tx() {
local tx_signature=$1
local status=""
local previous_status=""
local attempts=0
local max_attempts=42
while true; do
status=$(solana confirm "$tx_signature" 2>&1)
if echo "$status" | grep -i "Finalized" > /dev/null; then
echo "Transaction $tx_signature is Finalized"
break
elif echo "$status" | grep -i "Confirmed" > /dev/null; then
current_status="Confirmed"
elif echo "$status" | grep -i "Processed" > /dev/null; then
current_status="Processed"
else
current_status="Pending"
fi
if [ "$current_status" != "$previous_status" ]; then
echo "TX is $current_status"
previous_status=$current_status
else
echo "TX is $current_status"
fi
attempts=$((attempts + 1))
if [ $attempts -ge $max_attempts ]; then
echo "Transaction $tx_signature failed after $max_attempts attempts."
break
fi
sleep 1 # Wait for 1 second before checking again
done
}
send_sol() {
while true; do
echo "How would you like to send SOL?"
echo "1 - Enter a Solana address."
echo "2 - Select from Unruggable loaded wallets."
echo "3 - Select from your address book."
echo "9 - Return to home screen."
read -p "Enter your choice (1, 2, 3, or 9): " send_choice
# Extract the Keypair Path from the solana config
config_output=$(solana config get)
keypair_path=$(echo "$config_output" | grep "Keypair Path" | awk '{ print $NF }')
keypair_dir=$(echo "$config_output" | grep 'Keypair Path' | awk '{print $3}' | xargs dirname)
if [[ $send_choice -eq 2 ]]; then
echo "Available Wallets:"
local i=0
declare -a wallet_paths # Use a simple array to store paths
declare -a wallet_addys # Use a simple array to store paths
# Function to process directories and find wallets
process_directory() {
local directory=$1
if [ -d "$directory" ]; then
for keypair in "$directory"/*.json; do
# Check if the file exists to avoid the case where the glob doesn't match anything
if [ -e "$keypair" ]; then
wallet_address=$(solana address -k "$keypair")
balance=$(solana balance "$wallet_address")
echo "$i. $wallet_address ($balance)"
wallet_paths+=("$keypair")
wallet_addys+=("$wallet_address")
i=$((i+1))
fi
done
fi
}
# Check and process each unique directory
if [[ "$keypair_dir" != "$UNRUGGABLE_FOLDER" && "$keypair_dir" != "$DEFAULT_KEYS_DIR" ]]; then
process_directory "$keypair_dir"
fi
process_directory "$UNRUGGABLE_FOLDER"
process_directory "$DEFAULT_KEYS_DIR"
read -p "Select the number of the wallet you want to send SOL to: " wallet_selection
if [[ $wallet_selection =~ ^[0-9]+$ ]] && [ $wallet_selection -ge 0 ] && [ $wallet_selection -lt ${#wallet_paths[@]} ]; then
recipient_address=${wallet_addys[$wallet_selection]}
echo "You have selected to send SOL to: $recipient_address"
else
echo "Invalid selection. Returning to the main menu."
return
fi
elif [[ $send_choice -eq 1 ]]; then
read -p "Enter the recipient's address: " recipient_address
#echo "You have selected to send SOL to $recipient_address"
# Print the static message part
echo -n "You have selected to send SOL to "
# Print the recipient address in color
print_colored_address "$recipient_address"
echo ""
elif [[ $send_choice -eq 3 ]]; then
echo "Select a recipient from the address book:"
local i=0
declare -a book_entries
while IFS= read -r line; do
address=$(echo $line | awk '{print $1}')
tag=$(echo $line | cut -d ' ' -f 2-)
echo "$i. $tag ($address)"
book_entries[i]=$address
i=$((i+1))
done < "$ADDRESS_BOOK_FILE"
read -p "Enter the number of the recipient: " book_selection
if [[ $book_selection =~ ^[0-9]+$ ]] && [ $book_selection -ge 0 ] && [ $book_selection -lt ${#book_entries[@]} ]; then
recipient_address=${book_entries[$book_selection]}
echo "You have selected to send SOL to $recipient_address"
else
echo "Invalid selection. Please try again."
continue
fi
elif [[ $send_choice -eq 9 ]]; then
echo "Returning to home screen."
return
else
echo "Invalid choice. Please try again."
continue
fi
# Assuming the address could be valid, proceed to check the balance
recipient_balance=$(solana balance "$recipient_address" 2>&1)
# Check if the solana command succeeded
if [[ $? -ne 0 ]]; then
echo "Error fetching balance. Please ensure the address is correct. Error details: $recipient_balance"
return
else
echo "Recipient owns : $recipient_balance"
# Extract all mint addresses for tokens owned by the wallet
output=$(spl-token accounts --output json-compact --owner "$recipient_address")
owned_mints=$(echo "$output" | jq -r '.accounts[] | select(.tokenAmount.uiAmount > 0) | .mint')
# Check if owned_mints is not empty
if [ -n "$owned_mints" ]; then
# Process each owned mint for tokens
echo "$owned_mints" | while read -r mint_address; do
token_info=$(grep -i "$mint_address" "$TOKENS_FILE")
if [ ! -z "$token_info" ]; then
token_name=$(echo "$token_info" | awk -F, '{print $2}')
balance=$(echo "$output" | jq -r --arg mint_address "$mint_address" '.accounts[] | select(.mint == $mint_address) | .tokenAmount.uiAmountString')
echo "Recipient owns token: $balance $token_name"
fi
done
else
echo ""
fi
# Check if owned_mints is not empty
if [ -n "$owned_mints" ]; then
# Process each owned mint for tokens
echo "$owned_mints" | while read -r mint_address; do
first_char=${mint_address:0:1}
range=$(get_range_for_char "$first_char")
nft_info=$(sed -n "${range}p" $NFT_FILE | grep -i "$mint_address")
if [ ! -z "$token_info" ]; then
token_name=$(echo "$nft_info" | awk -F, '{print $2}')
balance=$(echo "$output" | jq -r --arg mint_address "$mint_address" '.accounts[] | select(.mint == $mint_address) | .tokenAmount.uiAmountString')
echo "Recipient owns token: $balance $token_name"
fi
done
else
echo ""
fi
fi
# Prompt for amount to send
read -p "Enter the amount of SOL to send: " amount
# Handle the case where the recipient's account is unfunded
if [[ $recipient_balance == "0" ]]; then
echo "You are sending $amount SOL to Wallet: $recipient_address"
echo "The recipient's account is unfunded."
read -p "Do you still want to proceed with the transfer? (yes/no): " confirmation
if [[ $confirmation != "yes" ]]; then
echo "Transfer cancelled."
return
fi
transfer_command="solana transfer --allow-unfunded-recipient --with-compute-unit-price 0.00001 $recipient_address $amount"
else
echo "You are sending $amount SOL to Wallet: $recipient_address"
read -p "Confirm the transaction? (yes/no): " confirmation
if [[ $confirmation != "yes" ]]; then
echo "Transfer cancelled."
return
fi
transfer_command="solana transfer --no-wait --allow-unfunded-recipient --with-compute-unit-price 0.00001 $recipient_address $amount"
fi
# Initialize a flag to track which transaction method is used
use_hermes_flag=0
# Check for calypso/hermes.js existence within CALYPSO_FOLDER
if [[ -d "$CALYPSO_FOLDER" && -f "$CALYPSO_FOLDER/hermes.js" ]]; then
echo "The Hermes tool is available for transactions."
read -p "Would you like to use the Hermes tool for this transaction? (yes/no): " use_hermes
if [[ $use_hermes == "yes" ]]; then
# Execute the transaction with Hermes
echo "Executing transaction with Hermes..."
hermes_output=$(node "$CALYPSO_FOLDER/hermes.js" "$amount" "$recipient_address" "$keypair_path")
tx_signature=$(echo "$hermes_output")
#echo "Transaction completed with Hermes. Signature: $tx_signature"
# Confirm the transaction
confirm_tx "$tx_signature"
use_hermes_flag=1
fi
fi
# Check if Hermes was not used, then proceed with Solana transfer
if [[ $use_hermes_flag -eq 0 ]]; then
echo "Executing transfer with Solana CLI..."
signature=$(eval $transfer_command)
tx_signature=$(echo "$signature" | awk '{print $2}')
echo $tx_signature
echo "Transaction completed with Solana CLI. Signature: $tx_signature"
confirm_tx "$tx_signature"
fi
# Check if the address is already in the address book
if grep -q "$recipient_address" "$ADDRESS_BOOK_FILE"; then
echo "This address is already in your address book."
else
read -p "Press Enter to go back home or type 'add' to add this address to your address book: " post_tx_choice
if [[ $post_tx_choice == "add" ]]; then
read -p "Enter a tag for this address: " tag
echo "$recipient_address $tag" >> "$ADDRESS_BOOK_FILE"
echo "Address added to your address book."
fi
fi
break
done
}
display_tokens_and_send() {
# Get the current wallet address
wallet_address=$(solana address)
echo "Fetching tokens for wallet: $wallet_address"
# Call the command and store the result in a variable
output=$(spl-token accounts --output json-compact --owner "$wallet_address")
declare -a mint_addresses
declare -a token_names
declare -a balances
declare -a is_nft
index=0
# Extract all mint addresses for tokens owned by the wallet
owned_mints=$(echo "$output" | jq -r '.accounts[] | select(.tokenAmount.uiAmount > 0) | .mint')
# Check if owned_mints is not empty
if [ -z "$owned_mints" ]; then
echo "No tokens found in the wallet. Returning to the home screen."
return
fi
echo "--------------------------------------------------------------------------------"
echo "| Token Balances |"
echo "--------------------------------------------------------------------------------"
# Process each owned mint for tokens using process substitution
while IFS= read -r mint_address; do
token_info=$(grep -i "$mint_address" "$TOKENS_FILE")
if [ ! -z "$token_info" ]; then
token_name=$(echo "$token_info" | awk -F, '{print $2}')
balance=$(echo "$output" | jq -r --arg mint_address "$mint_address" '.accounts[] | select(.mint == $mint_address) | .tokenAmount.uiAmountString')
echo "$index. $token_name ($balance)"
mint_addresses[$index]=$mint_address
token_names[$index]="$token_name"
balances[$index]=$balance
index=$((index+1))
fi
done < <(echo "$owned_mints")
if [ $index -eq 0 ]; then
echo "No tokens found in the wallet."
return
fi
#read -p "Enter the number of the token you wish to send: " token_selection
echo "--------------------------------------------------------------------------------"
echo "Enter the number of the token you wish to send, or type 'home' to return to the home screen:"
read token_selection
# Check if user wants to return to the home screen
if [[ $token_selection == "home" ]]; then
echo "Returning to the home screen."