How to use Swap method of config Package

Best Gauge code snippet using config.Swap

swarm.go

Source:swarm.go Github

copy

Full Screen

...73 swapEnabled bool74 netStore *storage.NetStore75 sfs *fuse.SwarmFS // need this to cleanup all the active mounts on node exit76 ps *pss.Pss77 swap *swap.Swap78 stateStore *state.DBStore79 accountingMetrics *protocols.AccountingMetrics80 tracerClose io.Closer81}82type SwarmAPI struct {83 Api *api.API84 Backend chequebook.Backend85}86func (self *Swarm) API() *SwarmAPI {87 return &SwarmAPI{88 Api: self.api,89 Backend: self.backend,90 }91}92// creates a new swarm service instance93// implements node.Service94// If mockStore is not nil, it will be used as the storage for chunk data.95// MockStore should be used only for testing.96func NewSwarm(config *api.Config, mockStore *mock.NodeStore) (self *Swarm, err error) {97 if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroAddr) {98 return nil, fmt.Errorf("empty public key")99 }100 if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroAddr) {101 return nil, fmt.Errorf("empty bzz key")102 }103 var backend chequebook.Backend104 if config.SwapAPI != "" && config.SwapEnabled {105 log.Info("connecting to SWAP API", "url", config.SwapAPI)106 backend, err = ethclient.Dial(config.SwapAPI)107 if err != nil {108 return nil, fmt.Errorf("error connecting to SWAP API %s: %s", config.SwapAPI, err)109 }110 }111 self = &Swarm{112 config: config,113 backend: backend,114 privateKey: config.ShiftPrivateKey(),115 }116 log.Debug("Setting up Swarm service components")117 config.HiveParams.Discovery = true118 bzzconfig := &network.BzzConfig{119 NetworkID: config.NetworkID,120 OverlayAddr: common.FromHex(config.BzzKey),121 HiveParams: config.HiveParams,122 LightNode: config.LightNodeEnabled,123 }124 self.stateStore, err = state.NewDBStore(filepath.Join(config.Path, "state-store.db"))125 if err != nil {126 return127 }128 // set up high level api129 var resolver *api.MultiResolver130 if len(config.EnsAPIs) > 0 {131 opts := []api.MultiResolverOption{}132 for _, c := range config.EnsAPIs {133 tld, endpoint, addr := parseEnsAPIAddress(c)134 r, err := newEnsClient(endpoint, addr, config, self.privateKey)135 if err != nil {136 return nil, err137 }138 opts = append(opts, api.MultiResolverOptionWithResolver(r, tld))139 }140 resolver = api.NewMultiResolver(opts...)141 self.dns = resolver142 }143 lstore, err := storage.NewLocalStore(config.LocalStoreParams, mockStore)144 if err != nil {145 return nil, err146 }147 self.netStore, err = storage.NewNetStore(lstore, nil)148 if err != nil {149 return nil, err150 }151 to := network.NewKademlia(152 common.FromHex(config.BzzKey),153 network.NewKadParams(),154 )155 delivery := stream.NewDelivery(to, self.netStore)156 self.netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, config.DeliverySkipCheck).New157 if config.SwapEnabled {158 balancesStore, err := state.NewDBStore(filepath.Join(config.Path, "balances.db"))159 if err != nil {160 return nil, err161 }162 self.swap = swap.New(balancesStore)163 self.accountingMetrics = protocols.SetupAccountingMetrics(10*time.Second, filepath.Join(config.Path, "metrics.db"))164 }165 var nodeID enode.ID166 if err := nodeID.UnmarshalText([]byte(config.NodeID)); err != nil {167 return nil, err168 }169 syncing := stream.SyncingAutoSubscribe170 if !config.SyncEnabled || config.LightNodeEnabled {171 syncing = stream.SyncingDisabled172 }173 retrieval := stream.RetrievalEnabled174 if config.LightNodeEnabled {175 retrieval = stream.RetrievalClientOnly176 }177 registryOptions := &stream.RegistryOptions{178 SkipCheck: config.DeliverySkipCheck,179 Syncing: syncing,180 Retrieval: retrieval,181 SyncUpdateDelay: config.SyncUpdateDelay,182 MaxPeerServers: config.MaxStreamPeerServers,183 }184 self.streamer = stream.NewRegistry(nodeID, delivery, self.netStore, self.stateStore, registryOptions, self.swap)185 // Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage186 self.fileStore = storage.NewFileStore(self.netStore, self.config.FileStoreParams)187 var feedsHandler *feed.Handler188 fhParams := &feed.HandlerParams{}189 feedsHandler = feed.NewHandler(fhParams)190 feedsHandler.SetStore(self.netStore)191 lstore.Validators = []storage.ChunkValidator{192 storage.NewContentAddressValidator(storage.MakeHashFunc(storage.DefaultHash)),193 feedsHandler,194 }195 err = lstore.Migrate()196 if err != nil {197 return nil, err198 }199 log.Debug("Setup local storage")200 self.bzz = network.NewBzz(bzzconfig, to, self.stateStore, self.streamer.GetSpec(), self.streamer.Run)201 // Pss = postal service over swarm (devp2p over bzz)202 self.ps, err = pss.NewPss(to, config.Pss)203 if err != nil {204 return nil, err205 }206 if pss.IsActiveHandshake {207 pss.SetHandshakeController(self.ps, pss.NewHandshakeParams())208 }209 self.api = api.NewAPI(self.fileStore, self.dns, feedsHandler, self.privateKey)210 self.sfs = fuse.NewSwarmFS(self.api)211 log.Debug("Initialized FUSE filesystem")212 return self, nil213}214// parseEnsAPIAddress parses string according to format215// [tld:][contract-addr@]url and returns ENSClientConfig structure216// with endpoint, contract address and TLD.217func parseEnsAPIAddress(s string) (tld, endpoint string, addr common.Address) {218 isAllLetterString := func(s string) bool {219 for _, r := range s {220 if !unicode.IsLetter(r) {221 return false222 }223 }224 return true225 }226 endpoint = s227 if i := strings.Index(endpoint, ":"); i > 0 {228 if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {229 tld = endpoint[:i]230 endpoint = endpoint[i+1:]231 }232 }233 if i := strings.Index(endpoint, "@"); i > 0 {234 addr = common.HexToAddress(endpoint[:i])235 endpoint = endpoint[i+1:]236 }237 return238}239// ensClient provides functionality for api.ResolveValidator240type ensClient struct {241 *ens.ENS242 *ethclient.Client243}244// newEnsClient creates a new ENS client for that is a consumer of245// a ENS API on a specific endpoint. It is used as a helper function246// for creating multiple resolvers in NewSwarm function.247func newEnsClient(endpoint string, addr common.Address, config *api.Config, privkey *ecdsa.PrivateKey) (*ensClient, error) {248 log.Info("connecting to ENS API", "url", endpoint)249 client, err := rpc.Dial(endpoint)250 if err != nil {251 return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)252 }253 ethClient := ethclient.NewClient(client)254 ensRoot := config.EnsRoot255 if addr != (common.Address{}) {256 ensRoot = addr257 } else {258 a, err := detectEnsAddr(client)259 if err == nil {260 ensRoot = a261 } else {262 log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", ensRoot), "err", err)263 }264 }265 transactOpts := bind.NewKeyedTransactor(privkey)266 dns, err := ens.NewENS(transactOpts, ensRoot, ethClient)267 if err != nil {268 return nil, err269 }270 log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))271 return &ensClient{272 ENS: dns,273 Client: ethClient,274 }, err275}276// detectEnsAddr determines the ENS contract address by getting both the277// version and genesis hash using the client and matching them to either278// mainnet or testnet addresses279func detectEnsAddr(client *rpc.Client) (common.Address, error) {280 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)281 defer cancel()282 var version string283 if err := client.CallContext(ctx, &version, "net_version"); err != nil {284 return common.Address{}, err285 }286 block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))287 if err != nil {288 return common.Address{}, err289 }290 switch {291 case version == "1" && block.Hash() == params.MainnetGenesisHash:292 log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)293 return ens.MainNetAddress, nil294 case version == "3" && block.Hash() == params.TestnetGenesisHash:295 log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)296 return ens.TestNetAddress, nil297 default:298 return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())299 }300}301/*302Start is called when the stack is started303* starts the network kademlia hive peer management304* (starts netStore level 0 api)305* starts DPA level 1 api (chunking -> store/retrieve requests)306* (starts level 2 api)307* starts http proxy server308* registers url scheme handlers for bzz, etc309* TODO: start subservices like sword, swear, swarmdns310*/311// implements the node.Service interface312func (self *Swarm) Start(srv *p2p.Server) error {313 startTime = time.Now()314 self.tracerClose = tracing.Closer315 // update uaddr to correct enode316 newaddr := self.bzz.UpdateLocalAddr([]byte(srv.Self().String()))317 log.Info("Updated bzz local addr", "oaddr", fmt.Sprintf("%x", newaddr.OAddr), "uaddr", fmt.Sprintf("%s", newaddr.UAddr))318 // set chequebook319 //TODO: Currently if swap is enabled and no chequebook (or inexistent) contract is provided, the node would crash.320 //Once we integrate back the contracts, this check MUST be revisited321 if self.config.SwapEnabled && self.config.SwapAPI != "" {322 ctx := context.Background() // The initial setup has no deadline.323 err := self.SetChequebook(ctx)324 if err != nil {325 return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)326 }327 log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))328 } else {329 log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))330 }331 log.Info("Starting bzz service")332 err := self.bzz.Start(srv)333 if err != nil {334 log.Error("bzz failed", "err", err)335 return err336 }337 log.Info("Swarm network started", "bzzaddr", fmt.Sprintf("%x", self.bzz.Hive.BaseAddr()))338 if self.ps != nil {339 self.ps.Start(srv)340 }341 // start swarm http proxy server342 if self.config.Port != "" {343 addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)344 server := httpapi.NewServer(self.api, self.config.Cors)345 if self.config.Cors != "" {346 log.Debug("Swarm HTTP proxy CORS headers", "allowedOrigins", self.config.Cors)347 }348 log.Debug("Starting Swarm HTTP proxy", "port", self.config.Port)349 go func() {350 err := server.ListenAndServe(addr)351 if err != nil {352 log.Error("Could not start Swarm HTTP proxy", "err", err.Error())353 }354 }()355 }356 self.periodicallyUpdateGauges()357 startCounter.Inc(1)358 self.streamer.Start(srv)359 return nil360}361func (self *Swarm) periodicallyUpdateGauges() {362 ticker := time.NewTicker(updateGaugesPeriod)363 go func() {364 for range ticker.C {365 self.updateGauges()366 }367 }()368}369func (self *Swarm) updateGauges() {370 uptimeGauge.Update(time.Since(startTime).Nanoseconds())371 requestsCacheGauge.Update(int64(self.netStore.RequestsCacheLen()))372}373// implements the node.Service interface374// stops all component services.375func (self *Swarm) Stop() error {376 if self.tracerClose != nil {377 err := self.tracerClose.Close()378 if err != nil {379 return err380 }381 }382 if self.ps != nil {383 self.ps.Stop()384 }385 if ch := self.config.Swap.Chequebook(); ch != nil {386 ch.Stop()387 ch.Save()388 }389 if self.swap != nil {390 self.swap.Close()391 }392 if self.accountingMetrics != nil {393 self.accountingMetrics.Close()394 }395 if self.netStore != nil {396 self.netStore.Close()397 }398 self.sfs.Stop()399 stopCounter.Inc(1)400 self.streamer.Stop()401 err := self.bzz.Stop()402 if self.stateStore != nil {403 self.stateStore.Close()404 }405 return err406}407// implements the node.Service interface408func (self *Swarm) Protocols() (protos []p2p.Protocol) {409 protos = append(protos, self.bzz.Protocols()...)410 if self.ps != nil {411 protos = append(protos, self.ps.Protocols()...)412 }413 return414}415func (self *Swarm) RegisterPssProtocol(spec *protocols.Spec, targetprotocol *p2p.Protocol, options *pss.ProtocolParams) (*pss.Protocol, error) {416 if !pss.IsActiveProtocol {417 return nil, fmt.Errorf("Pss protocols not available (built with !nopssprotocol tag)")418 }419 topic := pss.ProtocolTopic(spec)420 return pss.RegisterProtocol(self.ps, &topic, spec, targetprotocol, options)421}422// implements node.Service423// APIs returns the RPC API descriptors the Swarm implementation offers424func (self *Swarm) APIs() []rpc.API {425 apis := []rpc.API{426 // public APIs427 {428 Namespace: "bzz",429 Version: "3.0",430 Service: &Info{self.config, chequebook.ContractParams},431 Public: true,432 },433 // admin APIs434 {435 Namespace: "bzz",436 Version: "3.0",437 Service: api.NewControl(self.api, self.bzz.Hive),438 Public: false,439 },440 {441 Namespace: "chequebook",442 Version: chequebook.Version,443 Service: chequebook.NewApi(self.config.Swap.Chequebook),444 Public: false,445 },446 {447 Namespace: "swarmfs",448 Version: fuse.Swarmfs_Version,449 Service: self.sfs,450 Public: false,451 },452 }453 apis = append(apis, self.bzz.APIs()...)454 if self.ps != nil {455 apis = append(apis, self.ps.APIs()...)456 }457 return apis458}459func (self *Swarm) Api() *api.API {460 return self.api461}462// SetChequebook ensures that the local checquebook is set up on chain.463func (self *Swarm) SetChequebook(ctx context.Context) error {464 err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)465 if err != nil {466 return err467 }468 log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))469 return nil470}471// serialisable info about swarm472type Info struct {473 *api.Config474 *chequebook.Params475}476func (self *Info) Info() *Info {477 return self478}...

Full Screen

Full Screen

ws_test.go

Source:ws_test.go Github

copy

Full Screen

1package okex2/*3 OKEX ws api websocket test & sample4 @author Lingting Fu5 @date 2018-12-276 @version 1.0.07*/8import (9 "fmt"10 "github.com/stretchr/testify/assert"11 "hash/crc32"12 "testing"13 "time"14)15func TestOKWSAgent_AllInOne(t *testing.T) {16 agent := OKWSAgent{}17 config := GetDefaultConfig()18 // Step1: Start agent.19 agent.Start(config)20 // Step2: Subscribe channel21 // Step2.0: Subscribe public channel swap/ticker successfully.22 agent.Subscribe(CHNL_SWAP_TICKER, "BTC-USD-SWAP", DefaultDataCallBack)23 // Step2.1: Subscribe private channel swap/position before login, so it would be a fail.24 agent.Subscribe(CHNL_SWAP_POSITION, "BTC-USD-SWAP", DefaultDataCallBack)25 // Step3: Wait for the ws server's pushed table responses.26 time.Sleep(60 * time.Second)27 // Step4. Unsubscribe public channel swap/ticker28 agent.UnSubscribe(CHNL_SWAP_TICKER, "BTC-USD-SWAP")29 time.Sleep(1 * time.Second)30 // Step5. Login31 agent.Login(config.ApiKey, config.Passphrase)32 time.Sleep(1 * time.Second)33 // Step6. Subscribe private channel swap/position after login, so it would be a success.34 agent.Subscribe(CHNL_SWAP_POSITION, "BTC-USD-SWAP", DefaultDataCallBack)35 time.Sleep(120 * time.Second)36 // Step7. Stop all the go routine run in background.37 agent.Stop()38 time.Sleep(1 * time.Second)39}40func TestOKWSAgent_Depths(t *testing.T) {41 agent := OKWSAgent{}42 config := GetDefaultConfig()43 // Step1: Start agent.44 agent.Start(config)45 // Step2: Subscribe channel46 // Step2.0: Subscribe public channel swap/depths successfully.47 agent.Subscribe(CHNL_SWAP_DEPTH, "BTC-USD-SWAP", DefaultDataCallBack)48 // Step3: Client receive depths from websocket server.49 // Step3.0: Receive partial depths50 // Step3.1: Receive update depths (It may take a very long time to see Update Event.)51 time.Sleep(60 * time.Second)52 // Step4. Stop all the go routine run in background.53 agent.Stop()54 time.Sleep(1 * time.Second)55}56func TestOKWSAgent_mergeDepths(t *testing.T) {57 oldDepths := [][4]interface{}{58 {"5088.59", "34000", 0, 1},59 {"7200", "1", 0, 1},60 {"7300", "1", 0, 1},61 }62 // Case1.63 newDepths1 := [][4]interface{}{64 {"5088.59", "32000", 0, 1},65 }66 expectedMerged1 := [][4]interface{}{67 {"5088.59", "32000", 0, 1},68 {"7200", "1", 0, 1},69 {"7300", "1", 0, 1},70 }71 m1, e1 := mergeDepths(oldDepths, newDepths1)72 assert.True(t, e1 == nil)73 assert.True(t, len(*m1) == len(expectedMerged1) && (*m1)[0][1] == expectedMerged1[0][1] && (*m1)[0][1] == "32000")74 // Case2.75 newDepths2 := [][4]interface{}{76 {"7200", "0", 0, 1},77 }78 expectedMerged2 := [][4]interface{}{79 {"5088.59", "34000", 0, 1},80 {"7300", "1", 0, 1},81 }82 m2, e2 := mergeDepths(oldDepths, newDepths2)83 assert.True(t, e2 == nil)84 assert.True(t, len(*m2) == len(expectedMerged2) && (*m2)[0][1] == expectedMerged2[0][1] && (*m2)[0][1] == "34000")85 // Case3.86 newDepths3 := [][4]interface{}{87 {"5000", "1", 0, 1},88 {"7400", "1", 0, 1},89 }90 expectedMerged3 := [][4]interface{}{91 {"5000", "1", 0, 1},92 {"5088.59", "34000", 0, 1},93 {"7200", "1", 0, 1},94 {"7300", "1", 0, 1},95 {"7400", "1", 0, 1},96 }97 m3, e3 := mergeDepths(oldDepths, newDepths3)98 assert.True(t, e3 == nil)99 assert.True(t, len(*m3) == len(expectedMerged3) && (*m3)[0][1] == expectedMerged3[0][1] && (*m3)[0][1] == "1")100}101func TestOKWSAgent_calCrc32(t *testing.T) {102 askDepths := [][4]interface{}{103 {"5088.59", "34000", 0, 1},104 {"7200", "1", 0, 1},105 {"7300", "1", 0, 1},106 }107 bidDepths1 := [][4]interface{}{108 {"3850", "1", 0, 1},109 {"3800", "1", 0, 1},110 {"3500", "1", 0, 1},111 {"3000", "1", 0, 1},112 }113 crcBuf1, caled1 := calCrc32(&askDepths, &bidDepths1)114 assert.True(t, caled1 != 0 && crcBuf1.String() == "3850:1:3800:1:3500:1:3000:1:5088.59:34000:7200:1:7300:1")115 bidDepths2 := [][4]interface{}{116 {"3850", "1", 0, 1},117 {"3800", "1", 0, 1},118 {"3500", "1", 0, 1},119 }120 crcBuf2, caled2 := calCrc32(&askDepths, &bidDepths2)121 assert.True(t, caled2 != 0 && crcBuf2.String() == "3850:1:5088.59:34000:3800:1:7200:1:3500:1:7300:1")122}123func TestArray(t *testing.T) {124 t1 := [4]int{1, 2, 3, 4}125 t2 := [][4]int{126 {1, 2, 3, 4},127 }128 t3 := [4][]int{129 {1, 2, 3, 4},130 }131 r1, _ := Struct2JsonString(t1)132 r2, _ := Struct2JsonString(t2)133 r3, _ := Struct2JsonString(t3)134 println(len(t1), r1)135 println(len(t2), r2)136 println(len(t3), r3)137 fmt.Printf("%+v", t1[0:len(t1)-1])138}139func TestCrc32(t *testing.T) {140 str1 := "3366.1:7:3366.8:9:3366:6:3368:8"141 r := crc32.ChecksumIEEE([]byte(str1))142 println(r)143 assert.True(t, int32(r) == -1881014294)144 str2 := "3366.1:7:3366.8:9:3368:8:3372:8"145 r = crc32.ChecksumIEEE([]byte(str2))146 println(r)147 assert.True(t, int32(r) == 831078360)148}149func TestFmtSprintf(t *testing.T) {150 a := [][]interface{}{151 {"199", "10"},152 {199.0, 10.0},153 }154 for _, v := range a {155 s1 := fmt.Sprintf("%v:%v", v[0], v[1])156 s2 := fmt.Sprintf("%s:%s", v[0], v[1])157 println(s1)158 println(s2)159 assert.True(t, s1 != "" && s2 != "")160 }161}162func TestOKWSAgent_Futures_AllInOne(t *testing.T) {163 agent := OKWSAgent{}164 config := GetDefaultConfig()165 publicChannels := []string{166 CHNL_FUTURES_CANDLE60S,167 CHNL_FUTURES_CANDLE180S,168 CHNL_FUTURES_CANDLE300S,169 CHNL_FUTURES_CANDLE900S,170 CHNL_FUTURES_CANDLE1800S,171 CHNL_FUTURES_CANDLE3600S,172 CHNL_FUTURES_CANDLE7200S,173 CHNL_FUTURES_CANDLE14400S,174 CHNL_FUTURES_DEPTH,175 CHNL_FUTURES_DEPTH5,176 CHNL_FUTURES_ESTIMATED_PRICE,177 CHNL_FUTURES_MARK_PRICE,178 CHNL_FUTURES_PRICE_RANGE,179 CHNL_FUTURES_TICKER,180 CHNL_FUTURES_TRADE,181 }182 privateChannels := []string{183 CHNL_FUTURES_ACCOUNT,184 CHNL_FUTURES_ORDER,185 CHNL_FUTURES_POSITION,186 }187 filter := "BTC-USD-170310"188 // Step1: Start agent.189 agent.Start(config)190 // Step2: Login191 agent.Login(config.ApiKey, config.Passphrase)192 time.Sleep(1 * time.Second)193 // Step3: Subscribe privateChannels194 for _, c := range privateChannels {195 agent.Subscribe(c, filter, DefaultDataCallBack)196 }197 // Step4: Subscribe publicChannels198 for _, c := range publicChannels {199 agent.Subscribe(c, filter, DefaultDataCallBack)200 }201 time.Sleep(time.Second * 2)202 // Step5: unsubscribe privateChannels203 for _, c := range privateChannels {204 agent.UnSubscribe(c, filter)205 }206 agent.Stop()207}208func TestOKWSAgent_Spots_AllInOne(t *testing.T) {209 agent := OKWSAgent{}210 config := GetDefaultConfig()211 publicChannels := []string{212 CHNL_SPOT_CANDLE60S,213 CHNL_SPOT_CANDLE180S,214 CHNL_SPOT_CANDLE300S,215 CHNL_SPOT_CANDLE900S,216 CHNL_SPOT_CANDLE1800S,217 CHNL_SPOT_CANDLE3600S,218 CHNL_SPOT_CANDLE7200S,219 CHNL_SPOT_CANDLE14400S,220 CHNL_SPOT_DEPTH,221 CHNL_SPOT_DEPTH5,222 CHNL_SPOT_TICKER,223 CHNL_SPOT_TRADE,224 }225 privateChannels := []string{226 CHNL_SPOT_ACCOUNT,227 CHNL_SPOT_MARGIN_ACCOUNT,228 CHNL_SPOT_ORDER,229 }230 filter := "ETH-USDT"231 // Step1: Start agent.232 agent.Start(config)233 // Step2: Login234 agent.Login(config.ApiKey, config.Passphrase)235 time.Sleep(1 * time.Second)236 // Step3: Subscribe privateChannels237 for _, c := range privateChannels {238 agent.Subscribe(c, filter, DefaultDataCallBack)239 }240 // Step4: Subscribe publicChannels241 for _, c := range publicChannels {242 agent.Subscribe(c, filter, DefaultDataCallBack)243 }244 time.Sleep(time.Second * 2)245 // Step5: unsubscribe privateChannels246 for _, c := range privateChannels {247 agent.UnSubscribe(c, filter)248 }249 agent.Stop()250}...

Full Screen

Full Screen

configure_eth_swap_ap.go

Source:configure_eth_swap_ap.go Github

copy

Full Screen

...17 "github.com/binance-chain/eth-swap-ap/restapi/operations/svc_info"18 "github.com/binance-chain/eth-swap-ap/restapi/operations/swap_pairs"19 "github.com/binance-chain/eth-swap-ap/restapi/operations/swap_sms"20 "github.com/binance-chain/eth-swap-ap/restapi/operations/swaps"21 SwapPairsSm "github.com/binance-chain/eth-swap-ap/restapi/swap_pair_sms"22 SwapPairs "github.com/binance-chain/eth-swap-ap/restapi/swap_pairs"23 Swaps "github.com/binance-chain/eth-swap-ap/restapi/swaps"24 "github.com/binance-chain/eth-swap-ap/services"25 "github.com/binance-chain/eth-swap-ap/utils/cache"26 uenv "github.com/binance-chain/eth-swap-ap/utils/env"27 "github.com/binance-chain/eth-swap-ap/utils/log"28)29//go:generate swagger generate server --target ../../eth-swap-ap --name EthSwapAp --spec ../swagger.yml30func configureAPI(api *operations.EthSwapApAPI) http.Handler {31 // configure the api here32 api.ServeError = errors.ServeError33 api.JSONConsumer = runtime.JSONConsumer()34 api.JSONProducer = runtime.JSONProducer()35 api.Logger = func(str string, args ...interface{}) {36 level, str := log.ParsePrefixedLogString(str)37 log.GetLogger(level)(str, args...)38 }39 api.SwapsGetSwapsHandler = swaps.GetSwapsHandlerFunc(func(params swaps.GetSwapsParams) middleware.Responder {40 return swapsCache.Serve(params.HTTPRequest, func() middleware.Responder {41 return Swaps.NewGetSwapsHandler(env, api).Serve(params)42 }, api.JSONProducer)43 })44 api.SwapPairsGetSwapPairsHandler = swap_pairs.GetSwapPairsHandlerFunc(func(params swap_pairs.GetSwapPairsParams) middleware.Responder {45 return swapPairCache.Serve(params.HTTPRequest, func() middleware.Responder {46 return SwapPairs.NewGetSwapPairsHandler(env, api).Serve(params)47 }, api.JSONProducer)48 })49 api.SwapSmsGetSwapPairSmsHandler = swap_sms.GetSwapPairSmsHandlerFunc(func(params swap_sms.GetSwapPairSmsParams) middleware.Responder {50 return swapPairSMCache.Serve(params.HTTPRequest, func() middleware.Responder {51 return SwapPairsSm.NewGetSwapPairSmsHandler(env, api).Serve(params)52 }, api.JSONProducer)53 })54 api.SvcInfoGetInfoHandler = svc_info.GetInfoHandlerFunc(func(params svc_info.GetInfoParams) middleware.Responder {55 return infoCache.Serve(params.HTTPRequest, func() middleware.Responder {56 return rinfo.NewGetInfoHandler(env, api).Serve(params)57 }, api.JSONProducer)58 })59 api.PreServerShutdown = func() {}60 api.ServerShutdown = func() {}61 return setupGlobalMiddleware(api.Serve(setupMiddlewares))62}63// The TLS configuration before HTTPS server starts.64func configureTLS(tlsConfig *tls.Config) {65 // Make all necessary changes to the TLS configuration here.66}67const cacheServiceTickRate = time.Hour68var (69 Log = logging.MustGetLogger("eth-swap-ap")70 config *cfg.Config71 // services72 cacheService services.Service73 // caches74 swapPairCache,75 swapPairSMCache,76 swapsCache,77 infoCache *middlewares.MWCacher78 //env79 env *uenv.Env80)81var cliOpts = struct {82 ConfigFileName string `short:"c" long:"config-file" description:"Config filename"`83 SecretName string `short:"s" long:"secret-name" description:"the secret name of the config"`84 SecretRegion string `short:"r" long:"secret-region" description:"the secret region of the config"`85}{}86func configureFlags(api *operations.EthSwapApAPI) {87 param1 := swag.CommandLineOptionsGroup{88 ShortDescription: "config",89 Options: &cliOpts,90 }91 api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{param1}92}93// As soon as server is initialized but not run yet, this function will be called.94// If you need to modify a config, store server instance to stop it individually later, this is the place.95// This function can be called multiple times, depending on the number of serving schemes.96// scheme value will be set accordingly: "http", "https" or "unix"97func configureServer(s *http.Server, scheme, addr string) {98 configFileName := cliOpts.ConfigFileName99 secretName := cliOpts.SecretName100 secretRegion := cliOpts.SecretRegion101 if configFileName == "" && (secretName == "" || secretRegion == "") {102 panic("missing config file path and secret path")103 }104 if configFileName != "" {105 config = cfg.InitConfigFromFile(configFileName)106 }107 if secretName != "" && secretRegion != "" {108 config = cfg.InitConfigFromSecret(secretName, secretRegion, config)109 }110 // init logger111 log.InitLogger(config.Logs)112 // init cache113 store := cache.NewMemStorage()114 swapPairCacheMS := config.CacheTTLs["swap_pairs"] * time.Millisecond.Nanoseconds()115 swapPairCache = middlewares.NewMWCacher(store, time.Duration(swapPairCacheMS))116 swapsCacheMs := config.CacheTTLs["swaps"] * time.Millisecond.Nanoseconds()117 swapPairSmsCacheMs := config.CacheTTLs["swap_pair_sms"] * time.Millisecond.Nanoseconds()118 swapPairSMCache = middlewares.NewMWCacher(store, time.Duration(swapPairSmsCacheMs))119 swapsCache = middlewares.NewMWCacher(store, time.Duration(swapsCacheMs))120 infoCacheMs := config.CacheTTLs["info"] * time.Millisecond.Nanoseconds()121 infoCache = middlewares.NewMWCacher(store, time.Duration(infoCacheMs))122 cacheService = services.NewCacheService(store, cacheServiceTickRate)123 if err := cacheService.Start(); err != nil {124 panic(err) // fatal125 }126 // init db127 dbConfig := config.DB128 swapPairDao, swapPairSMDao, swapDao, err := dao.NewDaoServices(dbConfig.UserName, dbConfig.Password, dbConfig.Host, dbConfig.DBName, dbConfig.Port, dbConfig.AutoMigrate)129 if err != nil {130 panic(err)131 }132 // init env133 env = &uenv.Env{134 Config: config,135 SwapPairDao: swapPairDao,136 SwapPairSMDao: swapPairSMDao,137 SwapDao: swapDao,138 Cache: store,139 }140}141// The middleware configuration is for the handler executors. These do not apply to the swagger.json document.142// The middleware executes after routing but before authentication, binding and validation143func setupMiddlewares(handler http.Handler) http.Handler {144 return handler145}146// The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document.147// So this is a good place to plug in a panic handling middleware, logging and metrics148func setupGlobalMiddleware(handler http.Handler) http.Handler {149 return handler150}...

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c, err := config.NewConfig("ini", "conf/app.conf")4 if err != nil {5 fmt.Println(err)6 }7 c.Swap()8 fmt.Println(c.String("appname"))9}10import (11func main() {12 c, err := config.NewConfig("ini", "conf/app.conf")13 if err != nil {14 fmt.Println(err)15 }16 c.Swap()17 fmt.Println(c.String("appname"))18}19import (20func main() {21 c, err := config.NewConfig("ini", "conf/app.conf")22 if err != nil {23 fmt.Println(err)24 }25 c.WatchConfig()26 fmt.Println(c.String("appname"))27}28import (29func main() {30 c, err := config.NewConfig("ini", "conf/app.conf")31 if err != nil {32 fmt.Println(err)33 }34 c.WatchConfig()35 fmt.Println(c.String("appname"))36}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cfg, err := config.NewConfig("ini", "conf/app.conf")4 if err != nil {5 fmt.Println(err)6 }7 cfg.Set("appname", "beego")8 fmt.Println(cfg.String("appname"))9 fmt.Println(cfg.String("httpport"))10 fmt.Println(cfg.String("runmode"))11 cfg.Set("appname", "beego1")12 cfg.Set("httpport", "8080")13 cfg.Set("runmode", "dev")14 cfg.SaveConfigFile("conf/app.conf")15 cfg.Swap()16 fmt.Println(cfg.String("appname"))17 fmt.Println(cfg.String("httpport"))18 fmt.Println(cfg.String("runmode"))19}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 swap.Swap(&a, &b)4 fmt.Println("a = ", a)5 fmt.Println("b = ", b)6}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := config.Config{A: 1, B: 2}4 fmt.Println("Before swap: ", c)5 c.Swap()6 fmt.Println("After swap: ", c)7}8type Config struct {9}10func (c Config) Swap() {11}12Before swap: {1 2}13After swap: {1 2}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 config := gobuild.NewConfig()5 config.Swap()6}7import (8func main() {9 fmt.Println("Hello World")10 config := gobuild.NewConfig()11 config.Swap()12}13import (14func main() {15 fmt.Println("Hello World")16 config := gobuild.NewConfig()17 config.Swap()18}19import (20func main() {21 fmt.Println("Hello World")22 config := gobuild.NewConfig()23 config.Swap()24}25import (26func main() {27 fmt.Println("Hello World")28 config := gobuild.NewConfig()29 config.Swap()30}31import (32func main() {33 fmt.Println("Hello World")34 config := gobuild.NewConfig()35 config.Swap()36}37import (38func main() {39 fmt.Println("Hello World")40 config := gobuild.NewConfig()41 config.Swap()42}43import (44func main() {45 fmt.Println("Hello World")46 config := gobuild.NewConfig()47 config.Swap()48}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful