|
- package endpoints
-
- import (
- "encoding/json"
- "fmt"
- "github.com/imosed/signet/auth"
- . "github.com/imosed/signet/data"
- "github.com/stellar/go/clients/horizonclient"
- "github.com/stellar/go/protocols/horizon"
- "net/http"
- "strconv"
- )
-
- type SuccessResponse struct {
- Success bool `json:"success"`
- }
-
- func CreateRewardFund(resp http.ResponseWriter, req *http.Request) {
- var fund RewardFund
- dec := json.NewDecoder(req.Body)
- err := dec.Decode(&fund)
- if err != nil {
- panic("Could not read submitted reward fund")
- }
-
- var bonuses []Bonus
-
- rewardFund := RewardFund{
- Asset: fund.Asset,
- FundWallet: fund.FundWallet,
- IssuerWallet: fund.IssuerWallet,
- Memo: fund.Memo,
- Price: 0,
- AmountGoal: fund.AmountGoal,
- MinContribution: fund.MinContribution,
- Title: fund.Title,
- Description: fund.Description,
- Contributions: nil,
- }
-
- offerReq := horizonclient.OfferRequest{
- Seller: rewardFund.IssuerWallet,
- Selling: fmt.Sprintf("%s:%s", rewardFund.Asset, rewardFund.IssuerWallet),
- Buying: fmt.Sprintf("XLM:%s", rewardFund.IssuerWallet),
- Order: horizonclient.OrderDesc,
- }
- op, err := client.Offers(offerReq)
- if err != nil {
- panic("Could not get offers")
- }
- offers := op.Embedded.Records
- var price float64
- if len(offers) == 1 {
- price, err = strconv.ParseFloat(op.Embedded.Records[0].Price, 64)
- if err != nil {
- panic("Could not parse price to float")
- }
- rewardFund.Price = price
- } else {
- var maxOffers float64 = 0
- var correctOffer horizon.Offer
- for _, o := range op.Embedded.Records {
- parsedAmt, err := strconv.ParseFloat(o.Amount, 64)
- if err != nil {
- panic("Could not parse amount to float")
- }
- if parsedAmt > maxOffers {
- correctOffer = o
- maxOffers = parsedAmt
- }
- }
- price, err = strconv.ParseFloat(correctOffer.Price, 64)
- if err != nil {
- panic("Could not parse price to float")
- }
- rewardFund.Price = price
- }
-
- var claims *auth.Claims
- claims, err = auth.GetUserClaims(req)
- if err != nil {
- panic("Could not determine if user is authenticated")
- }
-
- if claims.Privileges <= Admin {
- Db.Create(&rewardFund)
-
- for _, bonus := range fund.Bonuses {
- bonus.RewardFundID = rewardFund.ID
- bonuses = append(bonuses, bonus)
- }
- Db.Create(&bonuses)
-
- err = json.NewEncoder(resp).Encode(&SuccessResponse{Success: true})
- if err != nil {
- panic("Could not create response for created reward fund")
- }
- } else {
- resp.WriteHeader(403)
- }
- }
|