Skip to content

Commit

Permalink
Fix nft auction
Browse files Browse the repository at this point in the history
Fixes
  • Loading branch information
Boldizsar Mezei committed Sep 25, 2023
1 parent 6f65aa1 commit a09d98c
Show file tree
Hide file tree
Showing 7 changed files with 406 additions and 118 deletions.
141 changes: 88 additions & 53 deletions .github/workflows/functions_tangle-online-unit-tests_emulator.yml

Large diffs are not rendered by default.

151 changes: 93 additions & 58 deletions .github/workflows/functions_tangle-unit-tests.yml

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions packages/database/scripts/db.upgrade.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { COL } from '@build-5/interfaces';
import crypto from 'crypto';
import dotenv from 'dotenv';
import admin from 'firebase-admin';
import { getFirestore } from 'firebase-admin/firestore';
import fs from 'fs';
import { globSync } from 'glob';
import { FirebaseApp } from '../src/app/app';
import serviceAccount from './serviceAccountKey.json';

dotenv.config({ path: '../.env' });

const app = admin.initializeApp({
credential: admin.credential.cert(serviceAccount as any),
});
process.env.FIREBASE_CONFIG = JSON.stringify({ projectId: serviceAccount.project_id });

const execute = async () => {
const db = getFirestore(app);
const files = globSync(`./dbUpgrades/**/*.ts`);
for (const file of files.sort()) {
const content = fs.readFileSync(file);
const hash = crypto.createHash('sha1').update(content).digest('hex');

const docRef = db.doc(`${COL.DB_ROLL_FILES}/${hash}`);
const doc = await docRef.get();
if (doc.exists) {
console.warn(`${file} script was already ran`);
continue;
}

console.log(`Running ${file}`);
const func = await import(pathToImportFileName(file));
await func.roll(new FirebaseApp(app));
await docRef.create({});
}
};

const pathToImportFileName = (path: string) => './' + path.replace('.ts', '');

execute();
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import {
COL,
Timestamp,
Transaction,
TransactionPayloadType,
TransactionType,
} from '@build-5/interfaces';
import { FirebaseApp } from '../../../src/app/app';
import { Firestore } from '../../../src/firestore/firestore';

export const creditHighestPayment = async (app: FirebaseApp) => {
const db = new Firestore(app);

if (app.getName() !== 'soonaverse') {
console.log('Not prod env');
return;
}

const paymentUid = '0xe50e40db6c583e89733fd1b084e30e1d7b878755';
const batch = db.batch();

const paymentDocRef = db.doc(`${COL.TRANSACTION}/${paymentUid}`);
const payment = <Transaction>await paymentDocRef.get();

batch.update(paymentDocRef, { 'payload.invalidPayment': true });

// was generated randomly elswhere so getRandomEthAddress is not needed here,
const creditUid = '0x3c368f6d447e5b703fd5b2d3a9d276809d03affe';
const credit: Transaction = {
type: TransactionType.CREDIT,
uid: creditUid,
space: payment.space,
member: payment.member,
createdOn: Timestamp.now(),
network: payment.network,
payload: {
type: TransactionPayloadType.DATA_NO_LONGER_VALID,
amount: payment.payload.amount,
sourceAddress: payment.payload.targetAddress,
targetAddress: payment.payload.sourceAddress,
sourceTransaction: [payment.uid],
nft: payment.payload.nft || null,
reconciled: true,
void: false,
collection: payment.payload.collection || null,
invalidPayment: true,
},
ignoreWallet: false,
};
const creditDocRef = db.doc(`${COL.TRANSACTION}/${credit.uid}`);
batch.create(creditDocRef, credit);

await batch.commit();
};

export const roll = creditHighestPayment;
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export const getNftSetForSaleParams = async (params: NftSetForSaleRequest, owner
throw invalidArgument(WenError.nft_does_not_exists);
}

if (nft.auctionFrom && dayjs(nft.auctionFrom.toDate()).isBefore(dayjs())) {
throw invalidArgument(WenError.nft_auction_already_in_progress);
}

if (nft.setAsAvatar) {
throw invalidArgument(WenError.nft_set_as_avatar);
}
Expand All @@ -68,10 +72,6 @@ export const getNftSetForSaleParams = async (params: NftSetForSaleRequest, owner
params.auctionFrom = dateToTimestamp(params.auctionFrom, true).toDate();
}

if (params.auctionFrom && nft.auctionFrom && dayjs(nft.auctionFrom.toDate()).isBefore(dayjs())) {
throw invalidArgument(WenError.nft_auction_already_in_progress);
}

const collectionDocRef = build5Db().doc(`${COL.COLLECTION}/${nft.collection}`);
const collection = await collectionDocRef.get<Collection>();
if (![CollectionStatus.PRE_MINTED, CollectionStatus.MINTED].includes(collection?.status!)) {
Expand Down
6 changes: 3 additions & 3 deletions packages/functions/test-tangle/nft-set-for-sale/Helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,11 @@ export class Helper {
media: MEDIA,
});

public dummyAuctionData = (uid: string) => ({
public dummyAuctionData = (uid: string, availableFrom?: Date, auctionFrom?: Date) => ({
nft: uid,
price: MIN_IOTA_AMOUNT,
availableFrom: dayjs().toDate(),
auctionFrom: dayjs().toDate(),
availableFrom: availableFrom || dayjs().toDate(),
auctionFrom: auctionFrom || dayjs().toDate(),
auctionFloorPrice: MIN_IOTA_AMOUNT,
auctionLength: 60000 * 4,
access: NftAccess.OPEN,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
COL,
MIN_IOTA_AMOUNT,
Network,
Nft,
NftAvailable,
NftSetForSaleTangleRequest,
TangleRequestType,
Transaction,
TransactionType,
WenError,
} from '@build-5/interfaces';
import dayjs from 'dayjs';
import { build5Db } from '../../src/firebase/firestore/build5Db';
import { MnemonicService } from '../../src/services/wallet/mnemonic';
import { wait } from '../../test/controls/common';
import { getTangleOrder } from '../common';
import { requestFundsFromFaucet } from '../faucet';
import { Helper } from './Helper';

describe('Nft set for acution OTR', () => {
const helper = new Helper();
let tangleOrder: Transaction;

beforeAll(async () => {
await helper.beforeAll();
tangleOrder = await getTangleOrder();
});

beforeEach(async () => {
await helper.beforeEach();
});

it('Should throw, nft auction already in progress', async () => {
await helper.createAndOrderNft();

await requestFundsFromFaucet(Network.RMS, helper.guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT);

let auctionData = helper.dummyAuctionData(
helper.nft.uid,
dayjs().add(1, 'h').toDate(),
dayjs().add(1, 'h').toDate(),
);
await helper.walletService!.send(
helper.guardianAddress,
tangleOrder.payload.targetAddress!,
MIN_IOTA_AMOUNT,
{
customMetadata: {
request: {
requestType: TangleRequestType.NFT_SET_FOR_SALE,
...auctionData,
} as NftSetForSaleTangleRequest,
},
},
);
await MnemonicService.store(helper.guardianAddress.bech32, helper.guardianAddress.mnemonic);

const nftDocRef = build5Db().doc(`${COL.NFT}/${helper.nft.uid}`);
await wait(async () => {
helper.nft = (await nftDocRef.get<Nft>())!;
return helper.nft.available === NftAvailable.AUCTION_AND_SALE;
});

auctionData = helper.dummyAuctionData(helper.nft.uid);
await helper.walletService!.send(
helper.guardianAddress,
tangleOrder.payload.targetAddress!,
MIN_IOTA_AMOUNT,
{
customMetadata: {
request: {
requestType: TangleRequestType.NFT_SET_FOR_SALE,
...auctionData,
} as NftSetForSaleTangleRequest,
},
},
);
await MnemonicService.store(helper.guardianAddress.bech32, helper.guardianAddress.mnemonic);

const credit = build5Db()
.collection(COL.TRANSACTION)
.where('member', '==', helper.guardian)
.where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST);
await wait(async () => {
const snap = await credit.get<Transaction>();
return snap.length === 2;
});
const succeses = (await credit.get<Transaction>()).filter(
(t) => t.payload.response?.status === 'success',
);
expect(succeses.length).toBe(2);

auctionData = helper.dummyAuctionData(helper.nft.uid);
await helper.walletService!.send(
helper.guardianAddress,
tangleOrder.payload.targetAddress!,
MIN_IOTA_AMOUNT,
{
customMetadata: {
request: {
requestType: TangleRequestType.NFT_SET_FOR_SALE,
...auctionData,
} as NftSetForSaleTangleRequest,
},
},
);

await wait(async () => {
const snap = await credit.get<Transaction>();
return snap.length === 3;
});
const snap = await credit.get<Transaction>();
const creditTransction = snap.find(
(t) => t.payload.response?.code === WenError.nft_auction_already_in_progress.code,
);
expect(creditTransction).toBeDefined();
});
});

0 comments on commit a09d98c

Please sign in to comment.