Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vik #2

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
37 changes: 10 additions & 27 deletions lib/api/api.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@
import { Marketplace } from "../marketplace";
import express from 'express'
import bodyParser from 'body-parser'
import { OrderFront } from "../types/common";
import { graphqlHTTP } from "express-graphql";
import { schema } from "./schema";

// import { ApolloServer} from "apollo-server";
import express from "express";
import { ApolloServer } from 'apollo-server-express';
const {graphqlUploadExpress} = require("graphql-upload");

export async function start(marketplace: Marketplace) {

const app = express()
const jsonParser = bodyParser.json()

app.use(
"/graphql",
graphqlHTTP({
schema: schema(marketplace),
graphiql: true,
}));

app.post('/orders', jsonParser, async (req: any, res: any) => res.json(await marketplace.createOrder(OrderFront.fromJson(req.body))));
app.get('/orders', async (req: any, res: any) => res.json(await marketplace.getOrders()));
app.get('/orders/:orderId', async (req: any, res: any) => res.json(await marketplace.getOrder(req.params.orderId)));
app.get('/tokens', async (req: any, res: any) => res.json(await marketplace.getTokens()));
app.post('/asset/create', async (req: any, res: any) => res.set('Status Code', 202));


console.log("starting")
app.listen(8080);

const app = express();
app.use(graphqlUploadExpress());
const server = new ApolloServer({schema: schema(marketplace)});
await server.start();
server.applyMiddleware({ app });
await new Promise<void>(resolve => app.listen({ port: 8080 }, resolve));
}

147 changes: 128 additions & 19 deletions lib/api/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,45 @@ import {
GraphQLString
} from "graphql";

import {Order, TokensCollection} from "../types/mongo";
import {Order, TokensCollection, Tokens} from "../types/mongo";
import {OrderFront} from "../types/common";
import {Marketplace} from "../marketplace";

const {GraphQLUpload} = require("graphql-upload");

// import {util} from "prettier";
// import skip = util.skip;


export function schema(marketplace: Marketplace): GraphQLSchema {
// const FileType = new GraphQLObjectType({
// name: "FileType",
// fields: () => ({
// filename: {type: GraphQLString},
// mimetype: {type: GraphQLString},
// encoding: {type: GraphQLString}
// })
// });


const PageInfoType = new GraphQLObjectType({
name: "PageInfo",
fields: () => ({
hasNext: {type: GraphQLBoolean},
nextCursor: {type: GraphQLString}
})
});


const Page = (itemType: any, pageName: any) => {
return new GraphQLObjectType({
name: pageName,
fields: () => ({
results: {type: new GraphQLList(itemType)},
pageInfo: {type: PageInfoType}
})
});
}


const TokenOwnersType = new GraphQLScalarType({
Expand All @@ -37,13 +70,27 @@ export function schema(marketplace: Marketplace): GraphQLSchema {
})
});

const EventType = new GraphQLObjectType({
name: "Event",
fields: () => ({
from: {type: GraphQLString},
to: {type: GraphQLString},
quantity: {type: GraphQLInt},
timestamp: {type: GraphQLInt},
txHash: {type: GraphQLString},
})
});

const TokenType = new GraphQLObjectType({
name: "Token",
fields: () => ({
collectionObjectId: {type: GraphQLString},
tokenId: {type: GraphQLString},
metadata_uri: {type: GraphQLString},
metadata: {type: MetadataType},
last_update: {type: GraphQLInt},
owners: {type: TokenOwnersType},
events: {type: new GraphQLList(EventType)}
})
});

Expand All @@ -54,7 +101,6 @@ export function schema(marketplace: Marketplace): GraphQLSchema {
contractAddress: {type: GraphQLString},
tokenType: {type: GraphQLInt},
owner: {type: GraphQLString},
tokens: {type: new GraphQLList(TokenType),}
})
});

Expand Down Expand Up @@ -86,26 +132,78 @@ export function schema(marketplace: Marketplace): GraphQLSchema {
fields: () => ({
tokensCollection: {
type: new GraphQLList(TokensCollectionType),
resolve: () => {
resolve: async () => {
return TokensCollection
.find({tokenType: {$ne: null}})
.sort({'tokens.last_update': 1});
.find({tokenType: {$ne: null}})
.sort({'tokens.last_update': 1});
}
},

getTokens: {
type: Page(TokenType, "AllTokensPage"),
args: {
first: {type: GraphQLInt},
cursor: {type: GraphQLString }
},
resolve: async (_, args) => {
args.cursor = args.cursor === null ? undefined : args.cursor;

// @ts-ignore
return Tokens
.find({})
.sort({last_update: -1})
.limit(args.first)
.paginate(args.cursor) // noinspection
}
},

getTokensByOwner: {
type: new GraphQLList(TokensCollectionType),
args: {owner: {type: GraphQLString}},
resolve: (_, args) => {
return TokensCollection.find({
tokenType: {$ne: null},
tokens: {$elemMatch: {[`owners.${args.owner}`]: {$gt: 0}}}
})
type: Page(TokenType, "TokensByOwnerPage"),
args: {
owner: {type: GraphQLString},
first: {type: GraphQLInt},
cursor: {type: GraphQLString }
},
resolve: async (_, args) => {
args.cursor = args.cursor === null ? undefined : args.cursor;

// @ts-ignore
return Tokens
.find({[`owners.${args.owner}`]: {$gt: 0}})
.sort({last_update: -1})
.limit(args.first)
.paginate(args.cursor) // noinspection
}
},

getSpecificToken: {
type: Page(TokenType, "SpecificTokens"),
args: {
tokenId: {type: GraphQLString},
metadataName: {type: GraphQLString},
owner: {type: GraphQLString},
first: {type: GraphQLInt},
cursor: {type: GraphQLString }
},
resolve: async (_, args) => {
args.cursor = args.cursor === null ? undefined : args.cursor;

// @ts-ignore
return Tokens
.find({$or: [
{[`owners.${args.owner}`]: {$gt: 0}},
{"metadata.name": args.metadataName},
{"tokenId": args.tokendId},
]})
.sort({last_update: -1})
.limit(args.first)
.paginate(args.cursor) // noinspection
}
},

orders: {
type: new GraphQLList(OrderType),
resolve: () => {
resolve: async () => {
return Order.find({}).sort({createTime: 1})
}
},
Expand All @@ -116,15 +214,15 @@ export function schema(marketplace: Marketplace): GraphQLSchema {
contractAddress: {type: GraphQLString},
tokenId: {type: GraphQLString},
},
resolve: (_, args) => {
resolve: async (_, args) => {
const {contractAddress, tokenId} = args
const filter = {contractAddress, tokens: {tokenId}}
return Order
.find({$or: [
{left: {filter}},
{right: {filter}},
]})
.sort({createTime: 1})
.find({$or: [
{left: {filter}},
{right: {filter}},
]})
.sort({createTime: 1})
}
},

Expand All @@ -145,6 +243,17 @@ export function schema(marketplace: Marketplace): GraphQLSchema {
await marketplace.createOrder(order);
return true;
}
},

uploadFile: {
type: GraphQLBoolean,
args: {file: {type: GraphQLUpload}},
resolve: async (_, args) => {
const { createReadStream, filename, mimetype, encoding } = await args.file;
let stream = createReadStream();
// stream.on("readable", () => {console.log(stream.read())});
return true;
}
}
}
})
Expand Down
2 changes: 1 addition & 1 deletion lib/event_logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const interfaceId: { [key in TokenType]?: string } = {
[TokenType.ERC721]: "0x80ac58cd",
}

const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"
const ZERO_ADDRESS = ethers.constants.AddressZero;
const IPFS_GATEWAYS = [
"https://gateway.pinata.cloud/ipfs/",
"https://cloudflare-ipfs.com/ipfs/",
Expand Down
9 changes: 6 additions & 3 deletions lib/types/mongo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { model, Schema } from 'mongoose';
const paginationPlugin = require('@mother/mongoose-cursor-pagination')

// todo https://mongoosejs.com/docs/typescript.html

Expand Down Expand Up @@ -27,6 +28,8 @@ const TokenTransferEventSchema = new Schema({
}, { _id: false });

const TokenSchema = new Schema({
collectionObjectId: String,

tokenId: String,

metadata_uri: String,
Expand All @@ -35,15 +38,15 @@ const TokenSchema = new Schema({
last_update: Number,
owners: { type: Map, of: Number },
events: [TokenTransferEventSchema],
}, { _id: false })
}).plugin(paginationPlugin);

export const Tokens = model("Tokens", TokenSchema);

export const TokensCollection = model('TokensCollection', new Schema({
contractAddress: String,
tokenType: Number,
name: String,
owner: String,

tokens: [TokenSchema],
}));


Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"private": false,
"scripts": {
"api": "ts-node ./lib/main.ts",
"gen fake data": "ts-node ./scripts/gen_fake_tokens.ts",
"build": "hardhat compile",
"deploy": "hardhat deploy --network rinkeby",
"verify": "hardhat etherscan-verify --network rinkeby",
Expand Down Expand Up @@ -36,17 +37,21 @@
},
"dependencies": {
"@gnosis.pm/safe-deployments": "^1.1.0",
"@mother/mongoose-cursor-pagination": "^0.0.5",
"@nomiclabs/hardhat-ethers": "npm:hardhat-deploy-ethers",
"@nomiclabs/hardhat-waffle": "^2.0.1",
"@openzeppelin/contracts": "^4.1.0",
"@pinata/sdk": "^1.1.23",
"@types/dotenv": "^8.2.0",
"@types/mongoose": "^5.11.97",
"apollo-server": "^3.5.0",
"apollo-server-express": "^3.0.0-rc.1",
"dotenv": "^9.0.2",
"ethereum-waffle": "^3.2.0",
"ethers": "^5.5.1",
"express-graphql": "^0.12.0",
"graphql": "^16.0.1",
"graphql-upload": "^13.0.0",
"hardhat": "^2.3.3",
"hardhat-deploy": "^0.8.11",
"hardhat-deploy-ethers": "0.3.0-beta.10",
Expand Down
Loading