Compare commits

...
10 Commits
Author SHA1 Message Date
Chris Troutner 6dddfbdcb6 Merge pull request #122 from Permissionless-Software-Foundation/dh-ctr-offr-page
feat(counterOffer): Added new properties to counter offer model
2025-11-25 18:59:41 -08:00
Daniel Gonzalez fc2d7b4b9b feat(counterOffer): Added new properties to counter offer model 2025-11-25 20:57:44 -04:00
Chris Troutner c877898ae7 Merge pull request #121 from Permissionless-Software-Foundation/dh-track-counter-offrs
feat(offers): Track Counter Offers
2025-11-21 15:54:45 -08:00
Daniel Gonzalez 88e27f47f5 feat(offers): Track Counter Offers 2025-11-21 17:34:05 -04:00
Chris Troutner 0057007b4c Merge pull request #120 from Permissionless-Software-Foundation/dh-npub-offer
feat(nostr): Added npub to Offer model
2025-11-13 06:28:42 -08:00
Daniel Gonzalez 8aad93e572 feat(nostr): Added npub to Offer model 2025-11-11 14:48:09 -04:00
Chris Troutner fa0ec3ece2 Merge pull request #119 from Permissionless-Software-Foundation/dh-npub-order
feat(nostr): Added npub to order
2025-11-11 06:56:18 -08:00
Daniel Gonzalez 4f9f2f8370 feat(nostr): Added npub to order 2025-11-10 18:45:37 -04:00
Chris Troutner 0fb93be2cd Merge pull request #118 from Permissionless-Software-Foundation/dh-timer-deleted
feat(chats): Added timer to delete old deleted chat and post database models
2025-11-06 10:58:25 -08:00
Daniel Gonzalez 26dcd6072e feat(chats): Added timer to delete old deleted chat and post database models 2025-11-06 11:42:46 -04:00
23 changed files with 697 additions and 17 deletions
+2
View File
@@ -11,6 +11,7 @@ import Usage from './models/usage.js'
import SmAccount from './models/smAccount.js'
import DeletedChat from './models/deletedChat.js'
import DeletedPost from './models/deletedPost.js'
import CounterOffer from './models/counter-offer.js'
class LocalDB {
constructor () {
@@ -23,6 +24,7 @@ class LocalDB {
this.SmAccount = SmAccount
this.DeletedChat = DeletedChat
this.DeletedPost = DeletedPost
this.CounterOffer = CounterOffer
}
}
@@ -0,0 +1,14 @@
import mongoose from 'mongoose'
const CounterOffer = new mongoose.Schema({
nostrEventId: { type: String, required: true }, // Nostr Event Id.
takerAddr: { type: String, default: null },
takerNpub: { type: String, default: null },
makerNpub: { type: String, default: null },
counterOfferAddr: { type: String, default: null },
counterOfferUtxo: { type: String, default: null },
takerOfferUtxo: { type: String, default: null },
tokenId: { type: String, default: null }
})
export default mongoose.model('counterOffer', CounterOffer)
+1 -1
View File
@@ -18,7 +18,7 @@ const Offer = new mongoose.Schema({
p2wdbHash: { type: String },
offerStatus: { type: String },
makerAddr: { type: String },
makerNpub: { type: String },
makerNpub: { type: String, default: null },
// Authentication data
signature: { type: String },
+1
View File
@@ -24,6 +24,7 @@ const Order = new mongoose.Schema({
p2wdbTxid: { type: String },
p2wdbHash: { type: String },
makerAddr: { type: String, required: true },
makerNpub: { type: String, required: true },
// Authentication data
signature: { type: String },
+28
View File
@@ -7,6 +7,8 @@ import BchNostr from 'bch-nostr'
import { RelayPool } from 'nostr'
import RetryQueue from '@chris.troutner/retry-queue'
import * as nip19 from 'nostr-tools/nip19'
import { base58_to_binary as base58Tobinary } from 'base58-js'
import { getPublicKey } from 'nostr-tools/pure'
class NostrAdapter {
constructor (localConfig = { nostrRelay: '', nostrTopic: '' }) {
@@ -44,6 +46,7 @@ class NostrAdapter {
this.npub2pubkey = this.npub2pubkey.bind(this)
this.readGlobalFeed = this.readGlobalFeed.bind(this)
this.getFollowers = this.getFollowers.bind(this)
this.privKeyToNpub = this.privKeyToNpub.bind(this)
}
// Create nostr keys.
@@ -247,6 +250,31 @@ class NostrAdapter {
throw error
}
}
// Convert a BCH private key (WIF) to a Nostr npub.
privKeyToNpub (privKey) {
try {
if (!privKey || typeof privKey !== 'string') {
throw new Error('privKey must be a string!')
}
// Extract the privaty key from the WIF, using this guide:
// https://learnmeabitcoin.com/technical/keys/private-key/wif/
const wifBuf = base58Tobinary(privKey)
const privBuf = wifBuf.slice(1, 33)
// console.log('privBuf: ', privBuf)
const nostrPubKey = getPublicKey(privBuf)
// console.log('nostrPubKey: ', nostrPubKey)
// Convert pubkey to npub
const nostrNpub = nip19.npubEncode(nostrPubKey)
// console.log('nostrNpub: ', nostrNpub)
return nostrNpub
} catch (error) {
console.log(`Error in nostr.js/privKeyToNpub() ${error.message} `)
throw error
}
}
}
export default NostrAdapter
@@ -35,6 +35,7 @@ class OfferRESTControllerLib {
this.takeOffer = this.takeOffer.bind(this)
this.listOffersByAddress = this.listOffersByAddress.bind(this)
this.syncOfferMutableData = this.syncOfferMutableData.bind(this)
this.listCounterOffersByAddress = this.listCounterOffersByAddress.bind(this)
this.handleError = this.handleError.bind(this)
}
@@ -408,6 +409,52 @@ class OfferRESTControllerLib {
}
}
/**
* @api {get} /offer/list/counter-offer/:addr List all counter offers being made by a given address
* @apiPermission public
* @apiName listCounterOffersByAddress
* @apiGroup REST Offer
*
* @apiExample Example usage:
* curl -H "Content-Type: application/json" -X GET localhost:5000/offer/list/counter-offer/bitcoincash:qq54a3xyyptty63ztlcavzzh64gy4d247qs4ueaupe
*
*
* @apiSuccess {String} offers.nostrEventId Nostr event id
* @apiSuccess {String} offers.takerNpub Nostr Npub.
* @apiSuccess {String} offers.takerAddr BCH Address.
* @apiSuccess {String} offers.counterOfferAddr BCH Address
* @apiSuccess {String} offers.counterOfferUtxo Utxo txid.
*
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "counterOffers": [{
* "_id": "56bd1da600a526986cf65c80",
* "nostrEventId": "1234567890",
* "takerAddr": "bitcoincash:qq54a3xyyptty63ztlcavzzh64gy4d247qs4ueaupe",
* "takerNpub": "npub1nhc47z2tf42a4ps7plzcyax2j76gdausve763tqw3xuw7jjd7ceqppquly",
* "counterOfferAddr": "bitcoincash:qzltx40ldxr53edchprppj5lpg4q7vl20usx25ga44",
* "counterOfferUtxo": "71dab5b81cf06f3495aeebcc70fb351109e5e88bc85da67d0d144c0e5ca0bd6a",
* }]
* }
*
* @apiUse TokenError
*/
async listCounterOffersByAddress (ctx) {
try {
const addr = ctx.params.addr
const counterOffers = await this.useCases.offer.listCounterOffersByAddress(addr)
ctx.body = { counterOffers }
} catch (err) {
console.log('Error in listCounterOffersByAddress REST API handler: ', err)
this.handleError(ctx, err)
}
}
// DRY error handler
handleError (ctx, err) {
console.log('err', err.message)
+1
View File
@@ -60,6 +60,7 @@ class OfferRouter {
this.router.get('/list/nft/:page', this.offerRESTController.listNftOffers)
this.router.get('/list/fungible/:page', this.offerRESTController.listFungibleOffers)
this.router.get('/list/addr/:addr', this.offerRESTController.listOffersByAddress)
this.router.get('/list/counter-offer/:addr', this.offerRESTController.listCounterOffersByAddress)
// Attach the Controller routes to the Koa app.
app.use(this.router.routes())
+21 -1
View File
@@ -28,6 +28,7 @@ class TimerControllers {
this.backupUsageInterval = 60000 * 10 // 10 minutes
this.newSmAccountsInterval = 60000 * 60 // 60 minutes
this.updateSmAccountsInterval = 60000 * 10 // 10 minutes
this.removeOlderDeletedChatsAndPostsInterval = 60000 * 60 * 1 // 1 hour
// Encapsulate dependencies
this.config = config
@@ -42,7 +43,7 @@ class TimerControllers {
this.backupUsage = this.backupUsage.bind(this)
this.newSmAccounts = this.newSmAccounts.bind(this)
this.updateSmAccounts = this.updateSmAccounts.bind(this)
this.removeOlderDeletedChatsAndPosts = this.removeOlderDeletedChatsAndPosts.bind(this)
// State
this.gcOrdersInt = null
this.gcOffersInt = null
@@ -50,6 +51,7 @@ class TimerControllers {
this.loadOffersInt = null
this.newSmAccountsInt = null
this.updateSmAccountsInt = null
this.removeOlderDeletedChatsAndPostsInt = null
}
// Start all the time-based controllers.
@@ -62,6 +64,7 @@ class TimerControllers {
this.backupUsageHandle = setInterval(this.backupUsage, this.backupUsageInterval)
this.newSmAccountsInt = setInterval(this.newSmAccounts, this.newSmAccountsInterval)
this.updateSmAccountsInt = setInterval(this.updateSmAccounts, this.updateSmAccountsInterval)
this.removeOlderDeletedChatsAndPostsInt = setInterval(this.removeOlderDeletedChatsAndPosts, this.removeOlderDeletedChatsAndPostsInterval)
return true
}
@@ -74,6 +77,7 @@ class TimerControllers {
clearInterval(this.backupUsageHandle)
clearInterval(this.newSmAccountsInt)
clearInterval(this.updateSmAccountsInt)
clearInterval(this.removeOlderDeletedChatsAndPostsInt)
}
// Garbage Collect the Orders.
@@ -194,6 +198,22 @@ class TimerControllers {
return false
}
}
// Remove older deleted chats and posts.
async removeOlderDeletedChatsAndPosts () {
try {
// console.log('removeOlderDeletedChatsAndPosts() Timer Controller executing at ', new Date().toLocaleString())
clearInterval(this.removeOlderDeletedChatsAndPostsInt)
await this.useCases.nostr.removeOlderDeletedChats()
await this.useCases.nostr.removeOlderDeletedPosts()
this.removeOlderDeletedChatsAndPostsInt = setInterval(this.removeOlderDeletedChatsAndPosts, this.removeOlderDeletedChatsAndPostsInterval)
return true
} catch (err) {
console.error('Error in time-controller.js/removeOlderDeletedChatsAndPosts(): ', err)
this.removeOlderDeletedChatsAndPostsInt = setInterval(this.removeOlderDeletedChatsAndPosts, this.removeOlderDeletedChatsAndPostsInterval)
return false
}
}
}
export default TimerControllers
+68
View File
@@ -0,0 +1,68 @@
/*
Counter Offer Entity
*/
class CounterOfferEntity {
validate (offerData = {}) {
console.log('counter offer data input validation ', offerData)
// Throw an error if input object does not have a data property
if (!offerData.data) {
throw new Error(
'Input to counterOffer.validate() must be an object with a data property.'
)
}
const {
nostrEventId,
takerAddr,
takerNpub,
makerNpub,
counterOfferAddr,
counterOfferUtxo,
takerOfferUtxo,
tokenId
} = offerData.data
// Input Validation
if (!nostrEventId || typeof nostrEventId !== 'string') {
throw new Error("Property 'nostrEventId' must be a string.")
}
// Next validations are optional, to allow old counter offers without the data.
if (takerAddr && typeof takerAddr !== 'string') {
throw new Error("Property 'takerAddr' must be a string.")
}
if (takerNpub && typeof takerNpub !== 'string') {
throw new Error("Property 'takerNpub' must be a string.")
}
if (counterOfferAddr && typeof counterOfferAddr !== 'string') {
throw new Error("Property 'counterOfferAddr' must be a string.")
}
if (counterOfferUtxo && typeof counterOfferUtxo !== 'string') {
throw new Error("Property 'counterOfferUtxo' must be a string.")
}
if (takerOfferUtxo && typeof takerOfferUtxo !== 'string') {
throw new Error("Property 'takerOfferUtxo' must be a string.")
}
if (tokenId && typeof tokenId !== 'string') {
throw new Error("Property 'tokenId' must be a string.")
}
if (makerNpub && typeof makerNpub !== 'string') {
throw new Error("Property 'makerNpub' must be a string.")
}
const validatedCounterOfferData = {
nostrEventId,
takerAddr,
takerNpub,
counterOfferAddr,
counterOfferUtxo,
takerOfferUtxo,
tokenId,
makerNpub
}
return validatedCounterOfferData
}
}
export default CounterOfferEntity
+7 -1
View File
@@ -31,6 +31,7 @@ class OfferEntity {
utxoVout,
offerStatus,
makerAddr,
makerNpub,
ticker,
tokenType,
nostrEventId,
@@ -89,6 +90,10 @@ class OfferEntity {
if (!operatorPercentage || typeof operatorPercentage !== 'number') {
throw new Error("Property 'operatorPercentage' must be a number.")
}
// Validate npub type if it exist
if (makerNpub && typeof makerNpub !== 'string') {
throw new Error("Property 'makerNpub' must be a string.")
}
// Convert the timestamp to a number.
let timestamp = new Date(offerData.timestamp)
@@ -113,7 +118,8 @@ class OfferEntity {
makerAddr,
ticker,
tokenType,
nostrEventId
nostrEventId,
makerNpub
}
// console.log('offer entity validatedOfferData: ', validatedOfferData)
+38
View File
@@ -25,6 +25,8 @@ class NostrUseCases {
this.getDeletedChats = this.getDeletedChats.bind(this)
this.createDeletedPost = this.createDeletedPost.bind(this)
this.getDeletedPosts = this.getDeletedPosts.bind(this)
this.removeOlderDeletedChats = this.removeOlderDeletedChats.bind(this)
this.removeOlderDeletedPosts = this.removeOlderDeletedPosts.bind(this)
}
// Create a new deleted chat model and add it to the Mongo database.
@@ -87,6 +89,42 @@ class NostrUseCases {
throw err
}
}
// Remove deleted chats that are older than 3 months.
async removeOlderDeletedChats () {
try {
const deletedChats = await this.DeletedChatModel.find({})
const threeMonthsAgo = new Date()
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3)
for (let i = 0; i < deletedChats.length; i++) {
const deletedChat = deletedChats[i]
if (deletedChat.createdAt.getTime() < threeMonthsAgo.getTime()) {
await deletedChat.remove()
}
}
} catch (err) {
wlogger.error('Error in lib/users.js/removeOlderDeletedChats()')
throw err
}
}
// Remove deleted posts that are older than 3 months.
async removeOlderDeletedPosts () {
try {
const deletedPosts = await this.DeletedPostModel.find({})
const threeMonthsAgo = new Date()
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3)
for (let i = 0; i < deletedPosts.length; i++) {
const deletedPost = deletedPosts[i]
if (deletedPost.createdAt.getTime() < threeMonthsAgo.getTime()) {
await deletedPost.remove()
}
}
} catch (err) {
wlogger.error('Error in lib/users.js/removeOlderDeletedPosts()')
throw err
}
}
}
export default NostrUseCases
+31
View File
@@ -19,6 +19,7 @@ import RetryQueue from '@chris.troutner/retry-queue'
// Local libraries
import OfferEntity from '../../entities/offer.js'
import CounterOfferEntity from '../../entities/counterOffer.js'
import config from '../../../config/index.js'
const DEFAULT_ENTRIES_PER_PAGE = 20
@@ -45,7 +46,9 @@ class OfferUseCases {
this.config = config
this.axios = axios
this.offerEntity = new OfferEntity()
this.counterOfferEntity = new CounterOfferEntity()
this.OfferModel = this.adapters.localdb.Offer
this.CounterOfferModel = this.adapters.localdb.CounterOffer
this.retryQueue = new RetryQueue({ retryPeriod: 1000, attempts: 3 })
// Bind 'this' object to functions
@@ -66,6 +69,7 @@ class OfferUseCases {
this.loadOffers = this.loadOffers.bind(this)
this.listOffersByAddress = this.listOffersByAddress.bind(this)
this.syncOfferMutableData = this.syncOfferMutableData.bind(this)
this.listCounterOffersByAddress = this.listCounterOffersByAddress.bind(this)
// State
this.seenOffers = []
@@ -595,10 +599,23 @@ class OfferUseCases {
// and broadcasts the transaction to accept the Counter Offer.
async acceptCounterOffer (offerData) {
try {
console.log('offerData', offerData)
// console.log(`acceptCounterOffer() offerData: ${JSON.stringify(offerData, null, 2)}`)
// Quickly skip over offers that have already been processed.
const eventId = offerData.data.nostrEventId
// Create counter offer entity for nostr event id if it not exist
const existingCounterOffer = await this.CounterOfferModel.findOne(({ nostrEventId: eventId }))
if (!existingCounterOffer) {
// Add taker offer utxo to counter offer data.
offerData.data.takerOfferUtxo = offerData.data.utxoTxid
const counterOEntity = this.counterOfferEntity.validate(offerData)
// Create new counter offfer model and save it.
const counterOffer = new this.CounterOfferModel(counterOEntity)
await counterOffer.save()
}
if (this.seenOffers.includes(eventId)) {
// console.log(`Offer with event ID ${eventId} already processed. Skipping.`)
return false
@@ -1020,6 +1037,20 @@ class OfferUseCases {
throw err
}
}
async listCounterOffersByAddress (takerAddr) {
try {
if (!takerAddr || typeof takerAddr !== 'string') {
throw new Error('takerAddr must be a string')
}
const counterOffers = await this.CounterOfferModel.find({ takerAddr })
return counterOffers
} catch (err) {
console.error('Error in listCounterOffersByAddress(): ', err)
throw err
}
}
}
export default OfferUseCases
+3
View File
@@ -116,6 +116,9 @@ class OrderLib {
orderEntity.operatorAddress = this.config.operatorAddress
orderEntity.operatorPercentage = this.config.operatorPercentage
// Convert the Seller's BCH private key to a Nostr npub. This is used to identify the seller in Nostr.
orderEntity.makerNpub = this.adapters.nostr.privKeyToNpub(userWallet.walletInfo.privateKey)
// Post the new Order information to Nostr under the topic set in the
// config file.
const postObj = {
+29
View File
@@ -224,4 +224,33 @@ describe('#nostr.js', () => {
assert.isArray(result)
})
})
describe('#privKeyToNpub', () => {
it('should handle error if providedprivKey is not a string', async () => {
try {
uut.privKeyToNpub()
assert.fail('Unexpected code path')
} catch (err) {
// console.log('err: ', err)
assert.include(err.message, 'privKey must be a string!')
}
})
it('should return npub if privKey is valid', async () => {
const result = uut.privKeyToNpub('L2kh34VinQNRq1ad8nnXnGoFrb9pT7j8GJXiT6Scsg18KMxsUVDr')
// console.log('result: ', result)
assert.isString(result)
assert.include(result, 'npub')
})
it('should handle unexpected error', async () => {
try {
uut.privKeyToNpub('invalid format')
assert.fail('Unexpected code path')
} catch (err) {
// console.log('err: ', err)
assert.include(err.message, 'Invalid base58 character')
}
})
})
})
@@ -52,6 +52,7 @@ describe('#OrderPagination', () => {
nostrEventId: 'nostrEventId',
dataType: 'dataType',
makerAddr: 'makerAddr',
makerNpub: 'makerNpub',
rateInBaseUnit: 'rateInBaseUnit',
minUnitsToExchange: 'minUnitsToExchange',
ticker: 'ticker',
@@ -251,6 +251,28 @@ describe('#Offer-REST-Router', () => {
})
})
describe('#listCounterOffersByAddress', () => {
it('should list counter offers by address', async () => {
ctx.params = { addr: 'testAddress' }
sandbox.stub(uut.useCases.offer, 'listCounterOffersByAddress').resolves([])
await uut.listCounterOffersByAddress(ctx)
assert.isArray(ctx.body.counterOffers)
})
it('should catch and throw an error', async () => {
try {
ctx.params = { addr: 'testAddress' }
sandbox
.stub(uut.useCases.offer, 'listCounterOffersByAddress')
.throws(new Error('test error'))
await uut.listCounterOffersByAddress(ctx)
assert.fail('Unexpected code path')
} catch (err) {
assert.include(err.message, 'test error')
}
})
})
describe('#handleError', () => {
it('should still throw error if there is no message', () => {
try {
@@ -187,4 +187,20 @@ describe('#Timer-Controllers', () => {
assert.equal(result, false)
})
})
describe('#removeOlderDeletedChatsAndPosts', () => {
it('should kick off the Use Cases and return true', async () => {
sandbox.stub(uut.useCases.nostr, 'removeOlderDeletedChats').resolves()
sandbox.stub(uut.useCases.nostr, 'removeOlderDeletedPosts').resolves()
const result = await uut.removeOlderDeletedChatsAndPosts()
assert.equal(result, true)
})
})
it('should kick off the Use Cases and return false on error', async () => {
sandbox.stub(uut.useCases.nostr, 'removeOlderDeletedChats').throws(new Error('test error'))
sandbox.stub(uut.useCases.nostr, 'removeOlderDeletedPosts').throws(new Error('test error'))
const result = await uut.removeOlderDeletedChatsAndPosts()
assert.equal(result, false)
})
})
@@ -0,0 +1,177 @@
/*
Unit tests for the CounterOffer entity library.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import CounterOfferEntity from '../../../src/entities/counterOffer.js'
let sandbox
let uut
describe('#CounterOffer-Entity', () => {
before(async () => { })
beforeEach(() => {
uut = new CounterOfferEntity()
sandbox = sinon.createSandbox()
})
afterEach(() => sandbox.restore())
describe('#validate', () => {
it('should throw an error if data is not provided', () => {
try {
uut.validate({})
} catch (err) {
assert.include(err.message, 'Input to counterOffer.validate() must be an object with a data property.')
}
})
it('should throw an error if nostrEventId is not provided', () => {
try {
uut.validate({ data: {} })
} catch (err) {
assert.include(err.message, "Property 'nostrEventId' must be a string")
}
})
it('should throw an error if provided takerAddr is not string', () => {
try {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 1234
}
uut.validate({ data: inObj })
} catch (err) {
assert.include(err.message, "Property 'takerAddr' must be a string")
}
})
it('should throw an error if provided takerNpub is not string', () => {
try {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 'taker address',
takerNpub: 1234
}
uut.validate({ data: inObj })
} catch (err) {
assert.include(err.message, "Property 'takerNpub' must be a string")
}
})
it('should throw an error if provided makerNpub is not string', () => {
try {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 'taker address',
takerNpub: 'npub',
makerNpub: 1234
}
uut.validate({ data: inObj })
} catch (err) {
assert.include(err.message, "Property 'makerNpub' must be a string")
}
})
it('should throw an error if provided counterOfferAddr is not string', () => {
try {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 'taker address',
takerNpub: 'npub',
makerNpub: 'npub',
counterOfferAddr: 1234
}
uut.validate({ data: inObj })
} catch (err) {
assert.include(err.message, "Property 'counterOfferAddr' must be a string")
}
})
it('should throw an error if provided counterOfferUtxo is not string', () => {
try {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 'taker address',
takerNpub: 'npub',
makerNpub: 'npub',
counterOfferAddr: 'counter offer address',
counterOfferUtxo: 1234
}
uut.validate({ data: inObj })
} catch (err) {
assert.include(err.message, "Property 'counterOfferUtxo' must be a string")
}
})
it('should throw an error if provided takerOfferUtxo is not string', () => {
try {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 'taker address',
takerNpub: 'npub',
makerNpub: 'npub',
counterOfferAddr: 'counter offer address',
counterOfferUtxo: 'utxo txid',
takerOfferUtxo: 1234
}
uut.validate({ data: inObj })
} catch (err) {
assert.include(err.message, "Property 'takerOfferUtxo' must be a string")
}
})
it('should throw an error if provided tokenId is not string', () => {
try {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 'taker address',
takerNpub: 'npub',
makerNpub: 'npub',
counterOfferAddr: 'counter offer address',
counterOfferUtxo: 'utxo txid',
takerOfferUtxo: 'utxo txid',
tokenId: 1234
}
uut.validate({ data: inObj })
} catch (err) {
assert.include(err.message, "Property 'tokenId' must be a string")
}
})
it('should return a counter offer object', () => {
const inObj = {
nostrEventId: 'nostr event id',
takerAddr: 'taker address',
takerNpub: 'npub',
makerNpub: 'npub',
counterOfferAddr: 'counter offer address',
counterOfferUtxo: 'utxo txid',
takerOfferUtxo: 'utxo txid',
tokenId: 'token id'
}
const counterOfferEntity = uut.validate({ data: inObj })
assert.property(counterOfferEntity, 'nostrEventId')
assert.equal(counterOfferEntity.nostrEventId, inObj.nostrEventId)
assert.property(counterOfferEntity, 'takerAddr')
assert.equal(counterOfferEntity.takerAddr, inObj.takerAddr)
assert.property(counterOfferEntity, 'takerNpub')
assert.equal(counterOfferEntity.takerNpub, inObj.takerNpub)
assert.property(counterOfferEntity, 'makerNpub')
assert.equal(counterOfferEntity.makerNpub, inObj.makerNpub)
assert.property(counterOfferEntity, 'counterOfferAddr')
assert.equal(counterOfferEntity.counterOfferAddr, inObj.counterOfferAddr)
assert.property(counterOfferEntity, 'counterOfferUtxo')
assert.equal(counterOfferEntity.counterOfferUtxo, inObj.counterOfferUtxo)
assert.property(counterOfferEntity, 'takerOfferUtxo')
assert.equal(counterOfferEntity.takerOfferUtxo, inObj.takerOfferUtxo)
assert.property(counterOfferEntity, 'tokenId')
assert.equal(counterOfferEntity.tokenId, inObj.tokenId)
})
})
})
+34 -1
View File
@@ -491,6 +491,36 @@ describe('#Offer-Entity', () => {
assert.include(err.message, "Property 'operatorPercentage' must be a number.")
}
})
it('should throw an error if makerNpub is not a string', () => {
try {
const offerData = {
data: {
messageType: 1,
messageClass: 1,
tokenId: 'fakeId',
buyOrSell: 'buy',
rateInBaseUnit: 1000,
minUnitsToExchange: 350,
numTokens: 1,
utxoTxid: 'fakeTxid',
utxoVout: 0,
offerStatus: 'posted',
makerAddr: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00',
tokenType: 1,
nostrEventId: 'test',
operatorAddress: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00',
operatorPercentage: 10,
makerNpub: 1234
}
}
uut.validate(offerData)
assert.fail('Unexpected code path')
} catch (err) {
// console.log(err)
assert.include(err.message, "Property 'makerNpub' must be a string.")
}
})
it('should validate a new offer', () => {
const offerObj = {
@@ -513,7 +543,8 @@ describe('#Offer-Entity', () => {
tokenType: 1,
nostrEventId: 'test',
operatorAddress: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00',
operatorPercentage: 10
operatorPercentage: 10,
makerNpub: 'npub1dtkf954h5k2yuv04xp44g5hnmk5k0ppv8mekxafm2gc0vveaxh6s0297qg'
},
timestamp: '2021-09-20T17:54:26.395Z',
localTimeStamp: '9/20/2021, 10:54:26 AM',
@@ -539,6 +570,8 @@ describe('#Offer-Entity', () => {
assert.property(result, 'txid')
assert.property(result, 'p2wdbHash')
assert.property(result, 'tokenType')
assert.property(result, 'makerAddr')
assert.property(result, 'makerNpub')
})
})
})
+13 -1
View File
@@ -154,6 +154,17 @@ const localdb = {
return {}
}
},
CounterOffer: class CounterOffer {
constructor (obj) {}
static findById () {}
static find () {}
static findOne () {}
static countDocuments(){}
async save () {
return {}
}
},
SmAccount: class SmAccount {
constructor (obj) {}
@@ -240,7 +251,8 @@ const nostr = {
read: async () => { return true },
eventId2note: () => { return 'testNoteId' },
readGlobalFeed: async () => { return [] },
getFollowers: async () => { return [] }
getFollowers: async () => { return [] },
privKeyToNpub: async () => { return 'fakeNpub' }
}
export default { ipfs, localdb, bch, wallet, p2wdb, bchjs, nostr}
+9 -1
View File
@@ -74,6 +74,9 @@ class Offer {
async syncOfferMutableData(){
return {}
}
async listCounterOffersByAddress() {
return []
}
}
class Order {
@@ -148,7 +151,12 @@ class NostrUseCasesMock {
async getDeletedPosts() {
return []
}
async removeOlderDeletedChats() {
return true
}
async removeOlderDeletedPosts() {
return true
}
}
class UseCasesMock {
@@ -210,4 +210,78 @@ describe('#nostr-use-cases', () => {
assert.include(err.message, 'test error')
}
})
describe('#removeOlderDeletedChats', () => {
it('should remove older deleted chats from the database', async () => {
const threeMonthsAgo = new Date()
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3) // 3 months ago
threeMonthsAgo.setDate(threeMonthsAgo.getDate() - 1) // 1 day ago
const spy = sinon.spy()
const deletedChatsMock = [
// Newer deleted chat
{
eventId: 'note19e93faw4ffqepsqsrwrnstd3ee00nmzakwwuyfjm43dankgummfqms4p6q',
createdAt: new Date(),
remove: spy
},
// Older deleted chat
{
eventId: 'note19e93faw4ffqepsqsrwrnstd3ee00nmzakwwuyfjm43dankgummfqms4p6q',
createdAt: threeMonthsAgo,
remove: spy
}
]
sandbox.stub(uut.DeletedChatModel, 'find').resolves(deletedChatsMock)
await uut.removeOlderDeletedChats()
assert.equal(spy.callCount, 1, 'Expected to be called once.')
})
it('should handle error', async () => {
try {
// Force an error.
sandbox.stub(uut.DeletedChatModel, 'find').throws(new Error('test error'))
await uut.removeOlderDeletedChats()
assert.fail('Unexpected code path')
} catch (err) {
assert.include(err.message, 'test error')
}
})
})
describe('#removeOlderDeletedPosts', () => {
it('should remove older deleted posts from the database', async () => {
const threeMonthsAgo = new Date()
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3) // 3 months ago
threeMonthsAgo.setDate(threeMonthsAgo.getDate() - 1) // 1 day ago
const spy = sinon.spy()
const deletedPostsMock = [
// Newer deleted post
{
eventId: 'note19e93faw4ffqepsqsrwrnstd3ee00nmzakwwuyfjm43dankgummfqms4p6q',
createdAt: new Date(),
remove: spy
},
// Older deleted post
{
eventId: 'note19e93faw4ffqepsqsrwrnstd3ee00nmzakwwuyfjm43dankgummfqms4p6q',
createdAt: threeMonthsAgo,
remove: spy
}
]
sandbox.stub(uut.DeletedPostModel, 'find').resolves(deletedPostsMock)
await uut.removeOlderDeletedPosts()
assert.equal(spy.callCount, 1, 'Expected to be called once.')
})
it('should handle error', async () => {
try {
// Force an error.
sandbox.stub(uut.DeletedPostModel, 'find').throws(new Error('test error'))
await uut.removeOlderDeletedPosts()
assert.fail('Unexpected code path')
} catch (err) {
assert.include(err.message, 'test error')
}
})
})
})
+60 -11
View File
@@ -835,6 +835,25 @@ describe('#offer-use-case', () => {
})
describe('#acceptCounterOffer', () => {
it('should capture counter offer if does not exist', async () => {
const offerObj = mockData.offerMockData
sandbox.stub(uut.CounterOfferModel, 'findOne').resolves(null)
const spy = sandbox.stub(uut.CounterOfferModel.prototype, 'save')
// Mock dependencies
await uut.acceptCounterOffer(offerObj)
assert.isTrue(spy.calledOnce)
})
it('should not save counter offer if already exist', async () => {
const offerObj = mockData.offerMockData
sandbox.stub(uut.CounterOfferModel, 'findOne').resolves(offerObj.data)
const spy = sandbox.stub(uut.CounterOfferModel.prototype, 'save')
// Mock dependencies
await uut.acceptCounterOffer(offerObj)
assert.isFalse(spy.calledOnce)
})
it('should return false if order already processed', async () => {
const offerObj = mockData.offerMockData
uut.seenOffers.push(offerObj.data.nostrEventId)
@@ -846,14 +865,18 @@ describe('#offer-use-case', () => {
it('should return if order is not found!', async () => {
// Mock dependencies
const offerObj = mockData.offerMockData
sandbox.stub(uut.orderUseCase, 'findOrderByUtxo').throws(new Error('test error'))
const result = await uut.acceptCounterOffer({ data: { /** .... */ } })
const result = await uut.acceptCounterOffer(offerObj)
assert.equal(result, 'N/A')
})
it('should return N/A on axios error', async () => {
// Mock dependencies
const offerObj = mockData.offerMockData
const mock = Object.assign({}, mockData.offerMockData.data)
sandbox.stub(uut.orderUseCase, 'findOrderByUtxo').resolves(mock)
// sandbox.stub(uut.adapters.wallet.bchWallet, 'utxoIsValid').throws(new Error('test error'))
@@ -861,32 +884,38 @@ describe('#offer-use-case', () => {
axiosErr.isAxiosError = true
sandbox.stub(uut.retryQueue, 'addToQueue').throws(axiosErr)
const result = await uut.acceptCounterOffer({ data: { /** .... */ } })
const result = await uut.acceptCounterOffer(offerObj)
assert.equal(result, 'N/A')
})
it('should return if utxo can not be validated', async () => {
// Mock dependencies
const offerObj = mockData.offerMockData
const mock = Object.assign({}, mockData.offerMockData.data)
sandbox.stub(uut.orderUseCase, 'findOrderByUtxo').resolves(mock)
// sandbox.stub(uut.adapters.wallet.bchWallet, 'utxoIsValid').throws(new Error('test error'))
sandbox.stub(uut.retryQueue, 'addToQueue').throws(new Error('test error'))
const result = await uut.acceptCounterOffer({ data: { /** .... */ } })
const result = await uut.acceptCounterOffer(offerObj)
assert.equal(result, 'N/A')
})
it('should return if utxo is invalid', async () => {
// Mock dependencies
const offerObj = mockData.offerMockData
const mock = Object.assign({}, mockData.offerMockData.data)
sandbox.stub(uut.orderUseCase, 'findOrderByUtxo').resolves(mock)
sandbox.stub(uut.adapters.wallet.bchWallet, 'utxoIsValid').resolves(false)
const result = await uut.acceptCounterOffer({ data: { /** .... */ } })
const result = await uut.acceptCounterOffer(offerObj)
assert.equal(result, 'N/A')
})
it('should handle error if counter offer cant be calculated', async () => {
try {
const offerObj = mockData.offerMockData
// Mock Data
const mock = Object.assign({}, mockData.offerMockData.data)
mock.rateInBaseUnit = null
@@ -895,8 +924,7 @@ describe('#offer-use-case', () => {
sandbox.stub(uut.orderUseCase, 'findOrderByEvent').resolves(mock)
sandbox.stub(uut.orderUseCase, 'findOrderByUtxo').resolves(mock)
const result = await uut.acceptCounterOffer({ data: {} })
console.log('result: ', result)
await uut.acceptCounterOffer(offerObj)
assert.fail('unexpected code path')
} catch (err) {
assert.include(err.message, 'Could not calculate the amount of BCH offered in the Counter Offer')
@@ -906,6 +934,7 @@ describe('#offer-use-case', () => {
it('should handle error for wrong transaction output', async () => {
try {
// Mock Data
const mock = Object.assign({}, mockData.offerMockData.data)
// Mock dependencies
@@ -923,6 +952,7 @@ describe('#offer-use-case', () => {
it('should skip transactions that do not have an output for the operator', async () => {
// Mock data
const mock = Object.assign({}, mockData.offerMockData.data)
mock.makerAddr = 'bitcoincash:qzy97glp47ut7tstm5g0tlrmkhk742795gkmyc7477' // Unknow Adress
mock.rateInBaseUnit = 0
@@ -934,7 +964,7 @@ describe('#offer-use-case', () => {
sandbox.stub(uut.adapters.wallet, 'deseralizeTx').resolves(mockData.deserealizeTxMockNoOperatorOut)
const result = await uut.acceptCounterOffer({ data: { /** .... */ } })
const result = await uut.acceptCounterOffer({ data: mock })
assert.equal(result, 'N/A')
})
it('should skip transactions if operator address does not match', async () => {
@@ -952,7 +982,7 @@ describe('#offer-use-case', () => {
sandbox.stub(uut.adapters.wallet, 'deseralizeTx').resolves(mockData.deserealizeTxMock)
await uut.acceptCounterOffer({ data: {} })
await uut.acceptCounterOffer({ data: mock })
assert.fail('unexpected code path')
} catch (error) {
assert.include(error.message, 'The Counter Offer has an output address of')
@@ -974,7 +1004,7 @@ describe('#offer-use-case', () => {
sandbox.stub(uut.adapters.wallet, 'deseralizeTx').resolves(mockData.deserealizeTxMock)
await uut.acceptCounterOffer({ data: {} })
await uut.acceptCounterOffer({ data: mock })
assert.fail('unexpected code path')
} catch (err) {
assert.include(err.message, 'The Counter Offer has an output address of')
@@ -997,7 +1027,7 @@ describe('#offer-use-case', () => {
sandbox.stub(uut.adapters.wallet, 'deseralizeTx').resolves(mockData.deserealizeTxMock)
const result = await uut.acceptCounterOffer({ data: {} })
const result = await uut.acceptCounterOffer({ data: mock })
assert.equal(result, 'N/A')
})
@@ -1017,7 +1047,7 @@ describe('#offer-use-case', () => {
sandbox.stub(uut.adapters.wallet, 'deseralizeTx').resolves(mockData.deserealizeTxMock)
//
const result = await uut.acceptCounterOffer({ data: {} })
const result = await uut.acceptCounterOffer({ data: mock })
assert.isString(result)
assert.notEqual('N/A')
})
@@ -1130,4 +1160,23 @@ describe('#offer-use-case', () => {
assert.isNumber(offer.lastUpdatedTokenData)
})
})
describe('#listCounterOffersByAddress', () => {
it('should throw an error if takerAddr is not provided!', async () => {
try {
await uut.listCounterOffersByAddress()
assert.fail('unexpected code path')
} catch (err) {
assert.include(err.message, 'takerAddr must be a string')
}
})
it('should return counter offers by address', async () => {
// Mock dependencies
sandbox.stub(uut.CounterOfferModel, 'find').resolves([])
const result = await uut.listCounterOffersByAddress('bitcoincash:qzltx40ldxr53edchprppj5lpg4q7vl20usx25ga44')
assert.isArray(result)
})
})
})