code.vegaprotocol.io/vega@v0.79.0/core/integration/steps/market/margin_calculators.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package market 17 18 import ( 19 "embed" 20 "fmt" 21 22 "code.vegaprotocol.io/vega/core/integration/steps/helpers" 23 "code.vegaprotocol.io/vega/core/integration/steps/market/defaults" 24 types "code.vegaprotocol.io/vega/protos/vega" 25 26 "github.com/jinzhu/copier" 27 ) 28 29 var ( 30 //go:embed defaults/margin-calculator/*.json 31 defaultMarginCalculators embed.FS 32 defaultMarginCalculatorFileNames = []string{ 33 "defaults/margin-calculator/default-margin-calculator.json", 34 "defaults/margin-calculator/default-capped-margin-calculator.json", 35 "defaults/margin-calculator/default-overkill-margin-calculator.json", 36 } 37 ) 38 39 type marginCalculators struct { 40 config map[string]*types.MarginCalculator 41 } 42 43 func newMarginCalculators(unmarshaler *defaults.Unmarshaler) *marginCalculators { 44 config := &marginCalculators{ 45 config: map[string]*types.MarginCalculator{}, 46 } 47 48 contentReaders := helpers.ReadAll(defaultMarginCalculators, defaultMarginCalculatorFileNames) 49 for name, contentReader := range contentReaders { 50 marginCalculator, err := unmarshaler.UnmarshalMarginCalculator(contentReader) 51 if err != nil { 52 panic(fmt.Errorf("couldn't unmarshal default margin calculator %s: %v", name, err)) 53 } 54 if err := config.Add(name, marginCalculator); err != nil { 55 panic(fmt.Errorf("failed to add default margin calculator %s: %v", name, err)) 56 } 57 } 58 59 return config 60 } 61 62 func (c *marginCalculators) Add(name string, calculator *types.MarginCalculator) error { 63 c.config[name] = calculator 64 return nil 65 } 66 67 func (c *marginCalculators) Get(name string) (*types.MarginCalculator, error) { 68 calculator, ok := c.config[name] 69 if !ok { 70 return calculator, fmt.Errorf("no margin calculator \"%s\" registered", name) 71 } 72 // Copy to avoid modification between tests. 73 copyConfig := &types.MarginCalculator{} 74 if err := copier.Copy(copyConfig, calculator); err != nil { 75 panic(fmt.Errorf("failed to deep copy margin calculator: %v", err)) 76 } 77 return copyConfig, nil 78 }