This commit is contained in:
2024-11-20 19:53:30 +08:00
parent dc8d01a6f8
commit d31f0fbecd
6 changed files with 3178 additions and 12 deletions

View File

@@ -1,11 +1,11 @@
import mysql from 'mysql2'; import mysql from 'mysql2';
import {Keypair} from '@solana/web3.js'; import {Keypair, Connection, PublicKey} from '@solana/web3.js';
import {createAssociatedTokenAccount} from '@solana/spl-token';
import bs58 from 'bs58'; import bs58 from 'bs58';
import {GenerateATAs} from './sol.js';
import dotenv from 'dotenv'; import dotenv from 'dotenv';
dotenv.config(); dotenv.config();
const newWallet = Keypair.generate();
const pool = mysql.createPool({ const pool = mysql.createPool({
host: process.env.MYSQL_HOST, host: process.env.MYSQL_HOST,
@@ -14,9 +14,49 @@ const pool = mysql.createPool({
database: process.env.MYSQL_DATABASE database: process.env.MYSQL_DATABASE
}).promise(); }).promise();
// const UsersInsertQuery = await pool.query(`INSERT INTO Users (pub_key, email,password) VALUES(${newWallet.publicKey.toBase58()}, email@gmail.com, securepass)`);
// const PrivateKeyInsertQuery = await pool.query(`INSERT INTO PrivateKeys (pub_key, private_key) VALUES(${newWallet.publicKey.toBase58()}, ${bs58.encode(newWallet.secretKey)})`);
const [rows] = await pool.query('SELECT * FROM Users'); export async function RegisterNewUser(email,password){
const existingUser = await GetUserFromEmail(email);
if(existingUser){
return undefined;
}
console.log(rows); const newWallet = Keypair.generate();
const pubKey=newWallet.publicKey.toBase58();
//GenerateATAs(newWallet);
await pool.query(`INSERT INTO Users (pub_key, email,password) VALUES(?, ?, ?)`, [pubKey, email, password]);
await pool.query(`INSERT INTO PrivateKeys (pub_key, private_key) VALUES(?, ?)`, [pubKey, bs58.encode(newWallet.secretKey)]);
return {
email: email,
publicKey: pubKey
}
}
export async function GetUserFromEmail(email){
const [rows] = await pool.query("SELECT pub_key,email FROM Users WHERE email=?", [email]);
return rows[0];
}
export async function GetUserFromPubkey(pubkey){
const [rows] = await pool.query("SELECT pub_key,email FROM Users WHERE pub_key=?", [pubkey]);
return rows[0];
}
export async function Authneticate(email, password){
const [rows] = await pool.query("SELECT pub_key,email FROM Users WHERE email=? AND password=?", [email, password]);
return rows.length >0;
}
export async function GetPrivateKey(pubkey){
const [rows] = await pool.query("SELECT private_key FROM PrivateKeys WHERE pub_key=?", [pubkey]);
return rows[0];
}
export async function GetKeypairFromEmail(email){
const [rows] = await pool.query("SELECT Users.pub_key,Users.email, PrivateKeys.private_key FROM Users JOIN PrivateKeys ON Users.pub_key = PrivateKeys.pub_key WHERE email=?", [email]);
return rows[0];
}

127
index.js
View File

@@ -1,7 +1,124 @@
import {Keypair} from '@solana/web3.js'; import express from 'express';
import bs58 from 'bs58'; import dotenv from 'dotenv';
const newWallet = Keypair.generate(); import {RegisterNewUser, GetUserFromEmail, GetUserFromPubkey, GetKeypairFromEmail, Authneticate} from './database.js';
console.log(newWallet.publicKey.toBase58()); dotenv.config();
console.log(bs58.encode(newWallet.secretKey));
const app = express();
app.use((err,req,res,next)=>{
console.error(err.stack);
res.status(500).send("Something went wrong!");
})
//----------------------------------------------------------------------------------------------------------------------------------------------------------------
app.get("/register", async (req,res)=>{
const {email, password} = req.query;
if(!email || !password){
res.status(403).json({error: "Missing credentials"});
return;
}
const newUser = await RegisterNewUser(email,password);
if(!newUser){
res.status(403).json({error: "Email exists"});
}
res.status(201).json(newUser);
})
app.get("/login", async(req,res)=>{
const {email, pubkey} = req.query;
if(!email && !pubkey){
res.status(403).json({error:"Neither email nor pubkey was sent"})
return;
}
if(email){
const user = await GetUserFromEmail(email);
if(user){
res.status(200).json(user);
}else{
res.status(404).json({error:"User couldnt be found"})
}
}else if(pubkey){
const user = await GetUserFromPubkey(pubkey);
if(user){
res.status(200).json(user);
}else{
res.status(404).json({error:"User couldnt be found"})
}
}
})
app.get("/authenticate", async(req,res)=>{
const {email, password} = req.query;
if(!email || !password){
res.status(403).json({error:"Credentials missing"})
return;
}
const authResult = await Authneticate(email,password);
if(authResult){
res.status(200).json({authenticated: true})
}else{
res.status(403).json({authenticated: false})
}
})
app.get("/getKeypairWithPassword", async(req,res)=>{
const {email, password} = req.query;
if(!email || !password){
res.status(403).json({error:"Credentials missing"})
return;
}
const authResult = await Authneticate(email,password);
if(authResult){
const user = await GetKeypairFromEmail(email);
res.status(200).json(user)
}else{
res.status(403).json({authenticated: false})
}
})
app.get("/getPubkey", async(req,res)=>{
const {email}= req.query;
if(!email){
res.status(403).json({error: "Missing credentials"});
return;
}
const user = await GetUserFromEmail(email);
res.status(200).json(user);
})
app.get("/getKeypair", async(req,res)=>{
const {email, apiKey}= req.query;
if(!email || !apiKey){
res.status(403).json({error: "Missing credentials"});
return;
}
if(apiKey!= process.env.API_KEY){
res.status(403).json({error: `Invalid Api Key`});
console.log(`Provided api key: ${apiKey}`);
console.log(`Correcte api key: ${process.env.API_KEY}`);
return;
}
const user = await GetKeypairFromEmail(email);
res.status(200).json(user);
})
//----------------------------------------------------------------------------------------------------------------------------------------------------------------
app.listen(process.env.EXPRESS_PORT, ()=>{
console.log(`Server is listening on Port ${process.env.EXPRESS_PORT}`);
})

2546
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,9 +10,13 @@
"description": "", "description": "",
"type": "module", "type": "module",
"dependencies": { "dependencies": {
"@project-serum/anchor": "^0.26.0",
"@solana/spl-token": "^0.4.9",
"@solana/web3.js": "^1.95.4", "@solana/web3.js": "^1.95.4",
"bs58": "^6.0.0", "bs58": "^6.0.0",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1",
"firebase-admin": "^13.0.0",
"mysql2": "^3.11.3" "mysql2": "^3.11.3"
} }
} }

45
sol.js Normal file
View File

@@ -0,0 +1,45 @@
import {Keypair, Connection, PublicKey, clusterApiUrl} from '@solana/web3.js';
import {createAssociatedTokenAccount} from '@solana/spl-token';
// import { GetPrivateKey } from './database.js';
// import {AnchorProvider, Wallet, setProvider} from '@project-serum/anchor';
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
// const ticketStoreIdl = require('./ticket_store_idl.json');
// const ticketStoreProgramId = new PublicKey("5kgwVNdKDndFYNkUhZ5TvkNXxEJngMSczfS61qNALhzJ");
// const ticketStoreProgram = new Program(ticketStoreIdl, ticketStoreProgramId);
const tokenMint = new PublicKey("vcHyeKhk67CVumjzYV3m8cf6V8xcE85N9ay48pcyUpB");
const ticketsMint = new PublicKey("tktUDLZhFGb9VW9zDxZ7HYDFuBooEf8daZEvPbBY7at");
export async function GenerateATAs(wallet){
let tokenAta = await createAssociatedTokenAccount(
connection,
wallet,
tokenMint,
wallet.publicKey,
);
console.log(`Tokens ATA: ${tokenAta.toBase58()}`);
let ticketsAta = await createAssociatedTokenAccount(
connection,
wallet,
ticketsMint,
wallet.publicKey,
);
console.log(`Tickets ATA: ${ticketsAta.toBase58()}`);
}
// export async function PurchaseTickets(pubkey, amount){
// const privateKey = GetPrivateKey(pubkey); //string
// const keypair = Keypair.fromSecretKey(privateKey);
// const provider = new AnchorProvider(connection, new Wallet(keypair));
// setProvider(provider);
// await ticketStoreProgram.methods.purchaseTickets(new BN(amount)).accounts({
// mint: ticketsMint
// }).rpc();
// }

414
ticket_store_idl.json Normal file
View File

@@ -0,0 +1,414 @@
{
"address": "5kgwVNdKDndFYNkUhZ5TvkNXxEJngMSczfS61qNALhzJ",
"metadata": {
"name": "ticket_store",
"version": "0.1.0",
"spec": "0.1.0",
"description": "Created with Anchor"
},
"instructions": [
{
"name": "add_seller",
"discriminator": [
146,
192,
28,
179,
211,
8,
182,
81
],
"accounts": [
{
"name": "signer",
"writable": true,
"signer": true
},
{
"name": "sales_account",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
115,
97,
108,
101,
115
]
},
{
"kind": "account",
"path": "signer"
}
]
}
},
{
"name": "signer_token_account",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
116,
105,
99,
107,
101,
116,
95,
115,
101,
108,
108,
101,
114
]
},
{
"kind": "account",
"path": "signer"
},
{
"kind": "account",
"path": "mint"
}
]
}
},
{
"name": "sellers_registry",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
115,
97,
108,
101,
115,
95,
114,
101,
103
]
}
]
}
},
{
"name": "mint"
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
}
],
"args": []
},
{
"name": "initialize",
"discriminator": [
175,
175,
109,
31,
13,
152,
155,
237
],
"accounts": [
{
"name": "signer",
"writable": true,
"signer": true
},
{
"name": "sellers_registry",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
115,
97,
108,
101,
115,
95,
114,
101,
103
]
}
]
}
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
}
],
"args": []
},
{
"name": "purchase_tickets",
"discriminator": [
146,
121,
85,
207,
182,
70,
169,
155
],
"accounts": [
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "owner",
"writable": true,
"signer": true,
"relations": [
"sales"
]
},
{
"name": "buyer_ata",
"writable": true,
"pda": {
"seeds": [
{
"kind": "account",
"path": "payer"
},
{
"kind": "const",
"value": [
6,
221,
246,
225,
215,
101,
161,
147,
217,
203,
225,
70,
206,
235,
121,
172,
28,
180,
133,
237,
95,
91,
55,
145,
58,
140,
245,
133,
126,
255,
0,
169
]
},
{
"kind": "account",
"path": "mint"
}
],
"program": {
"kind": "const",
"value": [
140,
151,
37,
143,
78,
36,
137,
241,
187,
61,
16,
41,
20,
142,
13,
131,
11,
90,
19,
153,
218,
255,
16,
132,
4,
142,
123,
216,
219,
233,
248,
89
]
}
}
},
{
"name": "mint"
},
{
"name": "sales",
"writable": true
},
{
"name": "seller_ata",
"relations": [
"sales"
]
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "associated_token_program",
"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
}
],
"args": [
{
"name": "amount",
"type": "u64"
}
]
}
],
"accounts": [
{
"name": "Sales",
"discriminator": [
173,
165,
151,
131,
107,
95,
166,
32
]
},
{
"name": "SellersRegistry",
"discriminator": [
53,
71,
248,
136,
244,
177,
37,
10
]
}
],
"errors": [
{
"code": 6000,
"name": "CustomError",
"msg": "Custom error message"
},
{
"code": 6001,
"name": "InsufficientFunds",
"msg": "Insufficient funds to purchase a ticket, Recharge your wallet and try again"
}
],
"types": [
{
"name": "Sales",
"type": {
"kind": "struct",
"fields": [
{
"name": "owner",
"type": "pubkey"
},
{
"name": "seller_ata",
"type": "pubkey"
},
{
"name": "sales_count",
"type": "u64"
},
{
"name": "last_buyer",
"type": "pubkey"
}
]
}
},
{
"name": "SellersRegistry",
"type": {
"kind": "struct",
"fields": [
{
"name": "sales_pdas",
"type": {
"vec": "pubkey"
}
}
]
}
}
],
"constants": [
{
"name": "ID",
"type": "string",
"value": "\"\""
},
{
"name": "SELLERS_REGISTRY_SEED",
"type": {
"array": [
"u8",
9
]
},
"value": "[115, 97, 108, 101, 115, 95, 114, 101, 103]"
}
]
}