mirror of
https://github.com/Permissionless-Software-Foundation/bch-dex.git
synced 2026-09-22 01:02:00 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
649655c7bb | ||
|
|
e7e6f31c96 | ||
|
|
f630b61343 | ||
|
|
f4a1f77077 | ||
|
|
956c67a288 | ||
|
|
827f094c94 | ||
|
|
41306cc943 | ||
|
|
b5b86aa525 | ||
|
|
075676aec1 | ||
|
|
f6646f8658 | ||
|
|
aa0a8a862c | ||
|
|
44c02beb3e | ||
|
|
10fb87d465 | ||
|
|
03942d5232 |
+1
-1
@@ -1,5 +1,5 @@
|
||||
The MIT License (MIT)
|
||||
Copyright (c) 2021 Permissionless Software Foundation
|
||||
Copyright (c) 2022 Permissionless Software Foundation
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
+2
-2
@@ -94,13 +94,13 @@ class Server {
|
||||
try {
|
||||
try {
|
||||
// Delete an old webhook if it exists.
|
||||
await webhookLib.deleteWebhook('http://localhost:5700/order')
|
||||
await webhookLib.deleteWebhook(`http://localhost:${config.port}/order`)
|
||||
} catch (err) {
|
||||
/* exit quietly */
|
||||
// console.log('err deleting webhook: ', err)
|
||||
}
|
||||
|
||||
await webhookLib.createWebhook('http://localhost:5700/order')
|
||||
await webhookLib.createWebhook(`http://localhost:${config.port}/order`)
|
||||
console.log('Webhook created')
|
||||
} catch (error) {
|
||||
console.log('Webhook cant be created')
|
||||
|
||||
Vendored
+9
-1
@@ -31,6 +31,12 @@ module.exports = {
|
||||
? process.env.EMAILPASS
|
||||
: 'emailpassword',
|
||||
|
||||
// PSF Web 3 community infrastructure
|
||||
useFullStackCash: process.env.USE_FULLSTACKCASH ? true : false,
|
||||
consumerUrl: process.env.CONSUMER_URL
|
||||
? process.env.CONSUMER_URL
|
||||
: 'https://free-bch.fullstack.cash',
|
||||
|
||||
// FullStack.cash account information, used for automatic JWT handling.
|
||||
getJwtAtStartup: process.env.GET_JWT_AT_STARTUP ? true : false,
|
||||
authServer: process.env.AUTHSERVER
|
||||
@@ -72,9 +78,11 @@ module.exports = {
|
||||
},
|
||||
|
||||
// P2WDB webhook endpoint
|
||||
p2wdbPort: process.env.P2WDB_PORT ? process.env.P2WDB_PORT : 5010,
|
||||
webhookService: process.env.WEBHOOKSERVICE
|
||||
? process.env.WEBHOOKSERVICE
|
||||
: 'http://localhost:5001/webhook', // P2WDB.
|
||||
: 'http://localhost:5010/webhook', // P2WDB.
|
||||
p2wdbAppId: process.env.APP_ID ? process.env.APP_ID : 'bch-dex-test556',
|
||||
|
||||
// IPFS Ports
|
||||
ipfsTcpPort: process.env.IPFS_TCP_PORT ? process.env.IPFS_TCP_PORT : 4001,
|
||||
|
||||
+19
-20
@@ -1,30 +1,29 @@
|
||||
# Developer Documentation
|
||||
|
||||
This is living documentation that will be updated, edited, and changed over time, using the same version control as the rest of the code. The purpose of this documentation is to capture and explain how this ipfs-swap-service interacts with the [P2WDB](https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service), to create a permissionless, censorship-resistant database for storing trading orders. A web client will be built in the future that will interact with the REST API of this app.
|
||||
This is living documentation that will be updated, edited, and changed over time, using the same version control as the rest of the code. The purpose of this documentation is to capture and explain how the `bch-dex` interacts with the [P2WDB](https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service), to create a permissionless, censorship-resistant database for storing trading orders. A web client will be built in the future that will interact with the REST API of this app.
|
||||
|
||||
- [Specification](./specification.md)
|
||||
|
||||
# Overview
|
||||
|
||||
There are three major pieces of software behind the ipfs-swap-service concept. They work together to form a censorship-resistant application for exchanging transaction data for building trades.
|
||||
There are three major pieces of software behind the bch-dex concept. They work together to form a censorship-resistant application for exchanging transaction data for building trades.
|
||||
|
||||

|
||||

|
||||
|
||||
- _Client_ could be a web browser, or a command-line client like [psf-bch-wallet](https://github.com/Permissionless-Software-Foundation/psf-bch-wallet) or [psf-avax-wallet](https://github.com/Permissionless-Software-Foundation/psf-avax-wallet).
|
||||
- [ipfs-swap-service](https://github.com/christroutner/ipfs-swap-service) is the back end REST API that maintains a local database of information that the client reads from.
|
||||
- [bch-dex](https://github.com/Permissionless-Software-Foundation/bch-dex) is the back end REST API that maintains a local database of information that the client reads from.
|
||||
- [P2WDB](https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service) is the pay-to-write global database with a REST API for interfacing with the other two pieces of software.
|
||||
|
||||
The arrows in the image represent the information flow between the three pieces of software:
|
||||
|
||||
- The _Client_ displays information about orders. It _reads_ this information from ipfs-swap-service.
|
||||
- The _Client_ is also a wallet. It can generate the needed transactions to _write_ information to the P2WDB.
|
||||
- `ipfs-swap-service` imports data from the global P2WDB database into its local database, using a [webhook](https://en.wikipedia.org/wiki/Webhook) (dashed line). It can also custody funds by creating an _Offer_ and submitting the data to the P2WDB to generate an _Order_ (solid line).
|
||||
- The _Client_ is essentially a 'dummy terminal' with a bidirectional interface to bch-dex. bch-dex does the heavy lifting, and the _Client_ is a 'thin' UI wrapper.
|
||||
- `bch-dex` imports data from the global P2WDB database into its local database, using a [webhook](https://en.wikipedia.org/wiki/Webhook) (dashed line). It can also custody funds, pay transaction fees, and create an _Offer_ by submitting the data to the P2WDB to generate an _Order_ (solid line).
|
||||
|
||||
This architecture keeps the global database highly censorship resistant, while allowing local installations to maintain tight control over the user experience. The goal is to have many redundant copies of `ipfs-swap-service` on the network, and to empower individual traders to run their own, private copy.
|
||||
This architecture keeps the global database highly censorship resistant, while allowing local installations to maintain tight control over the user experience. The goal is to have many redundant copies of `bch-dex` on the network, and to empower individual traders to run their own, private copy.
|
||||
|
||||
# Back End
|
||||
|
||||
This section provides additional information on `ipfs-swap-service` and P2WDB back end software.
|
||||
This section provides additional information on `bch-dex` and P2WDB back end software.
|
||||
|
||||
## P2WDB
|
||||
|
||||
@@ -32,11 +31,11 @@ The heart of the censorship resistance is the pay-to-write database ([P2WDB](htt
|
||||
|
||||
Because OrbitDB is a p2p database, no one party holds the 'official' copy of the database. Instead, like a blockchain, the database is replicated among several peers, and they coordinate updates to the database using consensus rules. Peers are free to leave or enter the network. Each peer independently verifies the database entries have sufficient proof-of-burn.
|
||||
|
||||
## `ipfs-swap-service`
|
||||
## `bch-dex`
|
||||
|
||||
The [ipfs-swap-service](https://github.com/christroutner/ipfs-swap-service) replicates a copy of the global P2WDB, but has the ability to apply localized filters to the data before passing it on to the _Client_, to be displayed.
|
||||
The `bch-dex` replicates a copy of the global P2WDB, but has the ability to apply localized filters to the data before passing it on to the _Client_, to be displayed.
|
||||
|
||||
`ipfs-swap-service` is based on this [ipfs-service-provider boilerplate](https://github.com/Permissionless-Software-Foundation/ipfs-service-provider). It's a production-ready template for a web server, providing interfaces via REST API over HTTP, as well as JSON RPC over IPFS. It includes many features for building a web app. This includes user management and authentication, REST API and JSON RPC scaffolding, API documentation, Docker container generation, and extensive test coverage. It's intended to be customized for the needs of the website administrator.
|
||||
`bch-dex` is based on this [ipfs-service-provider boilerplate](https://github.com/Permissionless-Software-Foundation/ipfs-service-provider). It's a production-ready template for a web server, providing interfaces via REST API over HTTP, as well as JSON RPC over IPFS. It includes many features for building a web app. This includes user management and authentication, REST API and JSON RPC scaffolding, API documentation, Docker container generation, and extensive test coverage. It's intended to be customized for the needs of the website administrator.
|
||||
|
||||
- [Specification](./specification.md)
|
||||
|
||||
@@ -48,17 +47,17 @@ These are just a brief, high-level overview. Review the [Specifications](./speci
|
||||
|
||||
## Writing to the Global Database
|
||||
|
||||
Adding data to the global P2WDB is a result of the interaction between the _Client_ and the P2WDB. Ideally, `ipfs-swap-service` is not involved. The [p2wdb npm library](https://www.npmjs.com/package/p2wdb) can be leveraged for easy reading and writing to the P2WDB.
|
||||
|
||||
During development, `ipfs-swap-service` is being used to submit Offers to the P2WDB and custody funds. When the project reaches maturity, these functions may be removed, and they should be handled by the Client, so that legal issues around custody of funds are not a problem.
|
||||
Adding data to the global P2WDB is triggered by the _Client_ calling a REST API endpoint on `bch-dex`. `bch-dex` [p2wdb npm library](https://www.npmjs.com/package/p2wdb) can be leveraged for easy reading and writing to the P2WDB.
|
||||
|
||||
Writing data follows these steps:
|
||||
|
||||
- A user submits data to the POST `/offer` REST API endpoint. This will move the funds a segregated UTXO and submit the data to the P2WDB to convert the Offer to an Order. Offers are tracked by the local instance of `ipfs-swap-service`, but Orders are tracked by all instances of `ipfs-swap-service`.
|
||||
- The P2WDB REST API will then evaluate the data and attempt to update the p2p database using the TXID.
|
||||
- Each peer on the network will independently validate the new database entry.
|
||||
- `ipfs-swap-service` will receive a webhook call to its POST `/order` endpoint. This event will trigger the import of the new data into the apps local Mongo database, and generate a new Order model.
|
||||
- Tokens and BCH are held by a wallet which is under the controlled of `bch-dex`.
|
||||
- The _Client_ submits data to the POST `/offer` REST API endpoint to create a new Offer.
|
||||
- `bch-dex` will move the funds into a segregated UTXO, and will use that UTXO to create an Offer. The Offer data is written to the P2WDB.
|
||||
- `bch-dex` will receive a webhook call to its POST `/order` endpoint by the P2WDB. This event will trigger the import of the new data into the apps local Mongo database, and generate a new Order model.
|
||||
- This webhook event is mirrored by every instance of `bch-dex` on the network. Each P2WDB peer on the network will independently validate the new database entry.
|
||||
|
||||
|
||||
## Reading from the Local Database
|
||||
|
||||
The Client reads data from the local database stored by `ipfs-swap-service`, and does not read the global database directly. This gives `ipfs-swap-service` the opportunity to filter and modify the data locally for a more controlled user experience.
|
||||
The *Client* reads data from the local database stored by `bch-dex`, and does not read the P2WDB global database directly. This gives `bch-dex` the opportunity to filter and modify the data locally, for a more controlled user experience.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 9.4 KiB |
@@ -1,13 +1,13 @@
|
||||
# ipfs-swap-service Specification
|
||||
# bch-dex Specification
|
||||
|
||||
This document contains a high-level, human-readable specification for the four major architectural areas of the ipfs-swap-service:
|
||||
This document contains a high-level, human-readable specification for the four major architectural areas of the bch-dex:
|
||||
|
||||
- Entities
|
||||
- Use Cases
|
||||
- Controllers (inputs)
|
||||
- Adapters (outputs)
|
||||
|
||||
This reflects the [Clean Architecture](https://troutsblog.com/blog/clean-architecture) design pattern.
|
||||
This reflects the [Clean Architecture](https://bafybeiajggd4zju7oen627bcy5l32hrxqomoqzvwqfir6phzgducozksv4.ipfs.dweb.link/blog/clean-architecture) design pattern.
|
||||
|
||||
## Entities
|
||||
|
||||
@@ -44,9 +44,9 @@ Order entities have the following properties:
|
||||
|
||||
An Offer Entity is nearly the same as an Order. But while an Order is generated
|
||||
by a webhook from P2WDB, the Offer Entity is created internally. It is used
|
||||
to track an Order generated by this application.
|
||||
to track an 'Order' generated and managed by this application.
|
||||
|
||||
The Offer tracks the [HD index address](https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch05.asciidoc#hd-wallets-bip-32bip-44) used to hold tokens or BCH for sale. This is the part of the app concerned with the custody of the funds. It creates a segregated [UTXO](https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch06.asciidoc#transaction-outputs-and-inputs) to hold the offered asset. The Offer is automatically destroyed if the UTXO is accidentally spent, which is why it needs to be segregated from other wallet UTXOs.
|
||||
The Offer tracks the [HD index address](https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch05.asciidoc#hd-wallets-bip-32bip-44) used to hold tokens or BCH for sale. This is the part of the app concerned with the custody of the funds. It creates a segregated [UTXO](https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch06.asciidoc#transaction-outputs-and-inputs) to hold the offered asset. The Offer is automatically destroyed if the UTXO is spent.
|
||||
|
||||
Offer entities have the following properties:
|
||||
|
||||
@@ -93,7 +93,7 @@ Controllers are inputs to the system. When a controller is activated, it causes
|
||||
|
||||
### Orders
|
||||
|
||||
- **POST /order** - This POST REST API endpoint will be triggered by a webhook generated by the P2WDB. This will notify the `ipfs-swap-service` that a new entry has been added to the P2WDB that matches the `appId` of `swap-<chain>`, where `<chain>` has a value of `avax`, `bch`, or `ecash`. It's a new entry that should be evaluated for inclusion in the `ipfs-swap-service` local database.
|
||||
- **POST /order** - This POST REST API endpoint will be triggered by a webhook generated from P2WDB. This will notify the `bch-dex` that a new entry has been added to the P2WDB that matches the `appId` of `swap-<chain>`, where `<chain>` has a value of `avax`, `bch`, or `ecash`. It's a new entry that should be evaluated for inclusion in the `ipfs-swap-service` local database.
|
||||
|
||||
### Offers
|
||||
|
||||
|
||||
Generated
+26262
-278
File diff suppressed because it is too large
Load Diff
+3
-1
@@ -9,6 +9,7 @@
|
||||
"test:all": "export BCH_DEX=test && nyc --reporter=text mocha --exit --timeout 15000 --recursive test/unit test/e2e/automated/",
|
||||
"test:unit": "export BCH_DEX=test && mocha --exit --timeout 15000 --recursive test/unit/",
|
||||
"test:e2e:auto": "export BCH_DEX=test && mocha --exit --timeout 15000 test/e2e/automated/",
|
||||
"test:integration": "export BCH_DEX=test && mocha --exit --timeout 30000 --recursive test/integration",
|
||||
"test:temp": "export BCH_DEX=test && mocha --exit --timeout 15000 -g '#rate-limit' test/unit/json-rpc/",
|
||||
"lint": "standard --env mocha --fix",
|
||||
"docs": "./node_modules/.bin/apidoc -i src/ -o docs",
|
||||
@@ -50,7 +51,7 @@
|
||||
"koa2-ratelimit": "0.9.1",
|
||||
"libp2p": "^0.36.2",
|
||||
"line-reader": "0.4.0",
|
||||
"minimal-slp-wallet": "4.4.1",
|
||||
"minimal-slp-wallet": "../minimal-slp-wallet",
|
||||
"mongoose": "5.13.13",
|
||||
"node-fetch": "npm:@achingbrain/node-fetch@2.6.7",
|
||||
"nodemailer": "6.4.17",
|
||||
@@ -68,6 +69,7 @@
|
||||
"eslint-config-standard": "16.0.2",
|
||||
"eslint-plugin-node": "11.1.0",
|
||||
"eslint-plugin-prettier": "3.3.1",
|
||||
"eslint-plugin-promise": "^4.3.1",
|
||||
"eslint-plugin-standard": "4.0.0",
|
||||
"husky": "4.3.8",
|
||||
"mocha": "8.4.0",
|
||||
|
||||
@@ -72,7 +72,7 @@ class Adapters {
|
||||
}
|
||||
|
||||
// Start the IPFS node.
|
||||
await this.ipfs.start()
|
||||
// await this.ipfs.start()
|
||||
|
||||
// Open the wallet file
|
||||
const walletData = await this.wallet.openWallet()
|
||||
|
||||
@@ -5,14 +5,20 @@
|
||||
// Public npm libraries.
|
||||
const axios = require('axios')
|
||||
|
||||
// Local libraries
|
||||
const config = require('../../config')
|
||||
|
||||
// Global constants
|
||||
const P2WDB_SERVER = 'http://localhost:5001/entry/write'
|
||||
let P2WDB_SERVER = 'http://localhost:5001/entry/write'
|
||||
// const P2WDB_SERVER = 'https://p2wdb.fullstack.cash/entry/write'
|
||||
|
||||
class P2wdbAdapter {
|
||||
constructor (localConfig = {}) {
|
||||
// Encapsulate dependencies
|
||||
this.axios = axios
|
||||
this.config = config
|
||||
|
||||
P2WDB_SERVER = `http://localhost:${config.p2wdbPort}/entry/write`
|
||||
}
|
||||
|
||||
async write (inputObj) {
|
||||
|
||||
+37
-28
@@ -7,6 +7,7 @@ const BchWallet = require('minimal-slp-wallet/index')
|
||||
|
||||
// Local libraries
|
||||
const JsonFiles = require('./json-files')
|
||||
const config = require('../../config')
|
||||
|
||||
const WALLET_FILE = `${__dirname.toString()}/../../wallet.json`
|
||||
const PROOF_OF_BURN_QTY = 0.01
|
||||
@@ -19,9 +20,12 @@ class WalletAdapter {
|
||||
this.jsonFiles = new JsonFiles()
|
||||
this.WALLET_FILE = WALLET_FILE
|
||||
this.BchWallet = BchWallet
|
||||
this.config = config
|
||||
}
|
||||
|
||||
// Open the wallet file, or create one if the file doesn't exist.
|
||||
// Does not instance the wallet. The output of this function is expected to
|
||||
// be passed to instanceWallet().
|
||||
async openWallet () {
|
||||
try {
|
||||
let walletData
|
||||
@@ -32,7 +36,6 @@ class WalletAdapter {
|
||||
walletData = await this.jsonFiles.readJSON(this.WALLET_FILE)
|
||||
} catch (err) {
|
||||
// Create a new wallet file if one does not already exist.
|
||||
// console.log('caught: ', err)
|
||||
console.warn('Wallet file not found. Creating new wallet.json file.')
|
||||
|
||||
// Create a new wallet.
|
||||
@@ -60,6 +63,35 @@ class WalletAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
// Create an instance of minimal-slp-wallet. Use data in the wallet.json file,
|
||||
// and pass the bch-js information to the minimal-slp-wallet library.
|
||||
async instanceWallet (walletData) {
|
||||
try {
|
||||
// TODO: throw error if wallet data is not passed in.
|
||||
|
||||
const advancedConfig = {}
|
||||
if (this.config.useFullStackCash) {
|
||||
advancedConfig.interface = 'rest-api'
|
||||
advancedConfig.restURL = this.config.apiServer
|
||||
advancedConfig.apiToken = this.config.apiToken
|
||||
} else {
|
||||
advancedConfig.interface = 'consumer-api'
|
||||
advancedConfig.restURL = this.config.consumerUrl
|
||||
}
|
||||
|
||||
// Instantiate minimal-slp-wallet.
|
||||
this.bchWallet = new this.BchWallet(walletData.mnemonic, advancedConfig)
|
||||
|
||||
// Wait for wallet to initialize.
|
||||
await this.bchWallet.walletInfoPromise
|
||||
|
||||
return this.bchWallet
|
||||
} catch (err) {
|
||||
console.error('Error in instanceWallet()')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Increments the 'nextAddress' property in the wallet file. This property
|
||||
// indicates the HD index that should be used to generate a key pair for
|
||||
// storing funds for Offers.
|
||||
@@ -107,7 +139,7 @@ class WalletAdapter {
|
||||
const childNode = masterHDNode.derivePath(`m/44'/245'/0'/0/${hdIndex}`)
|
||||
|
||||
const cashAddress = this.bchWallet.bchjs.HDNode.toCashAddress(childNode)
|
||||
console.log('cashAddress: ', cashAddress)
|
||||
console.log('Generating a new key pair for cashAddress: ', cashAddress)
|
||||
|
||||
const wif = this.bchWallet.bchjs.HDNode.toWIF(childNode)
|
||||
|
||||
@@ -124,31 +156,6 @@ class WalletAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
// Create an instance of minimal-slp-wallet. Use data in the wallet.json file,
|
||||
// and pass the bch-js information to the minimal-slp-wallet library.
|
||||
async instanceWallet (walletData, bchjs) {
|
||||
try {
|
||||
// TODO: Throw error if bch-js is not passed in.
|
||||
// TODO: throw error if wallet data is not passed in.
|
||||
|
||||
const advancedConfig = {
|
||||
restURL: bchjs.restURL,
|
||||
apiToken: bchjs.apiToken
|
||||
}
|
||||
|
||||
// Instantiate minimal-slp-wallet.
|
||||
this.bchWallet = new this.BchWallet(walletData.mnemonic, advancedConfig)
|
||||
|
||||
// Wait for wallet to initialize.
|
||||
await this.bchWallet.walletInfoPromise
|
||||
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in instanceWallet()')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a cryptographic signature, required to write to the P2WDB.
|
||||
async generateSignature (message) {
|
||||
try {
|
||||
@@ -187,6 +194,7 @@ class WalletAdapter {
|
||||
|
||||
// Get token UTXOs held by the wallet.
|
||||
const tokenUtxos = this.bchWallet.utxos.utxoStore.slpUtxos.type1.tokens
|
||||
// console.log(`tokenUtxos: ${JSON.stringify(tokenUtxos, null, 2)}`)
|
||||
|
||||
// Find a token UTXO that contains PSF with a quantity higher than needed
|
||||
// to generate a proof-of-burn.
|
||||
@@ -196,7 +204,7 @@ class WalletAdapter {
|
||||
|
||||
// If token ID matches.
|
||||
if (thisUtxo.tokenId === P2WDB_TOKEN_ID) {
|
||||
if (parseFloat(thisUtxo.tokenQty) >= PROOF_OF_BURN_QTY) {
|
||||
if (parseFloat(thisUtxo.qtyStr) >= PROOF_OF_BURN_QTY) {
|
||||
tokenUtxo = thisUtxo
|
||||
break
|
||||
}
|
||||
@@ -208,6 +216,7 @@ class WalletAdapter {
|
||||
`Token UTXO of with ID of ${P2WDB_TOKEN_ID} and quantity greater than ${PROOF_OF_BURN_QTY} could not be found in wallet.`
|
||||
)
|
||||
}
|
||||
// console.log(`tokenUtxo: ${JSON.stringify(tokenUtxo, null, 2)}`)
|
||||
|
||||
const result = await this.bchWallet.burnTokens(
|
||||
PROOF_OF_BURN_QTY,
|
||||
|
||||
@@ -7,8 +7,6 @@ const axios = require('axios')
|
||||
|
||||
let _this
|
||||
|
||||
const APPID = 'swapTest555'
|
||||
|
||||
class WebHook {
|
||||
constructor () {
|
||||
_this = this
|
||||
@@ -26,7 +24,7 @@ class WebHook {
|
||||
const endpoint = _this.config.webhookService
|
||||
|
||||
const obj = {
|
||||
appId: APPID,
|
||||
appId: this.config.p2wdbAppId,
|
||||
url
|
||||
}
|
||||
|
||||
@@ -49,7 +47,7 @@ class WebHook {
|
||||
const endpoint = _this.config.webhookService
|
||||
|
||||
const obj = {
|
||||
appId: APPID,
|
||||
appId: this.config.p2wdbAppId,
|
||||
url
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ class Controllers {
|
||||
// Attach the REST controllers to the Koa app.
|
||||
// this.attachRESTControllers(app)
|
||||
|
||||
this.attachRPCControllers()
|
||||
// this.attachRPCControllers()
|
||||
}
|
||||
|
||||
// Top-level function for this library.
|
||||
|
||||
@@ -49,7 +49,8 @@ class OfferRESTControllerLib {
|
||||
|
||||
// DRY error handler
|
||||
handleError (ctx, err) {
|
||||
console.log('err', err.message)
|
||||
console.log('err', err)
|
||||
|
||||
// If an HTTP status is specified by the buisiness logic, use that.
|
||||
if (err.status) {
|
||||
if (err.message) {
|
||||
|
||||
+13
-6
@@ -1,6 +1,11 @@
|
||||
const { wlogger } = require('../adapters/wlogger')
|
||||
/*
|
||||
Offer use-case library.
|
||||
*/
|
||||
|
||||
// Local libraries
|
||||
const { wlogger } = require('../adapters/wlogger')
|
||||
const OfferEntity = require('../entities/offer')
|
||||
const config = require('../../config')
|
||||
|
||||
class OfferLib {
|
||||
constructor (localConfig = {}) {
|
||||
@@ -16,6 +21,7 @@ class OfferLib {
|
||||
this.offerEntity = new OfferEntity()
|
||||
this.OfferModel = this.adapters.localdb.Offer
|
||||
this.bch = this.adapters.bch
|
||||
this.config = config
|
||||
}
|
||||
|
||||
// Create a new offer model and add it to the Mongo database.
|
||||
@@ -25,7 +31,7 @@ class OfferLib {
|
||||
|
||||
// Input Validation
|
||||
const offerEntity = this.offerEntity.validate(entryObj)
|
||||
// console.log('offerEntity: ', offerEntity)
|
||||
console.log('offerEntity: ', offerEntity)
|
||||
|
||||
// Ensure sufficient tokens exist to create the offer.
|
||||
await this.ensureFunds(offerEntity)
|
||||
@@ -57,7 +63,7 @@ class OfferLib {
|
||||
txid,
|
||||
signature,
|
||||
message,
|
||||
appId: 'swapTest555',
|
||||
appId: this.config.p2wdbAppId,
|
||||
data: offerEntity
|
||||
}
|
||||
|
||||
@@ -109,21 +115,21 @@ class OfferLib {
|
||||
|
||||
// Get UTXOs.
|
||||
const utxos = this.adapters.wallet.bchWallet.utxos.utxoStore
|
||||
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
|
||||
console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
|
||||
|
||||
if (offerEntity.buyOrSell.includes('sell')) {
|
||||
// Sell Offer
|
||||
|
||||
// Get token UTXOs that match the token in the offer.
|
||||
const tokenUtxos = utxos.slpUtxos.type1.tokens.filter(
|
||||
(x) => x.tokenId === offerEntity.tokenId
|
||||
x => x.tokenId === offerEntity.tokenId
|
||||
)
|
||||
// console.log('tokenUtxos: ', tokenUtxos)
|
||||
|
||||
// Get the total amount of tokens in the wallet that match the token
|
||||
// in the offer.
|
||||
let totalTokenBalance = 0
|
||||
tokenUtxos.map((x) => (totalTokenBalance += parseFloat(x.tokenQty)))
|
||||
tokenUtxos.map(x => (totalTokenBalance += parseFloat(x.tokenQty)))
|
||||
// console.log('totalTokenBalance: ', totalTokenBalance)
|
||||
|
||||
// If there are fewer tokens in the wallet than what's in the offer,
|
||||
@@ -135,6 +141,7 @@ class OfferLib {
|
||||
}
|
||||
} else {
|
||||
// Buy Offer
|
||||
throw new Error('Buy orders are not supported yet.')
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
const axios = require('axios')
|
||||
|
||||
const LOCALHOST = 'http://localhost:5700'
|
||||
const LOCALHOST = 'http://localhost:5002'
|
||||
|
||||
async function start () {
|
||||
try {
|
||||
@@ -15,11 +15,11 @@ async function start () {
|
||||
messageType: 1,
|
||||
messageClass: 1,
|
||||
tokenId:
|
||||
'38e97c5d7d3585a2cbf3f9580c82ca33985f9cb0845d4dcce220cb709f9538b0',
|
||||
'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
|
||||
buyOrSell: 'sell',
|
||||
rateInSats: 1000,
|
||||
minSatsToExchange: 10,
|
||||
numTokens: 0.02
|
||||
minSatsToExchange: 1000,
|
||||
numTokens: 1
|
||||
}
|
||||
|
||||
const options = {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
Integration tests for the wallet.js adapter library.
|
||||
*/
|
||||
|
||||
// Public npm libraries.
|
||||
const assert = require('chai').assert
|
||||
|
||||
// Local libraries.
|
||||
const WalletAdapter = require('../../../src/adapters/wallet')
|
||||
|
||||
describe('#wallet', () => {
|
||||
let uut
|
||||
|
||||
beforeEach(() => {
|
||||
uut = new WalletAdapter()
|
||||
})
|
||||
|
||||
describe('#instanceWallet', () => {
|
||||
it('should instance the wallet using the web 3 infra by default', async () => {
|
||||
const walletData = await uut.openWallet()
|
||||
// console.log('walletData: ', walletData)
|
||||
|
||||
const walletInstance = await uut.instanceWallet(walletData)
|
||||
// console.log('walletInstance: ', walletInstance)
|
||||
|
||||
assert.equal(walletInstance.ar.interface, 'consumer-api')
|
||||
})
|
||||
|
||||
it('should instance using web 2 FullStack.cash infra', async () => {
|
||||
const walletData = await uut.openWallet()
|
||||
|
||||
// Force usage of FullStack.cash
|
||||
uut.config.useFullStackCash = true
|
||||
|
||||
const walletInstance = await uut.instanceWallet(walletData)
|
||||
// console.log('walletInstance: ', walletInstance)
|
||||
|
||||
assert.equal(walletInstance.ar.interface, 'rest-api')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -102,19 +102,15 @@ describe('#wallet', () => {
|
||||
// Mock dependencies
|
||||
uut.BchWallet = MockBchWallet
|
||||
|
||||
const bchjs = {
|
||||
restURL: 'dummyUrl',
|
||||
apiToken: 'dummyToken'
|
||||
}
|
||||
|
||||
// Ensure we open the test file, not the production wallet file.
|
||||
uut.WALLET_FILE = testWalletFile
|
||||
|
||||
const walletData = await uut.openWallet()
|
||||
|
||||
const result = await uut.instanceWallet(walletData.mnemonic, bchjs)
|
||||
const result = await uut.instanceWallet(walletData.mnemonic)
|
||||
console.log('result: ', result)
|
||||
|
||||
assert.equal(result, true)
|
||||
assert.property(result, 'walletInfoPromise')
|
||||
})
|
||||
|
||||
it('should catch and throw an error', async () => {
|
||||
|
||||
@@ -105,7 +105,8 @@ class MockBchWallet {
|
||||
decimals: 8,
|
||||
tokenType: 1,
|
||||
isValid: true,
|
||||
tokenQty: '1'
|
||||
tokenQty: '1',
|
||||
qtyStr: '1'
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user