Skip to content

Commit

Permalink
Merge pull request #204 from NetSepio/main
Browse files Browse the repository at this point in the history
Merging main with prod
  • Loading branch information
Rushikeshnimkar authored Sep 4, 2024
2 parents 1b84f32 + ff7f294 commit 46d1107
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 169 deletions.
258 changes: 95 additions & 163 deletions api/v1/dvpnnft/dvpnnft.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"net/http"
"regexp"

contract "github.com/NetSepio/gateway/api/v1/dvpnnft/contract" // Replace with the actual path to your contract bindings
contract "github.com/NetSepio/gateway/api/v1/dvpnnft/contract"
"github.com/NetSepio/gateway/config/dbconfig"
"github.com/NetSepio/gateway/config/envconfig"
"github.com/NetSepio/gateway/models"
Expand All @@ -27,16 +27,21 @@ type RequestPayload struct {

type ResponsePayload struct {
TransactionHash string `json:"transaction_hash"`
Message string `json:"message,omitempty"`
}
type APTRequestPayload struct {
WalletAddress string `json:"wallet_address"`
EmailID string `json:"email_id"`
}

func ApplyRoutes(r *gin.RouterGroup) {
g := r.Group("/dvpnnft")
{
g.POST("", handleMintNFT)
g.POST("/chain=evm", handleMintNFTEVM)
g.POST("/chain=apt", handleMintNFTAPT)
}
}

func handleMintNFT(c *gin.Context) {
func handleMintNFTEVM(c *gin.Context) {
var payload RequestPayload
if err := c.BindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
Expand Down Expand Up @@ -141,187 +146,114 @@ func handleMintNFT(c *gin.Context) {
}

// Store the transaction hash in the database
if err := storeTransactionHash(payload.WalletAddress, tx.Hash().Hex()); err != nil {
if err := storeNFTRecord("evm", payload.WalletAddress, "", tx.Hash().Hex()); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error storing transaction hash in the database"})
return
}

c.JSON(http.StatusOK, ResponsePayload{
TransactionHash: tx.Hash().Hex(),
})
}

func storeTransactionHash(walletAddress, transactionHash string) error {
db := dbconfig.GetDb()
nft := &models.DVPNNFTRecord{
WalletAddress: walletAddress,
TransactionHash: transactionHash,
}
return db.Create(nft).Error
}
func isValidMantaAddress(address string) bool {
// Manta address format: 0x[0-9a-fA-F]{40}
mantaAddressRegex := `^0x[0-9a-fA-F]{40}$`
match, err := regexp.MatchString(mantaAddressRegex, address)
if err != nil {
return false
}
return match
}

// package dvpnnft

// import (
// "crypto/ecdsa"
// "math/big"
// "net/http"
// "os"
// "regexp"

// contract "github.com/NetSepio/gateway/api/v1/dvpnnft/contract" // Replace with the actual path to your contract bindings
// "github.com/NetSepio/gateway/config/dbconfig"
// "github.com/NetSepio/gateway/models"
// "github.com/ethereum/go-ethereum/accounts/abi/bind"
// "github.com/ethereum/go-ethereum/common"
// "github.com/ethereum/go-ethereum/crypto"
// "github.com/ethereum/go-ethereum/ethclient"
// "github.com/gin-gonic/gin"
// "github.com/joho/godotenv"
// )

// type RequestPayload struct {
// WalletAddress string `json:"wallet_address"`
// }

// type ResponsePayload struct {
// TransactionHash string `json:"transaction_hash"`
// }

// func ApplyRoutes(r *gin.RouterGroup) {
// g := r.Group("/dvpnnft")
// {
// g.POST("", handleMintNFT)
// func storeTransactionHash(walletAddress, transactionHash string) error {
// db := dbconfig.GetDb()
// nft := &models.DVPNNFTRecord{
// WalletAddress: walletAddress,
// TransactionHash: transactionHash,
// }
// return db.Create(nft).Error
// }

// func handleMintNFT(c *gin.Context) {
// var payload RequestPayload
// if err := c.BindJSON(&payload); err != nil {
// c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
// return
// }

// // Load environment variables from the .env file
// if err := godotenv.Load(); err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error loading .env file"})
// return
// }
//-------------------------aptos -------------------------------------------

// // Check if the wallet address is a valid Manta address
// if !isValidMantaAddress(payload.WalletAddress) {
// c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Manta wallet address"})
// return
// }
func handleMintNFTAPT(c *gin.Context) {
var payload APTRequestPayload
if err := c.BindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
return
}
fmt.Printf("Received Aptos address: %s\n", payload.WalletAddress)
fmt.Printf("Is valid Aptos address: %v\n", isValidAptosAddress(payload.WalletAddress))

// // Connect to the Ethereum client
// client, err := ethclient.Dial("https://rpc-amoy.polygon.technology/")
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to connect to Ethereum client"})
// return
// }
// Check if the wallet address and email are valid and don't exist in the database
if !isValidAptosAddress(payload.WalletAddress) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Aptos wallet address"})
return
}

// // Load the private key from the environment
// privateKey, err := crypto.HexToECDSA(os.Getenv("PRIVATE_KEY"))
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error loading private key"})
// return
// }
if !isValidEmail(payload.EmailID) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid email address"})
return
}

// // Get the public key and address
// publicKey := privateKey.Public()
// publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
// if !ok {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error casting public key to ECDSA"})
// return
// }
if exists, err := checkWalletAddressExists(payload.WalletAddress, "apt"); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
return
} else if exists {
c.JSON(http.StatusConflict, gin.H{"error": "Wallet address already exists"})
return
}

// fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
// nonce, err := client.PendingNonceAt(c, fromAddress)
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error getting nonce"})
// return
// }
if exists, err := checkEmailExists(payload.EmailID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
return
} else if exists {
c.JSON(http.StatusConflict, gin.H{"error": "Email address already exists"})
return
}

// gasPrice, err := client.SuggestGasPrice(c)
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error getting gas price"})
// return
// }
// TODO: Implement Aptos minting logic here

// chainID, err := client.NetworkID(c)
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error getting chain ID"})
// return
// }
// For now, we'll just store the record without a transaction hash
if err := storeNFTRecord("apt", payload.WalletAddress, payload.EmailID, ""); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error storing data"})
return
}

// auth, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error creating transactor"})
// return
// }
// auth.Nonce = big.NewInt(int64(nonce))
// auth.Value = big.NewInt(0) // in wei
// auth.GasLimit = uint64(300000) // Adjust as needed
// auth.GasPrice = gasPrice

// // Contract address
// contractAddress := common.HexToAddress(os.Getenv("CONTRACT_ADDRESS"))
// instance, err := contract.NewContract(contractAddress, client)
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error creating contract instance"})
// return
// }
c.JSON(http.StatusOK, ResponsePayload{
Message: "Aptos NFT minting record created",
})
}

// // Call the mint function
// tx, err := instance.DelegateMint(auth, common.HexToAddress(payload.WalletAddress))
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error calling Mint function"})
// return
// }
func isValidMantaAddress(address string) bool {
mantaAddressRegex := `^0x[0-9a-fA-F]{40}$`
match, _ := regexp.MatchString(mantaAddressRegex, address)
return match
}

// // Store the transaction hash in the database
// if err := storeTransactionHash(payload.WalletAddress, tx.Hash().Hex()); err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error storing transaction hash in the database"})
// return
// }
func isValidAptosAddress(address string) bool {
aptosAddressRegex := `^0x[0-9a-fA-F]{64}$`
match, _ := regexp.MatchString(aptosAddressRegex, address)
return match
}

// // Wait for the transaction to be mined
// _, err = client.TransactionReceipt(c, tx.Hash())
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Error waiting for transaction to be mined"})
// return
// }
func isValidEmail(email string) bool {
emailRegex := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
match, _ := regexp.MatchString(emailRegex, email)
return match
}

// c.JSON(http.StatusOK, ResponsePayload{
// TransactionHash: tx.Hash().Hex(),
// })
// }
func checkWalletAddressExists(walletAddress, chain string) (bool, error) {
db := dbconfig.GetDb()
var count int64
result := db.Model(&models.DVPNNFTRecord{}).Where("wallet_address = ? AND chain = ?", walletAddress, chain).Count(&count)
return count > 0, result.Error
}

// func storeTransactionHash(walletAddress, transactionHash string) error {
// db := dbconfig.GetDb()
// nft := &models.DVPNNFTRecord{
// WalletAddress: walletAddress,
// TransactionHash: transactionHash,
// }
// return db.Create(nft).Error
// }
func checkEmailExists(email string) (bool, error) {
db := dbconfig.GetDb()
var count int64
result := db.Model(&models.DVPNNFTRecord{}).Where("email_id = ?", email).Count(&count)
return count > 0, result.Error
}

// func isValidMantaAddress(address string) bool {
// // Manta address format: 0x[0-9a-fA-F]{40}
// mantaAddressRegex := `^0x[0-9a-fA-F]{40}$`
// match, err := regexp.MatchString(mantaAddressRegex, address)
// if err != nil {
// return false
// }
// return match
// }
func storeNFTRecord(chain, walletAddress, emailID, transactionHash string) error {
db := dbconfig.GetDb()
nft := &models.DVPNNFTRecord{
Chain: chain,
WalletAddress: walletAddress,
EmailID: emailID,
TransactionHash: transactionHash,
}
return db.Create(nft).Error
}
6 changes: 4 additions & 2 deletions config/dbconfig/dbconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ func GetDb() *gorm.DB {

func Init() error {
db := GetDb()

// db.Exec(`ALTER TABLE leader_boards DROP COLUMN IF EXISTS users;`)
db.Exec(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`)

if err := db.AutoMigrate(
&migrate.User{},
&migrate.Role{},
Expand Down Expand Up @@ -79,8 +83,6 @@ func Init() error {
log.Fatal(err)
}

// db.Exec(`ALTER TABLE leader_boards DROP COLUMN IF EXISTS users;
// CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`)
logwrapper.Log.Info("Congrats ! Automigration completed")

return nil
Expand Down
6 changes: 4 additions & 2 deletions models/DVPNNFTRecord.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import (
)

type DVPNNFTRecord struct {
ID uint `gorm:"primaryKey;autoIncrement"`
WalletAddress string
ID uint `gorm:"primaryKey;autoIncrement"`
Chain string `gorm:"not null"`
WalletAddress string `gorm:"not null"`
EmailID string
TransactionHash string
CreatedAt time.Time `gorm:"not null;default:CURRENT_TIMESTAMP"`
}
6 changes: 4 additions & 2 deletions models/Migrate/migrate_models.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,10 @@ type NftSubscription struct {
}

type DVPNNFTRecord struct {
ID uint `gorm:"primaryKey;autoIncrement"`
WalletAddress string
ID uint `gorm:"primaryKey;autoIncrement"`
Chain string
WalletAddress string `gorm:"not null"`
EmailID string
TransactionHash string
CreatedAt time.Time `gorm:"not null;default:CURRENT_TIMESTAMP"`
}

0 comments on commit 46d1107

Please sign in to comment.