Skip to content

Commit e4c1276

Browse files
authored
Merge pull request #71 from Gearbox-protocol/v3
v3 logic
2 parents 65e7a0e + f875971 commit e4c1276

File tree

179 files changed

+6705
-2674
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

179 files changed

+6705
-2674
lines changed

cmd/account_mining/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ func StartServer(lc fx.Lifecycle, client core.ClientI, config *config.Config) {
127127
lc.Append(fx.Hook{
128128
OnStart: func(context.Context) error {
129129
go func() {
130-
contractETH, err := addressProvider.NewAddressProvider(common.HexToAddress(config.AddressProviderAddress), client)
130+
contractETH, err := addressProvider.NewAddressProvider(common.HexToAddress(config.AddressProviderAddrs), client)
131131
log.CheckFatal(err)
132132
gearToken, err := contractETH.GetGearToken(&bind.CallOpts{})
133133
log.CheckFatal(err)

cmd/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func StartServer(lc fx.Lifecycle, engine ds.EngineI, cfg *config.Config, client
5353
// In production, we'd want to separate the Listen and Serve phases for
5454
// better error-handling.
5555
go func() {
56-
engine.UseThreads()
56+
// engine.UseThreads()
5757
engine.SyncHandler()
5858
}()
5959
return nil

config/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import "github.com/Gearbox-protocol/sdk-go/log"
44

55
type Config struct {
66
// Authentication
7-
AddressProviderAddress string `env:"REACT_APP_ADDRESS_PROVIDER" validate:"required"`
7+
AddressProviderAddrs string `env:"REACT_APP_ADDRESS_PROVIDER" validate:"required"`
88

99
// Database
1010
DatabaseUrl string `env:"DATABASE_URL" validate:"required"`
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
set -e
2+
3+
PARENT_DIR=$(dirname $0)
4+
MAINNET_IP=$1
5+
PROXY_IP=$2
6+
SUPERUSER=$3
7+
8+
FORK_BLOCK=`jq .forkBlock < <(curl https://anvil.gearbox.foundation/forks/432945bc-3620-11ee-be56-0242ac120002 )`
9+
10+
if [ "$PROXY_IP" = '' ]; then
11+
ssh -t debian@$MAINNET_IP "bash /home/debian/db_copy.sh"
12+
scp debian@$MAINNET_IP:/tmp/db.sql /tmp/db.sql
13+
else
14+
ssh -t root@$PROXY_IP 'ssh -t debian@'$MAINNET_IP' "bash /home/debian/db_copy.sh"'
15+
ssh -t root@$PROXY_IP 'scp debian@'$MAINNET_IP':/tmp/db.sql /tmp/db.sql'
16+
scp root@$PROXY_IP:/tmp/db.sql /tmp/db.sql
17+
fi
18+
19+
if [ "$SUPERUSER" = "postgres" ]; then
20+
sudo su postgres
21+
fi
22+
23+
24+
if [ "$SUPERUSER" = "debian" ]; then
25+
export TDB="postgres://$SUPERUSER:123Sample@localhost:5432/sample?sslmode=disable"
26+
else
27+
export TDB="postgres://$SUPERUSER@localhost:5432/sample?sslmode=disable"
28+
fi
29+
30+
set +e
31+
psql -U $SUPERUSER -d postgres -c 'drop database sample'
32+
psql -U $SUPERUSER -d postgres -c 'create database sample'
33+
psql -U $SUPERUSER -d sample < /tmp/db.sql
34+
set -e
35+
36+
# psql -U $SUPERUSER -d sample < db_scripts/local_testing/missing_table_from_download_db.sql
37+
psql -U $SUPERUSER -d sample < $PARENT_DIR/../../migrations/000016_rankings.up.sql
38+
migrate -path $PARENT_DIR/../../migrations/ -database "$TDB" up
39+
40+
41+
psql -U $SUPERUSER -d sample < <(cat $PARENT_DIR/reset_to_blocknum.sql | sed "s/18246321/$FORK_BLOCK/" )
42+
set -e
43+
psql -U $SUPERUSER -d postgres -c 'drop database tmp_sample'
44+
set +e
45+
createdb -O $SUPERUSER -T sample tmp_sample
46+
47+
# create user sample with encrypted password '123Sample';
48+
# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO sample;
49+
# ALTER DATABASE sample OWNER TO sample;
50+
# update schema_migrations set version=27, dirty='f';
51+
#
52+
# SELECT format(
53+
# 'ALTER TABLE public.%I OWNER TO sample',
54+
# table_name
55+
# )
56+
# FROM information_schema.tables
57+
# WHERE table_schema = 'public';
58+
59+
# SELECT * FROM information_schema.tables WHERE table_schema = 'public';

db_scripts/local_testing/local_db_copy.sql renamed to db_scripts/local_testing/missing_table_from_download_db.sql

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,14 @@ CREATE TABLE current_debts (
3737
profit_underlying DOUBLE PRECISION,
3838
collateral_usd DOUBLE PRECISION,
3939
collateral_underlying DOUBLE PRECISION,
40+
--
41+
total_value_usd double precision,
42+
tf_index double precision,
43+
--
4044
repay_amount DOUBLE PRECISION,
4145
repay_amount_bi varchar(80));
4246

4347
ALTER TABLE ONLY current_debts
44-
ADD CONSTRAINT current_debts_block_num_fkey FOREIGN KEY (block_num) REFERENCES blocks(id) ON DELETE CASCADE;
48+
ADD CONSTRAINT current_debts_block_num_fkey FOREIGN KEY (block_num) REFERENCES blocks(id) ON DELETE CASCADE;
49+
50+
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
delete from account_operations where block_num>18246321;
2+
delete from allowed_protocols where block_num>18246321;
3+
delete from allowed_tokens where block_num>18246321;
4+
delete from credit_manager_stats where block_num>18246321;
5+
delete from credit_session_snapshots where block_num>18246321;
6+
delete from dao_operations where block_num> 18246321;
7+
delete from blocks where id > 18246321;
8+
9+
10+
delete from debts where block_num> 18246321;
11+
update debt_sync set last_calculated_at=18246321;
12+
delete from token_oracle where block_num> 18246321;
13+
delete from transfer_account_allowed where block_num> 18246321;
14+
delete from no_session_transfers where block_num> 18246321;
15+
delete from fast_check_params where block_num> 18246321;
16+
delete from parameters where block_num> 18246321;
17+
delete from pool_stats where block_num> 18246321;
18+
delete from pool_ledger where block_num> 18246321;
19+
delete from current_debts where block_num > 18246321;
20+
delete from liquidable_accounts where block_num> 18246321; -- doesn't matter if it is closed or open
21+
delete from token_ltramp where block_num> 18246321;
22+
delete from quota_details where block_num> 18246321;
23+
24+
-- a
25+
update sync_adapters set last_sync = 18246321 where type in ('CreditConfigurator', 'AccountManager','CreditFilter', 'CreditManager', 'Pool') and last_sync > 18246321;
26+
--
27+
delete from credit_sessions where since> 18246321;
28+
update credit_sessions set closed_at=0,liquidator='', remaining_funds='0', close_transfers='{}',status=0 where closed_at> 18246321;
29+
30+
-- the borrower is not accounted for ; i.e. transfer of acocunt is not handled and should be used carefully
31+
update credit_sessions cs set borrowed_amount=css.borrowed_amount_bi, balances=css.balances from (select distinct on(session_id) * from credit_session_snapshots order by session_id, block_num desc) css where css.session_id=cs.id and cs.status=0;
32+
33+
-- for creditmanager
34+
35+
update credit_managers cm set
36+
opened_accounts_count=cms.opened_accounts_count,
37+
total_opened_accounts=cms.total_opened_accounts,
38+
total_repaid_accounts=cms.total_repaid_accounts,
39+
total_closed_accounts=cms.total_closed_accounts,
40+
total_liquidated_accounts=cms.total_liquidated_accounts,
41+
total_borrowed_bi=cms.total_borrowed_bi,
42+
cumulative_borrowed_bi=cms.cumulative_borrowed_bi,
43+
total_repaid_bi=cms.total_repaid_bi,
44+
total_losses_bi=cms.total_losses_bi,
45+
total_profit_bi=cms.total_profit_bi,
46+
total_borrowed=cms.total_borrowed,
47+
cumulative_borrowed=cms.cumulative_borrowed,
48+
total_repaid=cms.total_repaid,
49+
total_losses=cms.total_losses,
50+
total_profit=cms.total_profit,
51+
unique_users=cms.unique_users from (select distinct on (credit_manager) * from credit_manager_stats order by credit_manager, block_num desc) cms
52+
where cm.address= cms.credit_manager;
53+
54+
55+
56+
57+
delete from price_feeds where block_num > 18246321;
58+
delete from token_oracle where block_num > 18246321;
59+
update sync_adapters set last_sync=18246321 where type in ('PriceOracle', 'ChainlinkPriceFeed', 'CompositeChainlinkPF', 'QueryPriceFeed');
60+
update sync_adapters set last_sync=18246321 where type in ('AddressProvider', 'ACL', 'AccountFactory');
61+
delete from rebase_details where block_num > 18246321;
62+
63+
64+
65+
update sync_adapters set last_sync=18246321 where type in ('ContractRegister', 'ACL');
66+
delete from debts where block_num > 18246321;
67+
delete from current_debts where block_num > 18246321;
68+
update debt_sync set last_calculated_at=18246321;
69+
----
70+
71+
-- sync adapter for treasury is not updated.
72+
-- tokens and token_current_price, schema_migrations not are needed to be updated.
73+
-- faucet and operations are reduntant tables.
74+
-- gear_balances , no need to udpate as GearToken syncadpater is not updated.
75+
-- PooLMReward syncadapter is for table diesel_transfers, lm_rewards, diesel_balances.
76+
77+
78+
-- ALTER DATABASE gearbox RENAME TO old_gearbox;
79+
-- ALTER DATABASE sample RENAME TO gearbox;
80+
-- createdb -O sample -T sample tmp_sample

db_scripts/reset_to_blocknum.sql

Lines changed: 0 additions & 71 deletions
This file was deleted.

debts/calc_details.go

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,32 @@ import (
55

66
"github.com/Gearbox-protocol/sdk-go/core"
77
"github.com/Gearbox-protocol/sdk-go/core/schemas"
8+
"github.com/Gearbox-protocol/sdk-go/core/schemas/schemas_v3"
9+
"github.com/Gearbox-protocol/third-eye/ds"
810
)
911

1012
type sessionDetailsForCalc struct {
13+
addr string
1114
*schemas.CreditSessionSnapshot
1215
CM string
1316
rebaseDetails *schemas.RebaseDetailsForDB
1417
stETH string
18+
// for v3
19+
forQuotas v3DebtDetails
20+
version core.VersionType
21+
}
22+
23+
func (s sessionDetailsForCalc) GetAddr() string {
24+
return s.addr
1525
}
1626

1727
func (s sessionDetailsForCalc) GetCM() string {
1828
return s.CM
1929
}
20-
func (s sessionDetailsForCalc) GetBalances() map[string]core.BalanceType {
30+
func (s sessionDetailsForCalc) GetBalances() core.DBBalanceFormat {
2131
// credit session snapshot is not saved to db , so we can use it.
2232
schemas.AdjustRebaseToken(*s.Balances, s.stETH, s.rebaseDetails)
23-
return s.Balances.ToBalanceType()
33+
return *s.Balances
2434
}
2535

2636
func (s sessionDetailsForCalc) GetBorrowedAmount() *big.Int {
@@ -29,6 +39,13 @@ func (s sessionDetailsForCalc) GetBorrowedAmount() *big.Int {
2939
func (s sessionDetailsForCalc) GetCumulativeIndex() *big.Int {
3040
return s.СumulativeIndexAtOpen.Convert()
3141
}
42+
func (s sessionDetailsForCalc) GetVersion() core.VersionType {
43+
return s.version
44+
}
45+
46+
func (s sessionDetailsForCalc) GetQuotaCumInterestAndFees() (*big.Int, *big.Int) {
47+
return s.CumulativeQuotaInterest.Convert(), s.QuotaFees.Convert()
48+
}
3249

3350
type storeForCalc struct {
3451
inner *DebtEngine
@@ -41,6 +58,28 @@ func (s storeForCalc) GetPrices(token string, version core.VersionType, blockNum
4158
return s.inner.GetTokenLastPrice(token, version)
4259
}
4360

44-
func (s storeForCalc) GetLiqThreshold(cm, token string) *big.Int {
61+
func (s storeForCalc) GetLiqThreshold(ts uint64, cm, token string) *big.Int {
62+
if ltRamp := s.inner.tokenLTRamp[cm][token]; ltRamp != nil {
63+
return ltRamp.GetLTForTs(ts)
64+
}
4565
return s.inner.allowedTokensThreshold[cm][token].Convert()
4666
}
67+
68+
type poolDetailsForCalc struct {
69+
cumIndexAndUToken *ds.CumIndexAndUToken
70+
forQuotas v3DebtDetails
71+
}
72+
73+
func (s poolDetailsForCalc) GetUnderlying() string {
74+
return s.cumIndexAndUToken.Token
75+
}
76+
77+
func (s poolDetailsForCalc) getPool() string {
78+
return s.cumIndexAndUToken.PoolAddr
79+
}
80+
func (s poolDetailsForCalc) GetPoolQuotaDetails() map[string]*schemas_v3.QuotaDetails {
81+
return s.forQuotas.poolQuotaDetails[s.getPool()]
82+
}
83+
func (s poolDetailsForCalc) GetCumIndexNow() *big.Int {
84+
return s.cumIndexAndUToken.CumulativeIndex
85+
}

debts/debt_db.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,16 @@ import (
1111
"gorm.io/gorm/clause"
1212
)
1313

14+
// checks
1415
func (eng *DebtEngine) liquidationCheck(debt *schemas.Debt, cmAddr, borrower string, token *ds.CumIndexAndUToken) {
1516
lastDebt := eng.lastDebts[debt.SessionId]
17+
var sendMsgAfterXBlocks int64 = 20
18+
1619
if lastDebt != nil {
1720
if !core.IntGreaterThanEqualTo(lastDebt.CalHealthFactor, 10000) &&
1821
core.IntGreaterThanEqualTo(debt.CalHealthFactor, 10000) {
1922
if eng.liquidableBlockTracker[debt.SessionId] != nil &&
20-
(debt.BlockNumber-eng.liquidableBlockTracker[debt.SessionId].BlockNum) >= 20 {
23+
(debt.BlockNumber-eng.liquidableBlockTracker[debt.SessionId].BlockNum) >= sendMsgAfterXBlocks {
2124
eng.repo.RecentMsgf(log.RiskHeader{
2225
BlockNumber: debt.BlockNumber,
2326
EventCode: "AMQP",
@@ -34,7 +37,6 @@ func (eng *DebtEngine) liquidationCheck(debt *schemas.Debt, cmAddr, borrower str
3437
eng.addLiquidableAccount(debt.SessionId, debt.BlockNumber)
3538
}
3639
}
37-
var sendMsgAfterXBlocks int64 = 20
3840
// sent the account is liquidable notification after 20 blocks
3941
if !core.IntGreaterThanEqualTo(debt.CalHealthFactor, 10000) &&
4042
eng.liquidableBlockTracker[debt.SessionId] != nil &&

0 commit comments

Comments
 (0)