|
- package endpoints
-
- import (
- "encoding/json"
- "fmt"
- "net/http"
- "strings"
-
- "github.com/imosed/signet/client"
- . "github.com/imosed/signet/data"
- "github.com/rs/zerolog/log"
- "github.com/stellar/go/clients/horizonclient"
- "github.com/stellar/go/keypair"
- "github.com/stellar/go/network"
- "github.com/stellar/go/protocols/horizon"
- "github.com/stellar/go/txnbuild"
- )
-
- type ContributeRequest struct {
- PrivateKey string `json:"privateKey"`
- Amount float64 `json:"amount"`
- RewardFund uint `json:"rewardFund"`
- }
-
- func Contribute(resp http.ResponseWriter, req *http.Request) {
- var cont ContributeRequest
- err := json.NewDecoder(req.Body).Decode(&cont)
- if err != nil {
- log.Error().Err(err).Msg("Could not read in contribution")
- return
- }
-
- var fund RewardFund
-
- Db.Table("reward_funds").Select("id", "deleted_at", "fund_wallet", "memo", "min_contribution").First(&fund, cont.RewardFund)
-
- if cont.Amount < fund.MinContribution || !strings.HasPrefix(cont.PrivateKey, "S") || !fund.DeletedAt.Time.IsZero() {
- err = json.NewEncoder(resp).Encode(&SuccessResponse{Success: false})
- if err != nil {
- log.Error().Err(err).Msg("Could not deliver unsuccessful contribution response")
- }
- return
- }
-
- source := keypair.MustParseFull(cont.PrivateKey)
- sourceReq := horizonclient.AccountRequest{AccountID: source.Address()}
- var sourceAcct horizon.Account
- sourceAcct, err = client.SignetClient.AccountDetail(sourceReq)
- if err != nil {
- log.Error().Err(err).Msg("Could not get account details from Horizon SignetClient")
- return
- }
-
- tx, err := txnbuild.NewTransaction(
- txnbuild.TransactionParams{
- SourceAccount: &sourceAcct,
- IncrementSequenceNum: true,
- Operations: []txnbuild.Operation{
- &txnbuild.Payment{
- Destination: fund.FundWallet,
- Amount: fmt.Sprintf("%f", cont.Amount),
- Asset: txnbuild.NativeAsset{},
- SourceAccount: source.Address(),
- },
- },
- BaseFee: txnbuild.MinBaseFee,
- Memo: txnbuild.Memo(txnbuild.MemoText(fund.Memo)),
- Preconditions: txnbuild.Preconditions{
- TimeBounds: txnbuild.NewTimeout(15),
- },
- })
- if err != nil {
- log.Error().Err(err).Msg("Could not create contribution transaction")
- return
- }
-
- tx, err = tx.Sign(network.TestNetworkPassphrase, source)
- if err != nil {
- log.Error().Err(err).Msg("Could not sign contribution transaction")
- return
- }
-
- var response horizon.Transaction
- response, err = client.SignetClient.SubmitTransaction(tx)
- if err != nil {
- log.Error().Err(err).Msg("Could not submit contribution transaction")
- return
- }
-
- log.Info().Msg(fmt.Sprintf("Successful Transaction: { Ledger: %d, Hash: %s }", response.Ledger, response.Hash))
-
- var result SuccessResponse
- result.Success = response.Successful && err == nil
-
- err = json.NewEncoder(resp).Encode(&result)
- if err != nil {
- log.Error().Err(err).Msg("Could not create response for new contribution")
- }
- }
|