示例#1
0
// GetWalletBalance get local wallet balance.
// mode: GET
// url: /api/v1/wallet/balance?id=[:id]
// params:
// 		id: wallet id.
func GetWalletBalance(se Servicer) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		var rlt *pp.EmptyRes
		for {
			id := r.FormValue("id")
			if id == "" {
				err := errors.New("id is empty")
				logger.Error(err.Error())
				rlt = pp.MakeErrRes(err)
				break
			}
			// get addresses in wallet.
			addrs, err := wallet.GetAddresses(id)
			if err != nil {
				logger.Error(err.Error())
				rlt = pp.MakeErrRes(err)
				break
			}

			if len(addrs) == 0 {
				res := pp.GetAddrBalanceRes{
					Result: pp.MakeResult(pp.ErrCode_NotExits, "wallet have no address"),
				}
				sendJSON(w, &res)
				return
			}

			cp := strings.Split(id, "_")[0]

			// get address balance.
			req := pp.GetAddrBalanceReq{
				CoinType: pp.PtrString(cp),
				Addrs:    pp.PtrString(strings.Join(addrs, ",")),
			}

			var res pp.GetAddrBalanceRes
			if err := sknet.EncryGet(se.GetServAddr(), "/get/address/balance", req, &res); err != nil {
				logger.Error(err.Error())
				rlt = pp.MakeErrResWithCode(pp.ErrCode_ServerError)
				break
			}

			sendJSON(w, res)
			return
		}
		sendJSON(w, rlt)
	}
}
示例#2
0
// GetAccount get account that matchs the condition in url param.
// mode: GET
// url: /api/v1/account?active=[:active]
// params:
// 		active: optional condition, must be 1, if not exist, then retun all accounts.
func GetAccount(se Servicer) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		// get active
		res := struct {
			Result   *pp.Result      `json:"result"`
			Accounts []accountResult `json:"accounts,omitempty"`
		}{}

		active := r.FormValue("active")
		switch active {
		case "1":
			a, err := account.GetActive()
			if err != nil {
				// no active account.
				res.Result = pp.MakeResult(pp.ErrCode_NotExits, err.Error())
				sendJSON(w, &res)
				return
			}

			res.Result = pp.MakeResultWithCode(pp.ErrCode_Success)
			res.Accounts = make([]accountResult, 1)
			res.Accounts[0].Pubkey = a.Pubkey
			res.Accounts[0].WalletID = make(map[string]string)
			for cp, id := range a.WltIDs {
				res.Accounts[0].WalletID[cp] = id
			}
			sendJSON(w, &res)
		case "":
			accounts := account.GetAll()
			res.Result = pp.MakeResultWithCode(pp.ErrCode_Success)
			res.Accounts = func(accounts []account.Account) []accountResult {
				as := make([]accountResult, len(accounts))
				for i, a := range accounts {
					as[i].Pubkey = a.Pubkey
					as[i].WalletID = make(map[string]string)
					for cp, id := range a.WltIDs {
						as[i].WalletID[cp] = id
					}
				}
				return as
			}(accounts)
			sendJSON(w, &res)
		default:
			sendJSON(w, pp.MakeErrResWithCode(pp.ErrCode_WrongRequest))
		}
	}
}