forked from valory-xyz/trader-quickstart
-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_service.sh
executable file
·1119 lines (944 loc) · 42.3 KB
/
run_service.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
# ------------------------------------------------------------------------------
#
# Copyright 2023-2024 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------
# Convert Hex to Dec
hex_to_decimal() {
$PYTHON_CMD -c "print(int('$1', 16))"
}
# Convert Wei to Dai
wei_to_dai() {
local wei="$1"
local decimal_precision=4 # Change this to your desired precision
local dai=$($PYTHON_CMD -c "print('%.${decimal_precision}f' % ($wei / 1000000000000000000.0))")
echo "$dai"
}
# Function to get the balance of an Ethereum address
get_balance() {
local address="$1"
curl -s -S -X POST \
-H "Content-Type: application/json" \
--data "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBalance\",\"params\":[\"$address\",\"latest\"],\"id\":1}" "$rpc" | \
$PYTHON_CMD -c "import sys, json; print(json.load(sys.stdin)['result'])"
}
# Function to ensure a minimum balance for an Ethereum address
ensure_minimum_balance() {
local address="$1"
local minimum_balance="$2"
local address_description="$3"
local token="${4:-"0x0000000000000000000000000000000000000000"}"
erc20_balance=0
if [ ! "$token" = "0x0000000000000000000000000000000000000000" ]
then
erc20_balance=$(poetry run python "../scripts/erc20_balance.py" "$token" "$address" "$rpc")
fi
balance_hex=$(get_balance "$address")
balance=$(hex_to_decimal "$balance_hex")
balance=$($PYTHON_CMD -c "print(int($balance) + int($erc20_balance))")
echo "Checking balance of $address_description (minimum required $(wei_to_dai "$minimum_balance") DAI):"
echo " - Address: $address"
echo " - Balance: $(wei_to_dai "$balance") DAI"
if [ "$($PYTHON_CMD -c "print($balance < $minimum_balance)")" == "True" ]; then
echo ""
echo " Please, fund address $address with at least $(wei_to_dai "$minimum_balance") DAI."
local spin='-\|/'
local i=0
local cycle_count=0
while [ "$($PYTHON_CMD -c "print($balance < $minimum_balance)")" == "True" ]; do
printf "\r Waiting... %s" "${spin:$i:1} "
i=$(((i + 1) % 4))
sleep .1
# This will be checked every 10 seconds (100 cycles).
cycle_count=$((cycle_count + 1))
if [ "$cycle_count" -eq 100 ]; then
balance_hex=$(get_balance "$address")
balance=$(hex_to_decimal "$balance_hex")
balance=$((erc20_balance+balance))
cycle_count=0
fi
done
printf "\r Waiting... \n"
echo ""
echo " - Updated balance: $(wei_to_dai "$balance") DAI"
fi
echo " OK."
echo ""
}
# ensure erc20 balance
ensure_erc20_balance() {
local address="$1"
local minimum_balance="$2"
local address_description="$3"
local token="$4"
local token_name="$5"
balance=0
if [ ! "$token" = "0x0000000000000000000000000000000000000000" ]
then
balance=$(poetry run python "../scripts/erc20_balance.py" "$token" "$address" "$rpc")
fi
echo "Checking balance of $address_description (minimum required $(wei_to_dai "$minimum_balance") $token_name):"
echo " - Address: $address"
echo " - Balance: $(wei_to_dai "$balance") $token_name"
if [ "$($PYTHON_CMD -c "print($balance < $minimum_balance)")" == "True" ]; then
echo ""
echo " Please, fund address $address with at least $(wei_to_dai "$minimum_balance") $token_name."
local spin='-\|/'
local i=0
local cycle_count=0
while [ "$($PYTHON_CMD -c "print($balance < $minimum_balance)")" == "True" ]; do
printf "\r Waiting... %s" "${spin:$i:1} "
i=$(((i + 1) % 4))
sleep .1
# This will be checked every 10 seconds (100 cycles).
cycle_count=$((cycle_count + 1))
if [ "$cycle_count" -eq 100 ]; then
balance=$(poetry run python "../scripts/erc20_balance.py" "$token" "$address" "$rpc")
cycle_count=0
fi
done
printf "\r Waiting... \n"
echo ""
echo " - Updated balance: $(wei_to_dai "$balance") $token_name"
fi
echo " OK."
echo ""
}
# Function to wait until service is in a certain state
ensure_rpc_reports_service_state() {
local service_id="$1"
local expected_state="$2"
local timeout=60
local start_time=$(date +%s)
local current_state="$(get_on_chain_service_state "$service_id")"
local spin='-\|/'
local i=0
local cycle_count=0
while [ "$current_state" != "$expected_state" ]; do
printf "\rWaiting for RPC to report Service %s in %s state... %s" "$service_id" "$expected_state" "${spin:$i:1} "
i=$(((i + 1) % 4))
sleep .1
# This will be checked every 5 seconds (50 cycles).
cycle_count=$((cycle_count + 1))
if [ "$cycle_count" -eq 50 ]; then
current_state="$(get_on_chain_service_state "$service_id")"
cycle_count=0
local current_time=$(date +%s)
local elapsed_time=$((current_time - start_time))
if [ "$elapsed_time" -ge "$timeout" ]; then
break
fi
fi
done
current_state="$(get_on_chain_service_state "$service_id")" # Update current state before final check
if [ "$current_state" == "$expected_state" ]; then
printf "\rWaiting for RPC to report Service %s in %s state... OK\n" "$service_id" "$expected_state"
else
printf "\rWaiting for RPC to report Service %s in %s state... Timeout after %s seconds.\n" "$service_id" "$expected_state" "$timeout"
fi
echo ""
}
# Get the address from a keys.json file
get_address() {
local keys_json_path="$1"
if [ ! -f "$keys_json_path" ]; then
echo "Error: $keys_json_path does not exist."
return 1
fi
address=$($PYTHON_CMD -c 'import json; print(json.load(open("'"$keys_json_path"'"))[0]["address"])')
echo -n "$address"
}
# Get the private key from a keys.json file
get_private_key() {
local keys_json_path="$1"
if [ ! -f "$keys_json_path" ]; then
echo "Error: $keys_json_path does not exist."
return 1
fi
private_key=$($PYTHON_CMD -c 'import json; print(json.load(open("'"$keys_json_path"'"))[0]["private_key"])')
private_key="${private_key#0x}"
echo -n "$private_key"
}
# Function to warm start the policy
warm_start() {
echo '["prediction-online", "prediction-online-sme", "prediction-online-summarized-info", "prediction-sentence-embedding-bold", "prediction-sentence-embedding-conservative"]' | sudo tee "$PWD/../$store/available_tools_store.json" > /dev/null
echo '{"counts": [0,0,0,0,0], "eps": 0.1, "rewards": [0.0,0.0,0.0,0.0,0.0]}' | sudo tee "$PWD/../$store/policy_store.json" > /dev/null
echo '{}' | sudo tee "$PWD/../$store/utilized_tools.json" > /dev/null
}
# Function to add a volume to a service in a Docker Compose file
add_volume_to_service() {
local compose_file="$1"
local service_name="$2"
local volume_name="$3"
local volume_path="$4"
# Check if the Docker Compose file exists
if [ ! -f "$compose_file" ]; then
echo "Docker Compose file '$compose_file' not found."
return 1
fi
# Check if the service exists in the Docker Compose file
if ! grep -q "^[[:space:]]*${service_name}:" "$compose_file"; then
echo "Service '$service_name' not found in '$compose_file'."
return 1
fi
if grep -q "^[[:space:]]*volumes:" "$compose_file"; then
awk -v volume_path="$volume_path" -v volume_name="$volume_name" '
/^ *volumes:/ {
found_volumes = 1
print
print " - " volume_path ":" volume_name ":Z"
next
}
1
' "$compose_file" > temp_compose_file
else
awk -v service_name="$service_name" -v volume_path="$volume_path" -v volume_name="$volume_name" '
/^ *'"$service_name"':/ {
found_service = 1
print
print " volumes:"
print " - " volume_path ":" volume_name ":Z"
next
}
/^ *$/ && found_service == 1 {
print " volumes:"
print " - " volume_path ":" volume_name ":Z"
found_service = 0
}
1
' "$compose_file" > temp_compose_file
fi
mv temp_compose_file "$compose_file"
}
# Function to retrieve on-chain service state (requires env variables set to use --use-custom-chain)
get_on_chain_service_state() {
local service_id="$1"
local service_info=$(poetry run autonomy service --use-custom-chain info "$service_id")
local state="$(echo "$service_info" | awk '/Service State/ {sub(/\|[ \t]*Service State[ \t]*\|[ \t]*/, ""); sub(/[ \t]*\|[ \t]*/, ""); print}')"
echo "$state"
}
# Asks if user wishes to use password-protected key files
ask_confirm_password() {
echo "Use a password?"
echo "---------------"
echo "You can use a password to encrypt the generated key files. You will be asked for the password each time the script is run."
while true; do
read -p "Do you want to use a password? (yes/no): " use_password
case "$use_password" in
[Yy]|[Yy][Ee][Ss])
echo "WARNING:"
echo " - Passwords are case-sensitive. Check your Caps Lock before continuing."
echo " - Passwords are not stored on disk."
echo " - If you lose your password, you will lose access to all assets associated to your operator or trader agent keys."
echo ""
while true; do
read -s -p "Enter your password: " password
echo ""
read -s -p "Confirm your password: " confirm_password
echo ""
if [ -z "$password" ]; then
echo "Password cannot be blank. Please try again."
elif [[ -n $(echo "-$password-" | awk '{ if(match($0, /[ \t]/)) print "contains_whitespace"; }') ]]; then
echo "Password cannot contain whitespace characters. Please try again."
elif [ ${#password} -lt 4 ]; then
echo "Password must be at least 4 characters long. Please try again."
elif [ "$password" = "$confirm_password" ]; then
use_password=true
password_argument="--password $password"
echo "Password confirmed. Please, store your pasword in a safe place."
read -n 1 -s -r -p "Press any key to continue..."
echo ""
echo ""
return 0
else
echo "Passwords do not match. Please try again."
fi
done
;;
[Nn]|[Nn][Oo])
use_password=false
password_argument=""
echo ""
return 0
;;
* )
echo "Please enter 'yes' or 'no'."
;;
esac
done
echo ""
return 0
}
# Asks password if key files are password-protected
ask_password_if_needed() {
agent_pkey=$(get_private_key "$keys_json_path")
if [[ "$agent_pkey" = *crypto* ]]; then
echo "Enter your password"
echo "-------------------"
echo "Your key files are protected with a password."
read -s -p "Please, enter your password: " password
use_password=true
password_argument="--password $password"
echo ""
else
echo "Your key files are not protected with a password."
use_password=false
password_argument=""
fi
echo ""
}
# Validates the provided password
validate_password() {
local is_password_valid_1=$(poetry run python ../scripts/is_keys_json_password_valid.py ../$keys_json_path $password_argument)
local is_password_valid_2=$(poetry run python ../scripts/is_keys_json_password_valid.py ../$operator_keys_file $password_argument)
if [ "$is_password_valid_1" != "True" ] || [ "$is_password_valid_2" != "True" ]; then
echo "Could not decrypt key files. Please verify if your key files are password-protected, and if the provided password is correct (passwords are case-sensitive)."
echo "Terminating the script."
exit 1
fi
}
# Function to retrieve the multisig address of a service
get_multisig_address() {
local service_id="$1"
local service_info=$(poetry run autonomy service --use-custom-chain info "$service_id")
local state="$(echo "$service_info" | awk '/Multisig Address/ {sub(/\|[ \t]*Multisig Address[ \t]*\|[ \t]*/, ""); sub(/[ \t]*\|[ \t]*/, ""); print}')"
echo "$state"
}
# stake or unstake a service
perform_staking_ops() {
local unstake="$1"
poetry run python "../scripts/staking.py" "$service_id" "$CUSTOM_SERVICE_REGISTRY_ADDRESS" "$CUSTOM_STAKING_ADDRESS" "../$operator_pkey_path" "$rpc" "$unstake" $password_argument
echo ""
}
# Prompt user for staking preference
prompt_use_staking() {
while true; do
echo "Use staking?"
echo "------------"
read -p "Do you want to stake this service? (yes/no): " use_staking
case "$use_staking" in
[Yy]|[Yy][Ee][Ss])
USE_STAKING="true"
break
;;
[Nn]|[Nn][Oo])
USE_STAKING="false"
break
;;
*)
echo "Please enter 'yes' or 'no'."
;;
esac
done
echo ""
}
# Verify if there are enough slots for staking this service
verify_staking_slots() {
if [ "${USE_STAKING}" = true ]; then
staking_slots=$(poetry run python "../scripts/get_available_staking_slots.py" "$CUSTOM_STAKING_ADDRESS" "$rpc")
if [ "$staking_slots" -le 0 ]; then
echo "All staking slots for contract $CUSTOM_STAKING_ADDRESS are taken. Your service cannot be staked."
echo "The script will finish."
exit 1
fi
fi
}
# Function to set or add a variable in the .env file and export it
dotenv_set_key() {
local dotenv_path="$1"
local key_to_set="$2"
local value_to_set="$3"
# Check if the .env file exists
if [ ! -f "$dotenv_path" ]; then
touch "$dotenv_path"
echo "Created $dotenv_path"
fi
# Check if the variable already exists in the .env file
if grep -q "^$key_to_set=" "$dotenv_path"; then
# Variable exists, so update its value using awk
awk -v key="$key_to_set" -v val="$value_to_set" '{gsub("^" key "=.*", key "=" val); print}' "$dotenv_path" > temp && mv temp "$dotenv_path"
echo "Updated '$key_to_set=$value_to_set' in $dotenv_path"
else
# Variable doesn't exist, so add it to the .env file
echo "$key_to_set=$value_to_set" >> "$dotenv_path"
echo "Added '$key_to_set=$value_to_set' to $dotenv_path"
fi
export "$key_to_set=$value_to_set"
}
store=".trader_runner"
env_file_path="$store/.env"
rpc_path="$store/rpc.txt"
operator_keys_file="$store/operator_keys.json"
operator_pkey_path="$store/operator_pkey.txt"
keys_json="keys.json"
keys_json_path="$store/$keys_json"
agent_pkey_path="$store/agent_pkey.txt"
agent_address_path="$store/agent_address.txt"
service_id_path="$store/service_id.txt"
service_safe_address_path="$store/service_safe_address.txt"
store_readme_path="$store/README.txt"
use_password=false
password_argument=""
zero_address="0x0000000000000000000000000000000000000000"
# Function to create the .trader_runner storage
create_storage() {
local rpc="$1"
echo "This is the first run of the script. The script will generate new operator and agent instance addresses."
echo ""
ask_confirm_password
# Prompt use staking
prompt_use_staking
verify_staking_slots
mkdir "../$store"
# Generate README.txt file
echo -e 'IMPORTANT:\n\n' \
' This folder contains crucial configuration information and autogenerated keys for your Trader agent.\n' \
' Please back up this folder and be cautious if you are modifying or sharing these files to avoid potential asset loss.' > "../$store_readme_path"
dotenv_set_key "../$env_file_path" "USE_STAKING" "$USE_STAKING"
AGENT_ID=14
dotenv_set_key "../$env_file_path" "AGENT_ID" "$AGENT_ID"
# Generate the RPC file
echo -n "$rpc" > "../$rpc_path"
# Generate the owner/operator's key
poetry run autonomy generate-key -n1 ethereum $password_argument
mv "$keys_json" "../$operator_keys_file"
operator_address=$(get_address "../$operator_keys_file")
operator_pkey=$(get_private_key "../$operator_keys_file")
echo -n "$operator_pkey" > "../$operator_pkey_path"
echo "Your operator's autogenerated public address: $operator_address"
echo "(The same address will be used as the service owner.)"
# Generate the agent's key
poetry run autonomy generate-key -n1 ethereum $password_argument
mv "$keys_json" "../$keys_json_path"
agent_address=$(get_address "../$keys_json_path")
agent_pkey=$(get_private_key "../$keys_json_path")
echo -n "$agent_pkey" > "../$agent_pkey_path"
echo -n "$agent_address" > "../$agent_address_path"
echo "Your agent instance's autogenerated public address: $agent_address"
echo ""
}
# Function to read and load the .trader_runner storage information if it exists.
# Also sets `first_run` flag to identify whether we are running the script for the first time.
try_read_storage() {
if [ -d $store ]; then
# INFO: This is a fix to avoid corrupting already-created stores
if [ ! -f "$env_file_path" ]; then
touch "$env_file_path"
fi
# INFO: This is a fix to avoid corrupting already-created stores
if [[ -f "$operator_keys_file" && ! -f "$operator_pkey_path" ]]; then
operator_pkey=$(get_private_key "$operator_keys_file")
echo -n "$operator_pkey" > "$operator_pkey_path"
fi
# INFO: This is a fix to avoid corrupting already-created stores
if [[ -f "$keys_json_path" && ! -f "$agent_pkey_path" ]]; then
agent_pkey=$(get_private_key "$keys_json_path")
echo -n "$agent_pkey" > "$agent_pkey_path"
fi
first_run=false
paths="$env_file_path $rpc_path $operator_keys_file $operator_pkey_path $keys_json_path $agent_address_path $agent_pkey_path $service_id_path"
for file in $paths; do
if ! [ -f "$file" ]; then
if [ "$file" != $service_safe_address_path ] && [ "$file" != $service_id_path ]; then
echo "The runner's store is corrupted!"
echo "Please manually investigate the $store folder"
echo "Make sure that you do not lose your keys or any other important information!"
exit 1
fi
fi
done
unset USE_STAKING
unset AGENT_ID
source "$env_file_path"
rpc=$(cat $rpc_path)
agent_address=$(cat $agent_address_path)
operator_address=$(get_address "$operator_keys_file")
if [ -f "$service_id_path" ]; then
service_id=$(cat $service_id_path)
fi
# INFO: This is a fix to avoid corrupting already-created stores
if [ -z "$USE_STAKING" ]; then
prompt_use_staking
dotenv_set_key "$env_file_path" "USE_STAKING" "$USE_STAKING"
fi
# INFO: This is a fix to avoid corrupting already-created stores
if [ -z "$AGENT_ID" ]; then
AGENT_ID=14
dotenv_set_key "$env_file_path" "AGENT_ID" "$AGENT_ID"
fi
ask_password_if_needed
else
first_run=true
fi
}
# ------------------
# Script starts here
# ------------------
set -e # Exit script on first error
# Initialize repo and version variables
org_name="valory-xyz"
open_autonomy_author="valory"
directory="trader"
service_repo=https://github.com/$org_name/$directory.git
# This is a tested version that works well.
# Feel free to replace this with a different version of the repo, but be careful as there might be breaking changes
service_version="v0.15.2"
# Define constants for on-chain interaction
gnosis_chain_id=100
n_agents=1
olas_balance_required_to_bond=10000000000000000000
olas_balance_required_to_stake=10000000000000000000
xdai_balance_required_to_bond=10000000000000000
suggested_top_up_default=50000000000000000
suggested_safe_top_up_default=500000000000000000
export RPC_RETRIES=40
export RPC_TIMEOUT_SECONDS=120
export CUSTOM_SERVICE_MANAGER_ADDRESS="0x04b0007b2aFb398015B76e5f22993a1fddF83644"
export CUSTOM_SERVICE_REGISTRY_ADDRESS="0x9338b5153AE39BB89f50468E608eD9d764B755fD"
export CUSTOM_STAKING_ADDRESS="0x43fB32f25dce34EB76c78C7A42C8F40F84BCD237"
export CUSTOM_OLAS_ADDRESS="0xcE11e14225575945b8E6Dc0D4F2dD4C570f79d9f"
export CUSTOM_SERVICE_REGISTRY_TOKEN_UTILITY_ADDRESS="0xa45E64d13A30a51b91ae0eb182e88a40e9b18eD8"
export CUSTOM_GNOSIS_SAFE_PROXY_FACTORY_ADDRESS="0x3C1fF68f5aa342D296d4DEe4Bb1cACCA912D95fE"
export CUSTOM_GNOSIS_SAFE_SAME_ADDRESS_MULTISIG_ADDRESS="0x6e7f594f680f7aBad18b7a63de50F0FeE47dfD06"
export CUSTOM_MULTISEND_ADDRESS="0x40A2aCCbd92BCA938b02010E17A5b8929b49130D"
export WXDAI_ADDRESS="0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"
export MECH_CONTRACT_ADDRESS="0x77af31De935740567Cf4fF1986D04B2c964A786a"
# check if USE_NEVERMINED is set to true
if [ "$USE_NEVERMINED" == "true" ];
then
echo "A Nevermined subscription will be used to pay for the mech requests."
export MECH_CONTRACT_ADDRESS="0x327E26bDF1CfEa50BFAe35643B23D5268E41F7F9"
export AGENT_REGISTRY_ADDRESS="0xAed729d4f4b895d8ca84ba022675bB0C44d2cD52"
export MECH_REQUEST_PRICE=0
fi
sleep_duration=12
echo ""
echo "---------------"
echo " Trader runner "
echo "---------------"
echo ""
echo "This script will assist you in setting up and running the Trader service ($service_repo)."
echo ""
# Check the command-line arguments
while [[ "$#" -gt 0 ]]; do
case $1 in
--with-staking)
echo "WARNING: the flag '--with-staking' is deprecated"
echo "------------------------------------------------"
echo "Instead, the value is stored in the '$store' folder. You will be prompted in case the value has not been set."
read -n 1 -s -r -p "Press any key to continue..."
echo ""
echo ""
;;
*) echo "Unknown parameter: $1" ;;
esac
shift
done
# Check if user is inside a venv
if [[ "$VIRTUAL_ENV" != "" ]]
then
echo "Please exit the virtual environment!"
exit 1
fi
# Check dependencies
if command -v python3 >/dev/null 2>&1; then
PYTHON_CMD="python3"
python3 scripts/check_python.py
elif command -v python >/dev/null 2>&1; then
PYTHON_CMD="python"
python scripts/check_python.py
else
echo >&2 "Python is not installed!";
exit 1
fi
command -v git >/dev/null 2>&1 ||
{ echo >&2 "Git is not installed!";
exit 1
}
command -v poetry >/dev/null 2>&1 ||
{ echo >&2 "Poetry is not installed!";
exit 1
}
command -v docker >/dev/null 2>&1 ||
{ echo >&2 "Docker is not installed!";
exit 1
}
docker rm -f abci0 node0 trader_abci_0 trader_tm_0 &> /dev/null ||
{ echo >&2 "Docker is not running!";
exit 1
}
try_read_storage
# Prompt for RPC
[[ -z "${rpc}" ]] && read -rsp "Enter a Gnosis RPC that supports eth_newFilter [hidden input]: " rpc && echo || rpc="${rpc}"
# Check the RPC
echo "Checking the provided RCP..."
rcp_response=$(curl -s -S -X POST \
-H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0","method":"eth_newFilter","params":["invalid"],"id":1}' "$rpc")
rcp_error_message=$(echo "$rcp_response" | \
$PYTHON_CMD -c "import sys, json;
try: print(json.load(sys.stdin)['error']['message'])
except Exception as e: print('Exception processing RCP response')")
rcp_exception=$([[ "$rcp_error_message" == "Exception processing RCP response" ]] && echo true || echo false)
if [ "$rcp_exception" = true ]; then
echo "Error: The received RCP response is malformed. Please verify the RPC address and/or RCP behavior."
echo " Received response:"
echo " $rcp_response"
echo ""
echo "Terminating script."
exit 1
fi
rcp_out_of_requests=$([[ "$rcp_error_message" == "Out of requests" ]] && echo true || echo false)
if [ "$rcp_out_of_requests" = true ]; then
echo "Error: The provided RCP is out of requests."
echo "Terminating script."
exit 1
fi
rcp_new_filter_supported=$([[ "$rcp_error_message" == "The method eth_newFilter does not exist/is not available" ]] && echo false || echo true)
if [ "$rcp_new_filter_supported" = false ]; then
echo "Error: The provided RPC does not support 'eth_newFilter'."
echo "Terminating script."
exit 1
fi
echo "RPC checks passed."
echo ""
echo "------------------------------"
echo "Setting up '$directory' repository"
echo "------------------------------"
echo ""
if [ -d "$directory" ]; then
current_version=$(git --git-dir="$directory/.git" describe --tags --always)
if [ "$current_version" != "$service_version" ]; then
echo "Current version of $directory ($current_version) does not match expected version ($service_version)."
echo "Removing '$directory' directory..."
echo ""
sudo rm -rf "$directory"
fi
fi
if [ ! -d "$directory" ]; then
echo "Cloning '$directory' repo from '$org_name' GitHub..."
echo ""
git clone --depth 1 --branch $service_version $service_repo
fi
cd $directory
if [ "$(git rev-parse --is-inside-work-tree)" = true ]
then
poetry install
poetry run autonomy packages sync
poetry run autonomy init --reset --author $open_autonomy_author --remote --ipfs --ipfs-node "/dns/registry.autonolas.tech/tcp/443/https"
poetry add tqdm
else
echo "$directory is not a git repo!"
exit 1
fi
# Setup the minting tool
export CUSTOM_CHAIN_RPC=$rpc
export CUSTOM_CHAIN_ID=$gnosis_chain_id
if [ "$first_run" = "true" ]
then
create_storage "$rpc"
fi
validate_password
echo ""
echo "-----------------------------------------"
echo "Checking Autonolas Protocol service state"
echo "-----------------------------------------"
# We set by default AGENT_ID=14. In Everest the AGENT_ID was 12.
# This script does not allow to stake on Everest anymore, therefore
# all stores must be correctly updated with AGENT_ID=14.
AGENT_ID=14
dotenv_set_key "../$env_file_path" "AGENT_ID" "$AGENT_ID"
if [ -z ${service_id+x} ]; then
# Check balances
suggested_amount=$suggested_top_up_default
ensure_minimum_balance "$operator_address" $suggested_amount "owner/operator's address"
echo "[Service owner] Minting your service on the Gnosis chain..."
verify_staking_slots
# create service
nft="bafybeig64atqaladigoc3ds4arltdu63wkdrk3gesjfvnfdmz35amv7faq"
cmd="poetry run autonomy mint \
--retries $RPC_RETRIES \
--timeout $RPC_TIMEOUT_SECONDS \
--use-custom-chain \
service packages/valory/services/$directory/ \
--key \"../$operator_pkey_path\" $password_argument\
--nft $nft \
-a $AGENT_ID \
-n $n_agents \
--threshold $n_agents"
if [ "${USE_STAKING}" = true ]; then
cost_of_bonding=$olas_balance_required_to_bond
cmd+=" -c $cost_of_bonding --token $CUSTOM_OLAS_ADDRESS"
else
cost_of_bonding=$xdai_balance_required_to_bond
cmd+=" -c $cost_of_bonding"
fi
service_id=$(eval $cmd)
# parse only the id from the response
service_id="${service_id##*: }"
# validate id
if ! [[ "$service_id" =~ ^[0-9]+$ || "$service_id" =~ ^[-][0-9]+$ ]]
then
echo "Service minting failed: $service_id"
exit 1
fi
ensure_rpc_reports_service_state $service_id "PRE_REGISTRATION"
echo -n "$service_id" > "../$service_id_path"
fi
# Update the on-chain service if outdated
packages="packages/packages.json"
local_service_hash="$(grep 'service/valory/trader' $packages | awk -F: '{print $2}' | tr -d '", ' | head -n 1)"
remote_service_hash=$(poetry run python "../scripts/service_hash.py")
operator_address=$(get_address "../$operator_keys_file")
if [ "$local_service_hash" != "$remote_service_hash" ]; then
echo ""
echo "WARNING: Your on-chain service configuration is out-of-date"
echo "-----------------------------------------------------------"
echo "Your currently minted on-chain service (id $service_id) mismatches the local trader service ($service_version):"
echo " - Local service hash ($service_version): $local_service_hash"
echo " - On-chain service hash (id $service_id): $remote_service_hash"
echo ""
echo "This is most likely caused due to an update of the trader service code."
echo "The script will proceed now to update the on-chain service."
echo "The operator and agent addresses need to have enough funds to complete the process."
echo ""
response="y"
if [ "${USE_STAKING}" = true ]; then
echo "Your service is in a staking program. Updating your on-chain service requires that it is first unstaked."
echo "Unstaking your service will retrieve the accrued staking rewards."
echo ""
echo "Do you want to continue updating your service? (yes/no)"
read -r response
echo ""
fi
if [[ ! "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
echo "Skipping on-chain service update."
else
# unstake the service
if [ "${USE_STAKING}" = true ]; then
perform_staking_ops true
fi
# Check balances
suggested_amount=$suggested_top_up_default
ensure_minimum_balance "$operator_address" $suggested_amount "owner/operator's address"
suggested_amount=$suggested_top_up_default
ensure_minimum_balance $agent_address $suggested_amount "agent instance's address"
echo "------------------------------"
echo "Updating on-chain service $service_id"
echo "------------------------------"
echo ""
echo "PLEASE, DO NOT INTERRUPT THIS PROCESS."
echo ""
echo "Cancelling the on-chain service update prematurely could lead to an inconsistent state of the Safe or the on-chain service state, which may require manual intervention to resolve."
echo ""
service_safe_address=$(<"../$service_safe_address_path")
current_safe_owners=$(poetry run python "../scripts/get_safe_owners.py" "$service_safe_address" "../$agent_pkey_path" "$rpc" $password_argument | awk '{gsub(/"/, "\047", $0); print $0}')
# transfer the ownership of the Safe from the agent to the service owner
# (in a live service, this should be done by sending a 0 DAI transfer to its Safe)
if [[ "$(get_on_chain_service_state "$service_id")" == "DEPLOYED" && "$current_safe_owners" == "['$agent_address']" ]]; then
echo "[Agent instance] Swapping Safe owner..."
poetry run python "../scripts/swap_safe_owner.py" "$service_safe_address" "../$agent_pkey_path" "$operator_address" "$rpc" $password_argument
fi
# terminate current service
if [ "$(get_on_chain_service_state "$service_id")" == "DEPLOYED" ]; then
echo "[Service owner] Terminating on-chain service $service_id..."
poetry run autonomy service \
--retries $RPC_RETRIES \
--timeout $RPC_TIMEOUT_SECONDS \
--use-custom-chain \
terminate "$service_id" \
--key "../$operator_pkey_path" $password_argument
ensure_rpc_reports_service_state $service_id "TERMINATED_BONDED"
fi
# unbond current service
if [ "$(get_on_chain_service_state "$service_id")" == "TERMINATED_BONDED" ]; then
echo "[Operator] Unbonding on-chain service $service_id..."
poetry run autonomy service \
--retries $RPC_RETRIES \
--timeout $RPC_TIMEOUT_SECONDS \
--use-custom-chain \
unbond "$service_id" \
--key "../$operator_pkey_path" $password_argument
ensure_rpc_reports_service_state $service_id "PRE_REGISTRATION"
fi
# update service
if [ "$(get_on_chain_service_state "$service_id")" == "PRE_REGISTRATION" ]; then
echo "[Service owner] Updating on-chain service $service_id..."
verify_staking_slots
nft="bafybeig64atqaladigoc3ds4arltdu63wkdrk3gesjfvnfdmz35amv7faq"
export cmd=""
if [ "${USE_STAKING}" = true ]; then
cost_of_bonding=$olas_balance_required_to_bond
poetry run python "../scripts/update_service.py" "../$operator_pkey_path" "$nft" "$AGENT_ID" "$service_id" "$CUSTOM_OLAS_ADDRESS" "$cost_of_bonding" "packages/valory/services/trader/" "$rpc" $password_argument
else
cost_of_bonding=$xdai_balance_required_to_bond
cmd="poetry run autonomy mint \
--retries $RPC_RETRIES \
--timeout $RPC_TIMEOUT_SECONDS \
--use-custom-chain \
service packages/valory/services/trader/ \
--key \"../$operator_pkey_path\" $password_argument \
--nft $nft \
-a $AGENT_ID \
-n $n_agents \
-c $cost_of_bonding \
--threshold $n_agents \
--update \"$service_id\""
fi
eval "$cmd"
# Updating a service does not change the on-chain service state.
# Therefore, we add a sleep as precaution.
sleep $sleep_duration
ensure_rpc_reports_service_state $service_id "PRE_REGISTRATION"
fi
echo ""
echo "Finished updating on-chain service $service_id."
fi
fi
echo ""
echo "Ensuring on-chain service $service_id is in DEPLOYED state..."
if [ "$(get_on_chain_service_state "$service_id")" != "DEPLOYED" ]; then
suggested_amount=25000000000000000
ensure_minimum_balance "$operator_address" $suggested_amount "owner/operator's address"
fi
# activate service
if [ "$(get_on_chain_service_state "$service_id")" == "PRE_REGISTRATION" ]; then
echo "[Service owner] Activating registration for on-chain service $service_id..."
export cmd="poetry run autonomy service --retries $RPC_RETRIES --timeout $RPC_TIMEOUT_SECONDS --use-custom-chain activate --key "../$operator_pkey_path" $password_argument "$service_id""
if [ "${USE_STAKING}" = true ]; then
minimum_olas_balance=$($PYTHON_CMD -c "print(int($olas_balance_required_to_bond) + int($olas_balance_required_to_stake))")
echo "Your service is using staking. Therefore, you need to provide a total of $(wei_to_dai "$minimum_olas_balance") OLAS to your owner/operator's address."
echo " $(wei_to_dai "$olas_balance_required_to_bond") OLAS for security deposit (service owner)"
echo " +"
echo " $(wei_to_dai "$olas_balance_required_to_stake") OLAS for slashable bond (operator)."
echo ""
ensure_erc20_balance "$operator_address" $minimum_olas_balance "owner/operator's address" $CUSTOM_OLAS_ADDRESS "OLAS"
verify_staking_slots
cmd+=" --token $CUSTOM_OLAS_ADDRESS"
fi
eval "$cmd"
ensure_rpc_reports_service_state $service_id "ACTIVE_REGISTRATION"
fi
# register agent instance
if [ "$(get_on_chain_service_state "$service_id")" == "ACTIVE_REGISTRATION" ]; then
echo "[Operator] Registering agent instance for on-chain service $service_id..."
export cmd="poetry run autonomy service --retries $RPC_RETRIES --timeout $RPC_TIMEOUT_SECONDS --use-custom-chain register --key "../$operator_pkey_path" $password_argument "$service_id" -a $AGENT_ID -i "$agent_address""
if [ "${USE_STAKING}" = true ]; then
cmd+=" --token $CUSTOM_OLAS_ADDRESS"
fi
eval "$cmd"
ensure_rpc_reports_service_state $service_id "FINISHED_REGISTRATION"
fi
# deploy on-chain service
service_state="$(get_on_chain_service_state "$service_id")"