|
- package endpoints
-
- import (
- "encoding/json"
- "fmt"
- . "github.com/imosed/signet/data"
- "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"
- "net/http"
- "strings"
- )
-
- 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 {
- panic("Could not read in contribution")
- }
-
- var fund RewardFund
-
- Db.Table("reward_funds").Select("id", "fund_wallet", "memo", "min_contribution").First(&fund, cont.RewardFund)
-
- if cont.Amount < fund.MinContribution || !strings.HasPrefix(cont.PrivateKey, "S") {
- err = json.NewEncoder(resp).Encode(&SuccessResponse{Success: false})
- if err != nil {
- panic("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.AccountDetail(sourceReq)
- if err != nil {
- panic("Horizon client: could not get account details")
- }
-
- 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.NewInfiniteTimeout(),
- },
- })
- if err != nil {
- panic("Could not create contribution transaction")
- }
-
- tx, err = tx.Sign(network.TestNetworkPassphrase, source)
- if err != nil {
- panic("Could not sign contribution transaction")
- }
-
- var response horizon.Transaction
- response, err = client.SubmitTransaction(tx)
- if err != nil {
- panic("Could not submit contribution transaction")
- }
-
- fmt.Println("Successful Transaction:")
- fmt.Println("Ledger:", response.Ledger)
- fmt.Println("Hash:", response.Hash)
-
- var result SuccessResponse
- result.Success = response.Successful && err == nil
-
- err = json.NewEncoder(resp).Encode(&result)
- if err != nil {
- panic("Could not create response for new contribution")
- }
- }
|