mirror of
https://github.com/Permissionless-Software-Foundation/bch-js.git
synced 2026-09-22 00:52:01 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e5e636831 | ||
|
|
2adc2dfebb | ||
|
|
f9bc44ccb7 | ||
|
|
298b8f56ff | ||
|
|
139da8cf7b | ||
|
|
08e03c14d8 | ||
|
|
7da010e7af | ||
|
|
7b6eebe7c7 | ||
|
|
843f5eacef | ||
|
|
416e302ca5 | ||
|
|
1c66da70b6 | ||
|
|
59e92adf0b | ||
|
|
f369411ccb | ||
|
|
0504cf7b8d | ||
|
|
88ae47cade | ||
|
|
d144b13500 | ||
|
|
30d58bc337 | ||
|
|
651ae3f6ca | ||
|
|
04cd90f0f4 | ||
|
|
552ee31b79 | ||
|
|
affa9619bb | ||
|
|
39bff131af | ||
|
|
a84fecfe41 | ||
|
|
0736c9f2a1 | ||
|
|
aa898b31e7 | ||
|
|
29c3381cc5 | ||
|
|
f7ba6bb3ae | ||
|
|
62056e1ac4 | ||
|
|
a60e2fa2da | ||
|
|
37fe679800 | ||
|
|
4250d841c5 | ||
|
|
31079afc35 | ||
|
|
62b44d5058 | ||
|
|
150295cb43 | ||
|
|
5de2f71ea5 | ||
|
|
50a1d60229 | ||
|
|
f3e25a0338 | ||
|
|
640c582724 | ||
|
|
b472fa2673 | ||
|
|
ea83335fd2 | ||
|
|
3050819784 | ||
|
|
4ca9b1c00b | ||
|
|
bbc1a45a9e | ||
|
|
469d08e2b1 | ||
|
|
dcadad189b | ||
|
|
02f81ee203 | ||
|
|
972bf604d1 | ||
|
|
82f084edec |
@@ -4,6 +4,7 @@ wallet-info.txt
|
||||
wallet.json
|
||||
integration-test-sweet.sh
|
||||
integration-test-ss.sh
|
||||
integration-test-bitfinex.sh
|
||||
|
||||
docs/
|
||||
coverage/
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
[](https://www.npmjs.com/package/@psf/bch-js)
|
||||
[](https://npmjs.org/package/@psf/bch-js)
|
||||
[](https://github.com/Permissionless-Software-Foundation/bch-js/blob/master/LICENSE.md)
|
||||
[](https://github.com/feross/standard)
|
||||
[](https://github.com/feross/standard) [](https://gitter.im/Permissionless-Software-Foundation/bch-js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
[bch-js](https://www.npmjs.com/package/@psf/bch-js) is a JavaScript npm library for creating web and mobile apps that can interact with the Bitcoin Cash (BCH) blockchains. It can be used for free, but requires an account on [FullStack.cash](https://fullstack.cash) for increased rate limits. Learn more from [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) about Full Stack Bitcoin Cash development.
|
||||
[bch-js](https://www.npmjs.com/package/@psf/bch-js) is a JavaScript npm library for creating web and mobile apps that can interact with the Bitcoin Cash (BCH) and eCash (XEC) blockchains. bch-js contains a toolbox of handy tools, and an easy API for talking with [bch-api REST API](https://github.com/Permissionless-Software-Foundation/bch-api). [FullStack.cash](https://fullstack.cash) offers paid cloud access to bch-api. You can run your own infrastructure by following documentation on [CashStack.info](https://cashstack.info).
|
||||
|
||||
### Quick Start Videos:
|
||||
|
||||
@@ -23,6 +23,7 @@ Here are two YouTube walk-through videos to help you get started:
|
||||
- [FullStack.cash](https://fullstack.cash) - cloud-based infrastructure for application developers.
|
||||
- [FullStack.cash Account](https://fullstack.cash/login) - Get your API key to unlock increased rate limits.
|
||||
- [Permissionless Software Foundation](https://psfoundation.cash) - The organization that maintains this library.
|
||||
- [CashStack.info](https://cashstack.info) - bch-js is part of the Cash Stack, a JavaScript framework for writing web 2 and web 3 business applications.
|
||||
|
||||
### Quick Notes
|
||||
|
||||
@@ -42,10 +43,10 @@ the [bch-api](https://github.com/Permissionless-Software-Foundation/bch-api) RES
|
||||
- ABC Mainnet REST API server: https://abc.fullstack.cash/v5/
|
||||
- Check server status: https://metrics.fullstack.cash
|
||||
|
||||
### API Key
|
||||
### API Key (JWT Token)
|
||||
|
||||
The [bch-api](https://github.com/Permissionless-Software-Foundation/bch-api) REST API hosted by [FullStack.cash](https://fullstack.cash) uses JWT tokens to pay for increased
|
||||
rate limits when interacting with the back end server. See [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) if you want to understand the system-as-a-whole. The JWT token can be fed to bch-js _implicitly_ or _explicitly_.
|
||||
rate limits when interacting with the back end server. See [this article](https://cashstack.info) if you want to understand the system-as-a-whole. The JWT token can be fed to bch-js _implicitly_ or _explicitly_.
|
||||
|
||||
- Implicitly: bch-js will detect your JWT token if you set the `BCHJSTOKEN` environment variable.
|
||||
- Explicitly: You can directly feed in the JWT token with the `apiToken` property when instantiating the library. Here is an example:
|
||||
@@ -58,38 +59,25 @@ let bchjs = new BCHJS({
|
||||
})
|
||||
```
|
||||
|
||||
### Gatsby
|
||||
### Gatsby & Web Apps
|
||||
|
||||
bch-js is included in this [gatsby-ipfs-template](https://github.com/Permissionless-Software-Foundation/gatsby-ipfs-template) for building uncensorable web apps that can interact with the blockchain. When building a Gatsby (or other front-end app that uses Webpack), you'll need to add these lines to your `gatsby-node.js` file, as per [this issue](https://github.com/gatsbyjs/gatsby/issues/564):
|
||||
[minimal-slp-wallet](https://www.npmjs.com/package/minimal-slp-wallet) is a minimal wallet 'engine' that incorporates bch-js. It's compiled with Browserify for front end apps.
|
||||
|
||||
```
|
||||
exports.onCreateWebpackConfig = ({ actions }) => {
|
||||
actions.setWebpackConfig({
|
||||
node: {
|
||||
fs: 'empty'
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
[gatsby-theme-bch-wallet](https://github.com/Permissionless-Software-Foundation/gatsby-theme-bch-wallet) is a Gatsby Theme and [bch-wallet-starter](https://github.com/Permissionless-Software-Foundation/bch-wallet-starter) is a Gatsby Starter for building web wallets using minimal-slp-wallet.
|
||||
|
||||
This is because the new IPFS class in bch-js uses the fs library for uploading files, which is not supported by Gatsby.
|
||||
|
||||
We also provide [minimal-slp-wallet-web](https://www.npmjs.com/package/minimal-slp-wallet-web) as a basic Bitcoin Cash wallet with SLP support, for front end projects. bch-js is encapsulated inside the instantiation of the library Class.
|
||||
[This gist](https://gist.github.com/christroutner/6cb9d1b615f3f9363af79723157bc434) shows how to include minimal-slp-wallet into a basic web page without using a framework.
|
||||
|
||||
## Features
|
||||
|
||||
- [ECMAScript 2017 standard JavaScript](https://en.wikipedia.org/wiki/ECMAScript#8th_Edition_-_ECMAScript_2017) used instead of TypeScript. Works
|
||||
natively with node.js v10 or higher.
|
||||
|
||||
- Full SLP tokens support: bch-js has full support for all SLP token functionality, including send, mint, and genesis transactions. It also fully support all aspects of [non-fugible tokans (NFTs)](https://www.youtube.com/watch?v=vvlpYUx6HRs).
|
||||
- Full SLP tokens support: bch-js has full support for all SLP token functionality, including send, mint, and genesis transactions. It also fully supports all aspects of [non-fugible tokans (NFTs)](https://www.youtube.com/watch?v=vvlpYUx6HRs).
|
||||
|
||||
- [Semantic Release](https://github.com/semantic-release/semantic-release) for
|
||||
continuous delivery using semantic versioning.
|
||||
|
||||
- [Greenkeeper](https://greenkeeper.io/) automatic dependency management for
|
||||
automatically maintaining the latest, most secure dependencies.
|
||||
|
||||
- [IPFS uploads](https://ipfs.io) of all files and dependencies, to backup
|
||||
- [IPFS](https://ipfs.io) and [Radicle](https://radicle.xyz) uploads of all files and dependencies, to backup
|
||||
dependencies in case they are ever inaccessible from GitHub or npm.
|
||||
|
||||
## Documentation:
|
||||
@@ -109,14 +97,26 @@ live in the same repository. To generate the documentation:
|
||||
Have questions? Need help? Join our community support
|
||||
[Telegram channel](https://t.me/bch_js_toolkit)
|
||||
|
||||
## IPFS Releases
|
||||
## Donate
|
||||
|
||||
This open source software is developed and maintained by the [Permissionless Software Foundation](https://psfoundation.cash). If this library provides value to you, please consider making a donation to support the PSF developers:
|
||||
|
||||
<div align="center">
|
||||
<img src="./img/donation-qr.png" />
|
||||
<p>bitcoincash:qqsrke9lh257tqen99dkyy2emh4uty0vky9y0z0lsr</p>
|
||||
</div>
|
||||
|
||||
|
||||
## IPFS & Radicle Releases
|
||||
|
||||
Copies of this repository are also published on [IPFS](https://ipfs.io).
|
||||
|
||||
- v4.5.4: QmWv3pxJy3MH8vU5nLUVyzqFxfNKXLQQEnz1rgStNuQijd
|
||||
- v6.2.10: `bafybeifsioj3ba77u2763nsyuzq53gtbdxsnqpoipvdl4immj6ytznjaoy`
|
||||
- (with dependencies, node v14.18.2 and npm v8.8.0): `bafybeihfendd4oj6uxvvecm7sluobwwhpb5wdcxhvhmx56e667nxdncd4a`
|
||||
|
||||
They are also posted to the Radicle:
|
||||
- v6.2.10: `rad:git:hnrkkroqnbfwj6uxpfjuhspoxnfm4i8e6oqwy`
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE.md)
|
||||
|
||||
test
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
Generated
+7
-6
@@ -7545,9 +7545,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
|
||||
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
|
||||
"version": "1.2.6",
|
||||
"resolved": "http://94.130.170.209:4873/minimist/-/minimist-1.2.6.tgz",
|
||||
"integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/minimist-options": {
|
||||
"version": "4.1.0",
|
||||
@@ -20342,9 +20343,9 @@
|
||||
}
|
||||
},
|
||||
"minimist": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
|
||||
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
|
||||
"version": "1.2.6",
|
||||
"resolved": "http://94.130.170.209:4873/minimist/-/minimist-1.2.6.tgz",
|
||||
"integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q=="
|
||||
},
|
||||
"minimist-options": {
|
||||
"version": "4.1.0",
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ class ElectrumX {
|
||||
* @apiDescription Return a list of uxtos for an address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* (async () => {
|
||||
* try {
|
||||
* let utxo = await bchjs.Electrumx.utxo('bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9');
|
||||
* console.log(utxo);
|
||||
|
||||
+74
-1
@@ -41,7 +41,7 @@ class PsfSlpIndexer {
|
||||
this.rawTransaction = new RawTransaction(config)
|
||||
this.slpUtils = new SlpUtils(config)
|
||||
|
||||
// _this = this
|
||||
// _this = this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -288,6 +288,8 @@ class PsfSlpIndexer {
|
||||
*/
|
||||
async tx (txid) {
|
||||
try {
|
||||
// console.log('txid: ', txid)
|
||||
|
||||
// Handle single address.
|
||||
if (typeof txid === 'string') {
|
||||
const response = await axios.post(
|
||||
@@ -295,8 +297,11 @@ class PsfSlpIndexer {
|
||||
{ txid },
|
||||
this.axiosOptions
|
||||
)
|
||||
// console.log('response: ', response)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error('Input txid must be a string.')
|
||||
} catch (error) {
|
||||
// console.log('error: ', error)
|
||||
@@ -316,6 +321,7 @@ class PsfSlpIndexer {
|
||||
|
||||
// Check if this txid belongs to a blacklisted token.
|
||||
const isInBlacklist = await this.checkBlacklist(txid)
|
||||
// console.log('isInBlacklist: ', isInBlacklist)
|
||||
|
||||
// Get the TX Details from the full node.
|
||||
const txDetails = await this.rawTransaction.getTxData(txid)
|
||||
@@ -368,6 +374,73 @@ class PsfSlpIndexer {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api PsfSlpIndexer.getTokenData() getTokenData()
|
||||
* @apiName Token Data
|
||||
* @apiGroup PSF SLP
|
||||
* @apiDescription Get mutable and immutable data if the token contains them.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let tokenData = await bchjs.PsfSlpIndexer.getTokenData('a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2')
|
||||
* console.log(tokenData)
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* {
|
||||
* genesisData: {
|
||||
* type: 1,
|
||||
* ticker: 'TROUT',
|
||||
* name: "Trout's test token",
|
||||
* tokenId: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
|
||||
* documentUri: 'troutsblog.com',
|
||||
* documentHash: '',
|
||||
* decimals: 2,
|
||||
* mintBatonIsActive: true,
|
||||
* tokensInCirculationBN: '100098953386',
|
||||
* tokensInCirculationStr: '100098953386',
|
||||
* blockCreated: 622414,
|
||||
* totalBurned: '1046614',
|
||||
* totalMinted: '100100000000'
|
||||
* ]
|
||||
* },
|
||||
* immutableData :{
|
||||
* issuer:"FullStack.cash.",
|
||||
* website:"https://fullstack.cash/",
|
||||
* dateCreated:"2022-01-11"
|
||||
* },
|
||||
* mutableData :{
|
||||
* "tokenIcon":"https://gateway.ipfs.io/ipfs/bafybeiehitanirn5gmhqjg44xrmdtomn4n5lu5yjoepsvgpswk5mggaw6i/LP_logo-1.png",
|
||||
* "about":"Mutable data managed with npm package: https://www.npmjs.com/package/slp-mutable-data"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
*/
|
||||
async getTokenData (tokenId) {
|
||||
try {
|
||||
const url = `${this.restURL}psf/slp/token/data`
|
||||
// console.log(`url: ${url}`)
|
||||
|
||||
// Handle single address.
|
||||
if (typeof tokenId === 'string') {
|
||||
const response = await axios.post(
|
||||
// 'https://bchn.fullstack.cash/v5/psf/slp/token/data/',
|
||||
url,
|
||||
{ tokenId },
|
||||
this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
}
|
||||
throw new Error('Input tokenId must be a string.')
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PsfSlpIndexer
|
||||
|
||||
+15
-6
@@ -381,6 +381,8 @@ class RawTransactions {
|
||||
// Appends the BCH address to the inputs of the transaction.
|
||||
async getTxData (txid) {
|
||||
try {
|
||||
// console.log('getTxData() txid: ', txid)
|
||||
|
||||
if (typeof txid !== 'string') {
|
||||
throw new Error(
|
||||
'Input to raw-transaction.js/getTxData() must be a string containg a TXID.'
|
||||
@@ -391,17 +393,24 @@ class RawTransactions {
|
||||
const txDetails = await this.getRawTransaction(txid, true)
|
||||
// console.log(`txDetails: ${JSON.stringify(txDetails, null, 2)}`)
|
||||
|
||||
const inAddrs = await this._getInputAddrs(txDetails)
|
||||
// console.log(`inAddrs: ${JSON.stringify(inAddrs, null, 2)}`)
|
||||
try {
|
||||
const inAddrs = await this._getInputAddrs(txDetails)
|
||||
// console.log(`inAddrs: ${JSON.stringify(inAddrs, null, 2)}`)
|
||||
|
||||
// Add the input address to the transaction data.
|
||||
for (let i = 0; i < inAddrs.length; i++) {
|
||||
txDetails.vin[i].address = inAddrs[i].address
|
||||
txDetails.vin[i].value = inAddrs[i].value
|
||||
// Add the input address to the transaction data.
|
||||
for (let i = 0; i < inAddrs.length; i++) {
|
||||
txDetails.vin[i].address = inAddrs[i].address
|
||||
txDetails.vin[i].value = inAddrs[i].value
|
||||
}
|
||||
} catch (err) {
|
||||
// Coinbase transactions will throw an error. Just ignore them and
|
||||
// pass back the raw transaction data.
|
||||
/* exit quietly */
|
||||
}
|
||||
|
||||
return txDetails
|
||||
} catch (error) {
|
||||
// console.log('error: ', error)
|
||||
if (error.error) throw new Error(error.error)
|
||||
|
||||
// This case handles rate limit errors.
|
||||
|
||||
+1
-1
@@ -147,7 +147,7 @@ class Nft1 {
|
||||
// Loop through the tokenUtxos array and find the minting baton.
|
||||
let mintBatonUtxo
|
||||
for (let i = 0; i < tokenUtxos.length; i++) {
|
||||
if (tokenUtxos[i].utxoType === 'minting-baton') {
|
||||
if (tokenUtxos[i].utxoType === 'minting-baton' || tokenUtxos[i].type === 'baton') {
|
||||
mintBatonUtxo = tokenUtxos[i]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,11 +375,14 @@ class TokenType1 {
|
||||
if (!Array.isArray(tokenUtxos)) {
|
||||
throw new Error('tokenUtxos must be an array.')
|
||||
}
|
||||
if (!mintQty) {
|
||||
throw new Error('mintQty must be a positive number.')
|
||||
}
|
||||
|
||||
// Loop through the tokenUtxos array and find the minting baton.
|
||||
let mintBatonUtxo
|
||||
for (let i = 0; i < tokenUtxos.length; i++) {
|
||||
if (tokenUtxos[i].utxoType === 'minting-baton') {
|
||||
if (tokenUtxos[i].utxoType === 'minting-baton' || tokenUtxos[i].type === 'baton') {
|
||||
mintBatonUtxo = tokenUtxos[i]
|
||||
}
|
||||
}
|
||||
@@ -395,7 +398,7 @@ class TokenType1 {
|
||||
if (!tokenId) {
|
||||
throw new Error('tokenId property not found in mint-baton UTXO.')
|
||||
}
|
||||
if (!decimals) {
|
||||
if (!decimals && decimals !== 0) {
|
||||
throw new Error('decimals property not found in mint-baton UTXO.')
|
||||
}
|
||||
|
||||
@@ -404,6 +407,8 @@ class TokenType1 {
|
||||
baseQty = Math.floor(baseQty)
|
||||
baseQty = baseQty.toString()
|
||||
|
||||
if (isNaN(baseQty)) throw new Error('baseQty is non a number!')
|
||||
|
||||
// Signal that the baton should be passed or detroyed.
|
||||
let batonVout = 2
|
||||
if (destroyBaton) batonVout = null
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// Public npm libraries
|
||||
const axios = require('axios')
|
||||
const slpParser = require('slp-parser')
|
||||
const BigNumber = require('bignumber.js')
|
||||
|
||||
// Local libraries
|
||||
const Util = require('../util')
|
||||
@@ -183,526 +182,6 @@ class Utils {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Utils.tokenUtxoDetails() tokenUtxoDetails()
|
||||
* @apiName tokenUtxoDetails
|
||||
* @apiGroup SLP Utils
|
||||
* @apiDescription Hydrate a UTXO with SLP token metadata.
|
||||
*
|
||||
* Expects an array of UTXO objects as input. Returns an array of equal size.
|
||||
* Returns UTXO data hydrated with token information.
|
||||
*
|
||||
* - If the UTXO does not belong to a SLP transaction, it will return an
|
||||
* `isValid` property set to `false`.
|
||||
*
|
||||
* - If the UTXO is part of an SLP transaction, it will return the UTXO object
|
||||
* with additional SLP information attached. An `isValid` property will be
|
||||
* included.
|
||||
* - If the `isValid` property is `true`, the UTXO is a valid SLP UTXO.
|
||||
* - If the `isValid` property is `null`, then SLPDB has not yet processed
|
||||
* that txid and validity has not been confirmed, or a 429 rate-limit error
|
||||
* was enountered during the processing of the request.
|
||||
*
|
||||
* An optional second input object, `usrObj`, allows the user to inject an
|
||||
* artifical delay while processing UTXOs. If `usrObj.utxoDelay` is set to
|
||||
* a number, the call will delay by that number of milliseconds between
|
||||
* processing UTXOs.
|
||||
*
|
||||
* This is an API-heavy call. If you get a lot of `null` values, then slow down
|
||||
* the calls by using the usrObj.utxoDelay property, or request info on fewer
|
||||
* UTXOs at a
|
||||
* time. `null` indicates that the UTXO can *not* be safely spent, because
|
||||
* a judgement as to weather it is a token UTXO has not been made. Spending it
|
||||
* could burn tokens. It's safest to ignore UTXOs with a value of `null`.
|
||||
*
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* const utxos = await bchjs.Electrumx.utxo(`bitcoincash:qpcqs0n5xap26un2828n55gan2ylj7wavvzeuwdx05`)
|
||||
*
|
||||
* // Delay 100mS between processing UTXOs, to prevent rate-limit errors.
|
||||
* const utxoInfo = await bchjs.SLP.Utils.tokenUtxoDetails(utxos, { utxoDelay: 100 })
|
||||
*
|
||||
* console.log(`utxoInfo: ${JSON.stringify(utxoInfo, null, 2)}`)
|
||||
* } catch (error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // returns
|
||||
* {
|
||||
* "txid": "fde117b1f176b231e2fa9a6cb022e0f7c31c288221df6bcb05f8b7d040ca87cb",
|
||||
* "vout": 1,
|
||||
* "amount": 0.00000546,
|
||||
* "satoshis": 546,
|
||||
* "height": 596089,
|
||||
* "confirmations": 748,
|
||||
* "utxoType": "token",
|
||||
* "tokenId": "497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7",
|
||||
* "tokenTicker": "TOK-CH",
|
||||
* "tokenName": "TokyoCash",
|
||||
* "tokenDocumentUrl": "",
|
||||
* "tokenDocumentHash": "",
|
||||
* "decimals": 8,
|
||||
* "tokenQty": 2,
|
||||
* "isValid": true,
|
||||
* "tokenType": 1
|
||||
* }
|
||||
*/
|
||||
async tokenUtxoDetails (utxos, usrObj = null) {
|
||||
try {
|
||||
// Throw error if input is not an array.
|
||||
if (!Array.isArray(utxos)) throw new Error('Input must be an array.')
|
||||
|
||||
// console.log(`tokenUtxoDetails usrObj: ${JSON.stringify(usrObj, null, 2)}`)
|
||||
|
||||
// Loop through each element in the array and validate the input before
|
||||
// further processing.
|
||||
for (let i = 0; i < utxos.length; i++) {
|
||||
const utxo = utxos[i]
|
||||
|
||||
// Ensure the UTXO has a txid or tx_hash property.
|
||||
if (!utxo.txid) {
|
||||
// If Electrumx, convert the tx_hash property to txid.
|
||||
if (utxo.tx_hash) {
|
||||
utxo.txid = utxo.tx_hash
|
||||
} else {
|
||||
// If there is neither a txid or tx_hash property, throw an error.
|
||||
throw new Error(
|
||||
`utxo ${i} does not have a txid or tx_hash property.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure the UTXO has a vout or tx_pos property.
|
||||
if (!Number.isInteger(utxo.vout)) {
|
||||
if (Number.isInteger(utxo.tx_pos)) {
|
||||
utxo.vout = utxo.tx_pos
|
||||
} else {
|
||||
throw new Error(
|
||||
`utxo ${i} does not have a vout or tx_pos property.`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hydrate each UTXO with data from SLP OP_REUTRNs.
|
||||
const outAry = await this._hydrateUtxo(utxos, usrObj)
|
||||
// console.log(`outAry: ${JSON.stringify(outAry, null, 2)}`)
|
||||
|
||||
// *After* each UTXO has been hydrated with SLP data,
|
||||
// validate the TXID with SLPDB.
|
||||
for (let i = 0; i < outAry.length; i++) {
|
||||
const utxo = outAry[i]
|
||||
|
||||
// *After* the UTXO has been hydrated with SLP data,
|
||||
// validate the TXID with SLPDB.
|
||||
if (utxo.tokenType) {
|
||||
// Only execute this code-path if the current UTXO has a 'tokenType'
|
||||
// property. i.e. it has been successfully hydrated with SLP
|
||||
// information.
|
||||
|
||||
// Validate using a 'waterfall' of validators.
|
||||
utxo.isValid = await this.waterfallValidateTxid(utxo.txid, usrObj)
|
||||
// console.log(`isValid: ${JSON.stringify(utxo.isValid, null, 2)}`)
|
||||
}
|
||||
}
|
||||
|
||||
return outAry
|
||||
} catch (error) {
|
||||
// console.log('Error in tokenUtxoDetails()')
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// This is a private function that is called by tokenUtxoDetails().
|
||||
// It loops through an array of UTXOs and tries to hydrate them with SLP
|
||||
// token information from the OP_RETURN data.
|
||||
//
|
||||
// This function makes several calls to decodeOpReturn() to retrieve SLP
|
||||
// token data. If that call throws an error due to hitting rate limits, this
|
||||
// function will not throw an error. Instead, it will mark the `isValid`
|
||||
// property as `null`
|
||||
//
|
||||
// Exception to the above: It *will* throw an error if decodeOpReturn() throws
|
||||
// an error while trying to get the Genesis transaction for a Send or Mint
|
||||
// transaction. However, that is a rare occurence since the cache of
|
||||
// decodeOpReturn() will minimize API calls for this case. This behavior
|
||||
// could be changed, but right now it's a corner case of a corner case.
|
||||
//
|
||||
// If the usrObj has a utxoDelay property, then it will delay the loop for
|
||||
// each UTXO by that many milliseconds.
|
||||
async _hydrateUtxo (utxos, usrObj = null) {
|
||||
try {
|
||||
const decodeOpReturnCache = {}
|
||||
|
||||
// console.log(`_hydrateUtxo usrObj: ${JSON.stringify(usrObj, null, 2)}`)
|
||||
|
||||
// Output Array
|
||||
const outAry = []
|
||||
|
||||
// Loop through each utxo
|
||||
for (let i = 0; i < utxos.length; i++) {
|
||||
const utxo = utxos[i]
|
||||
|
||||
// If the user passes in a delay, then wait.
|
||||
if (usrObj && usrObj.utxoDelay && !isNaN(Number(usrObj.utxoDelay))) {
|
||||
const delayMs = Number(usrObj.utxoDelay)
|
||||
await this.util.sleep(delayMs)
|
||||
}
|
||||
|
||||
// Get raw transaction data from the full node and attempt to decode
|
||||
// the OP_RETURN data.
|
||||
// If there is no OP_RETURN, mark the UTXO as false.
|
||||
let slpData = false
|
||||
try {
|
||||
slpData = await this.decodeOpReturn(
|
||||
utxo.txid,
|
||||
decodeOpReturnCache,
|
||||
usrObj // pass user data when making an internal call.
|
||||
)
|
||||
// console.log(`slpData: ${JSON.stringify(slpData, null, 2)}`)
|
||||
} catch (err) {
|
||||
// console.log(
|
||||
// `error in _hydrateUtxo() from decodeOpReturn(${utxo.txid}): `,
|
||||
// err
|
||||
// )
|
||||
|
||||
// An error will be thrown if the txid is not SLP.
|
||||
// If error is for some other reason, like a 429 error, mark utxo as 'null'
|
||||
// to display the unknown state.
|
||||
if (
|
||||
!err.message ||
|
||||
(err.message.indexOf('scriptpubkey not op_return') === -1 &&
|
||||
err.message.indexOf('lokad id') === -1 &&
|
||||
err.message.indexOf('trailing data') === -1)
|
||||
) {
|
||||
// console.log(
|
||||
// "unknown error from decodeOpReturn(). Marking as 'null'",
|
||||
// err
|
||||
// )
|
||||
|
||||
utxo.isValid = null
|
||||
outAry.push(utxo)
|
||||
|
||||
// If error is thrown because there is no OP_RETURN, then it's not
|
||||
// an SLP UTXO.
|
||||
// Mark as false and continue the loop.
|
||||
} else {
|
||||
// console.log('marking as invalid')
|
||||
utxo.isValid = false
|
||||
outAry.push(utxo)
|
||||
}
|
||||
|
||||
// Halt the execution of the loop and increase to the next index.
|
||||
continue
|
||||
}
|
||||
// console.log(`slpData: ${JSON.stringify(slpData, null, 2)}`)
|
||||
|
||||
const txType = slpData.txType.toLowerCase()
|
||||
|
||||
// console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
|
||||
|
||||
// If there is an OP_RETURN, attempt to decode it.
|
||||
// Handle Genesis SLP transactions.
|
||||
if (txType === 'genesis') {
|
||||
if (
|
||||
utxo.vout !== slpData.mintBatonVout && // UTXO is not a mint baton output.
|
||||
utxo.vout !== 1 // UTXO is not the reciever of the genesis or mint tokens.
|
||||
) {
|
||||
// Can safely be marked as false.
|
||||
utxo.isValid = false
|
||||
outAry[i] = utxo
|
||||
} else {
|
||||
// If this is a valid SLP UTXO, then return the decoded OP_RETURN data.
|
||||
// Minting Baton
|
||||
if (utxo.vout === slpData.mintBatonVout) {
|
||||
utxo.utxoType = 'minting-baton'
|
||||
} else {
|
||||
// Tokens
|
||||
|
||||
utxo.utxoType = 'token'
|
||||
utxo.tokenQty = new BigNumber(slpData.qty)
|
||||
.div(Math.pow(10, slpData.decimals))
|
||||
.toString()
|
||||
}
|
||||
|
||||
utxo.tokenId = utxo.txid
|
||||
utxo.tokenTicker = slpData.ticker
|
||||
utxo.tokenName = slpData.name
|
||||
utxo.tokenDocumentUrl = slpData.documentUri
|
||||
utxo.tokenDocumentHash = slpData.documentHash
|
||||
utxo.decimals = slpData.decimals
|
||||
utxo.tokenType = slpData.tokenType
|
||||
|
||||
// Initial value is null until UTXO can be validated and confirmed
|
||||
// to be valid (true) or not (false).
|
||||
utxo.isValid = null
|
||||
|
||||
outAry[i] = utxo
|
||||
}
|
||||
}
|
||||
|
||||
// Handle Mint SLP transactions.
|
||||
if (txType === 'mint') {
|
||||
if (
|
||||
utxo.vout !== slpData.mintBatonVout && // UTXO is not a mint baton output.
|
||||
utxo.vout !== 1 // UTXO is not the reciever of the genesis or mint tokens.
|
||||
) {
|
||||
// Can safely be marked as false.
|
||||
utxo.isValid = false
|
||||
|
||||
outAry[i] = utxo
|
||||
} else {
|
||||
// If UTXO passes validation, then return formatted token data.
|
||||
|
||||
const genesisData = await this.decodeOpReturn(
|
||||
slpData.tokenId,
|
||||
decodeOpReturnCache,
|
||||
usrObj // pass user data when making an internal call.
|
||||
)
|
||||
// console.log(`genesisData: ${JSON.stringify(genesisData, null, 2)}`)
|
||||
|
||||
// Minting Baton
|
||||
if (utxo.vout === slpData.mintBatonVout) {
|
||||
utxo.utxoType = 'minting-baton'
|
||||
} else {
|
||||
// Tokens
|
||||
|
||||
utxo.utxoType = 'token'
|
||||
utxo.tokenQty = new BigNumber(slpData.qty)
|
||||
.div(Math.pow(10, genesisData.decimals))
|
||||
.toString()
|
||||
}
|
||||
|
||||
// Hydrate the UTXO object with information about the SLP token.
|
||||
utxo.transactionType = 'mint'
|
||||
utxo.tokenId = slpData.tokenId
|
||||
utxo.tokenType = slpData.tokenType
|
||||
|
||||
utxo.tokenTicker = genesisData.ticker
|
||||
utxo.tokenName = genesisData.name
|
||||
utxo.tokenDocumentUrl = genesisData.documentUri
|
||||
utxo.tokenDocumentHash = genesisData.documentHash
|
||||
utxo.decimals = genesisData.decimals
|
||||
|
||||
utxo.mintBatonVout = slpData.mintBatonVout
|
||||
|
||||
// Initial value is null until UTXO can be validated and confirmed
|
||||
// to be valid (true) or not (false).
|
||||
utxo.isValid = null
|
||||
|
||||
outAry[i] = utxo
|
||||
}
|
||||
}
|
||||
|
||||
// Handle Send SLP transactions.
|
||||
if (txType === 'send') {
|
||||
// Filter out any vouts that match.
|
||||
// const voutMatch = slpData.spendData.filter(x => utxo.vout === x.vout)
|
||||
// console.log(`voutMatch: ${JSON.stringify(voutMatch, null, 2)}`)
|
||||
|
||||
// Figure out what token quantity is represented by this utxo.
|
||||
const tokenQty = slpData.amounts[utxo.vout - 1]
|
||||
// console.log('tokenQty: ', tokenQty)
|
||||
|
||||
if (!tokenQty) {
|
||||
utxo.isValid = false
|
||||
|
||||
outAry[i] = utxo
|
||||
} else {
|
||||
// If UTXO passes validation, then return formatted token data.
|
||||
|
||||
const genesisData = await this.decodeOpReturn(
|
||||
slpData.tokenId,
|
||||
decodeOpReturnCache,
|
||||
usrObj // pass user data when making an internal call.
|
||||
)
|
||||
// console.log(`genesisData: ${JSON.stringify(genesisData, null, 2)}`)
|
||||
|
||||
// console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
|
||||
|
||||
// Hydrate the UTXO object with information about the SLP token.
|
||||
utxo.utxoType = 'token'
|
||||
utxo.transactionType = 'send'
|
||||
utxo.tokenId = slpData.tokenId
|
||||
utxo.tokenTicker = genesisData.ticker
|
||||
utxo.tokenName = genesisData.name
|
||||
utxo.tokenDocumentUrl = genesisData.documentUri
|
||||
utxo.tokenDocumentHash = genesisData.documentHash
|
||||
utxo.decimals = genesisData.decimals
|
||||
utxo.tokenType = slpData.tokenType
|
||||
|
||||
// Initial value is null until UTXO can be validated and confirmed
|
||||
// to be valid (true) or not (false).
|
||||
utxo.isValid = null
|
||||
|
||||
// Calculate the real token quantity.
|
||||
|
||||
const tokenQtyBig = new BigNumber(tokenQty).div(
|
||||
Math.pow(10, genesisData.decimals)
|
||||
)
|
||||
// console.log(`tokenQtyBig`, tokenQtyBig.toString())
|
||||
utxo.tokenQty = tokenQtyBig.toString()
|
||||
|
||||
// console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
|
||||
|
||||
outAry[i] = utxo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return outAry
|
||||
} catch (error) {
|
||||
// console.log('_hydrateUtxo error: ', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Utils.waterfallValidateTxid() waterfallValidateTxid()
|
||||
* @apiName waterfallValidateTxid
|
||||
* @apiGroup SLP Utils
|
||||
* @apiDescription Use multiple validators to validate an SLP TXID.
|
||||
*
|
||||
* This function aggregates all the available SLP token validation sources.
|
||||
* It starts with the fastest, most-efficient source first, and continues
|
||||
* to other validation sources until the txid is validated (true or false).
|
||||
* If the txid goes through all sources and can't be validated, it will
|
||||
* return null.
|
||||
*
|
||||
* Validation sources from most efficient to least efficient:
|
||||
* - SLPDB with whitelist filter
|
||||
* - SLPDB general purpose
|
||||
* - slp-api
|
||||
*
|
||||
* Currently only supports a single txid at a time.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* // validate single SLP txid
|
||||
* (async () => {
|
||||
* try {
|
||||
* let validated = await bchjs.SLP.Utils.waterfallValidateTxid(
|
||||
* "df808a41672a0a0ae6475b44f272a107bc9961b90f29dc918d71301f24fe92fb"
|
||||
* );
|
||||
* console.log(validated);
|
||||
* } catch (error) {
|
||||
* console.error(error);
|
||||
* }
|
||||
* })();
|
||||
*
|
||||
* // returns
|
||||
* true
|
||||
*/
|
||||
async waterfallValidateTxid (txid, usrObj = null) {
|
||||
try {
|
||||
// console.log('txid: ', txid)
|
||||
|
||||
const cachedTxValidation = {}
|
||||
|
||||
// If the value has been cached, use the cached version first.
|
||||
let isValid = cachedTxValidation[txid]
|
||||
if (!isValid && isValid !== false) {
|
||||
isValid = null
|
||||
} else {
|
||||
return isValid
|
||||
}
|
||||
|
||||
// There are two possible responses from SLPDB. If SLPDB is functioning
|
||||
// correctly, then validateTxid() will return this:
|
||||
// isValid: [
|
||||
// {
|
||||
// "txid": "ff0c0354f8d3ddb34fa36f73494eb58ea24f8b8da6904aa8ed43b7a74886c583",
|
||||
// "valid": true
|
||||
// }
|
||||
// ]
|
||||
//
|
||||
// If SLPDB has fallen behind real-time processing, it will return this:
|
||||
// isValid: [
|
||||
// null
|
||||
// ]
|
||||
//
|
||||
// Note: validateTxid3() has the same output as validateTxid().
|
||||
// validateTxid2() uses slp-validate, which has a different output format.
|
||||
|
||||
// Validate against the whitelist SLPDB first.
|
||||
const whitelistResult = await this.validateTxid3(txid, usrObj)
|
||||
// console.log(
|
||||
// `whitelist-SLPDB for ${txid}: ${JSON.stringify(
|
||||
// whitelistResult,
|
||||
// null,
|
||||
// 2
|
||||
// )}`
|
||||
// )
|
||||
|
||||
// Safely retrieve the returned value.
|
||||
if (whitelistResult[0] !== null) isValid = whitelistResult[0].valid
|
||||
|
||||
// Exit if isValid is not null.
|
||||
if (isValid !== null) {
|
||||
// Save to the cache.
|
||||
cachedTxValidation[txid] = isValid
|
||||
|
||||
return isValid
|
||||
}
|
||||
|
||||
// Try the general SLPDB, if the whitelist returned null.
|
||||
const generalResult = await this.validateTxid(txid, usrObj)
|
||||
// console.log(
|
||||
// `validateTxid() isValid: ${JSON.stringify(generalResult, null, 2)}`
|
||||
// )
|
||||
|
||||
// Safely retrieve the returned value.
|
||||
if (generalResult[0] !== null) isValid = generalResult[0].valid
|
||||
|
||||
// Exit if isValid is not null.
|
||||
if (isValid !== null) {
|
||||
// Save to the cache.
|
||||
cachedTxValidation[txid] = isValid
|
||||
|
||||
return isValid
|
||||
}
|
||||
|
||||
// If still null, as a last resort, check it against slp-validate
|
||||
let slpValidateResult = null
|
||||
try {
|
||||
slpValidateResult = await this.validateTxid2(txid)
|
||||
} catch (err) {
|
||||
/* exit quietly */
|
||||
}
|
||||
// console.log(
|
||||
// `slpValidateResult: ${JSON.stringify(slpValidateResult, null, 2)}`
|
||||
// )
|
||||
|
||||
// Exit if isValid is not null.
|
||||
if (slpValidateResult !== null) {
|
||||
isValid = slpValidateResult.isValid
|
||||
|
||||
// Save to the cache.
|
||||
cachedTxValidation[txid] = isValid
|
||||
|
||||
return isValid
|
||||
}
|
||||
|
||||
// If isValid is still null, return that value, signaling that the txid
|
||||
// could not be validated.
|
||||
return isValid
|
||||
} catch (error) {
|
||||
// This case handles rate limit errors.
|
||||
if (error.response && error.response.data && error.response.data.error) {
|
||||
throw new Error(error.response.data.error)
|
||||
}
|
||||
|
||||
// console.log('Error in waterfallValidateTxid()')
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Utils
|
||||
|
||||
+10
-467
@@ -3,7 +3,7 @@
|
||||
*/
|
||||
|
||||
// Global npm libraries
|
||||
const BigNumber = require('bignumber.js')
|
||||
// const BigNumber = require('bignumber.js')
|
||||
|
||||
// Local libraries
|
||||
const RawTransaction = require('./raw-transactions')
|
||||
@@ -20,11 +20,6 @@ class Transaction {
|
||||
this.psfSlpIndexer = new PsfSlpIndexer(config)
|
||||
}
|
||||
|
||||
// Proxy the call to the psf-slp-indexer.
|
||||
async get (txid) {
|
||||
return await this.psfSlpIndexer.tx(txid)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Transaction.get() get()
|
||||
* @apiName get
|
||||
@@ -34,8 +29,6 @@ class Transaction {
|
||||
* If it is a SLP token transaction, the token information for inputs and
|
||||
* outputs will also be included.
|
||||
*
|
||||
* This is an API heavy call. This function will only work with a single txid.
|
||||
* It does not yet support an array of TXIDs.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
@@ -47,481 +40,31 @@ class Transaction {
|
||||
* }
|
||||
* })()
|
||||
*/
|
||||
|
||||
// CT 10/31/21: TODO: this function should be refactored to use get2(), but
|
||||
// add waterfall validation of the TX and its inputs.
|
||||
|
||||
async getOld (txid) {
|
||||
try {
|
||||
if (typeof txid !== 'string') {
|
||||
throw new Error(
|
||||
'Input to Transaction.get() must be a string containing a TXID.'
|
||||
)
|
||||
}
|
||||
|
||||
const txDetails = await this.rawTransaction.getTxData(txid)
|
||||
// console.log(`txDetails: ${JSON.stringify(txDetails, null, 2)}`)
|
||||
|
||||
// Setup default SLP properties.
|
||||
txDetails.isValidSLPTx = false
|
||||
|
||||
// First get the token information for the output. If that fails, then
|
||||
// this is not an SLP transaction, and this method can return false.
|
||||
let outTokenData
|
||||
try {
|
||||
outTokenData = await this.slpUtils.decodeOpReturn(txid)
|
||||
// console.log(`outTokenData: ${JSON.stringify(outTokenData, null, 2)}`)
|
||||
|
||||
// Get Genesis data for this token.
|
||||
const genesisData = await this.slpUtils.decodeOpReturn(
|
||||
outTokenData.tokenId
|
||||
// decodeOpReturnCache
|
||||
// usrObj // pass user data when making an internal call.
|
||||
)
|
||||
// console.log(`genesisData: ${JSON.stringify(genesisData, null, 2)}`)
|
||||
|
||||
// Add token information to the tx details object.
|
||||
txDetails.tokenTxType = outTokenData.txType
|
||||
txDetails.tokenId = outTokenData.tokenId
|
||||
txDetails.tokenTicker = genesisData.ticker
|
||||
txDetails.tokenName = genesisData.name
|
||||
txDetails.tokenDecimals = genesisData.decimals
|
||||
txDetails.tokenUri = genesisData.documentUri
|
||||
txDetails.tokenDocHash = genesisData.documentHash
|
||||
|
||||
// Add the token quantity to each output.
|
||||
for (let i = 0; i < outTokenData.amounts.length; i++) {
|
||||
const rawQty = outTokenData.amounts[i]
|
||||
// const realQty = Number(rawQty) / Math.pow(10, txDetails.tokenDecimals)
|
||||
|
||||
// Calculate the real quantity using a BigNumber, then convert it to a
|
||||
// floating point number.
|
||||
let realQty = new BigNumber(rawQty).dividedBy(
|
||||
10 ** parseInt(txDetails.tokenDecimals)
|
||||
)
|
||||
realQty = realQty.toString()
|
||||
// realQty = parseFloat(realQty)
|
||||
|
||||
txDetails.vout[i + 1].tokenQtyStr = realQty
|
||||
txDetails.vout[i + 1].tokenQty = parseFloat(realQty)
|
||||
}
|
||||
|
||||
// Add tokenQty = null to any outputs that don't have a value.
|
||||
for (let i = 0; i < txDetails.vout.length; i++) {
|
||||
const thisVout = txDetails.vout[i]
|
||||
|
||||
if (!thisVout.tokenQty && thisVout.tokenQty !== 0) {
|
||||
thisVout.tokenQty = null
|
||||
}
|
||||
}
|
||||
|
||||
// Loop through each input and retrieve the token data.
|
||||
for (let i = 0; i < txDetails.vin.length; i++) {
|
||||
const thisVin = txDetails.vin[i]
|
||||
// console.log(`thisVin: ${JSON.stringify(thisVin, null, 2)}`)
|
||||
|
||||
try {
|
||||
// If decodeOpReturn() throws an error, then this input is not
|
||||
// from an SLP transaction and can be ignored.
|
||||
const inTokenData = await this.slpUtils.decodeOpReturn(thisVin.txid)
|
||||
// console.log(
|
||||
// `vin[${i}] tokenData: ${JSON.stringify(inTokenData, null, 2)}`
|
||||
// )
|
||||
|
||||
let tokenQty = 0
|
||||
|
||||
// Validate the input. Mark qty as null if not valid.
|
||||
const vinIsValid = await this.slpUtils.waterfallValidateTxid(
|
||||
thisVin.txid
|
||||
)
|
||||
|
||||
if (!vinIsValid) {
|
||||
// If the input is not a valid, then set qty as null.
|
||||
tokenQty = null
|
||||
} else if (inTokenData.txType === 'SEND') {
|
||||
// Get the appropriate vout token amount. This may throw an error,
|
||||
// which means this Vin is not actually a token UTXO, it was just
|
||||
// associated with a previous token TX.
|
||||
tokenQty = inTokenData.amounts[thisVin.vout - 1]
|
||||
// console.log(`tokenQty: ${JSON.stringify(tokenQty, null, 2)}`)
|
||||
|
||||
//
|
||||
} else if (inTokenData.txType === 'GENESIS') {
|
||||
// Only vout[1] of a Genesis transaction represents the tokens.
|
||||
// Any other outputs in that transaction are normal BCH UTXOs.
|
||||
if (thisVin.vout === 1) {
|
||||
tokenQty = inTokenData.qty
|
||||
// console.log(`tokenQty: ${JSON.stringify(tokenQty, null, 2)}`)
|
||||
}
|
||||
} else if (inTokenData.txType === 'MINT') {
|
||||
// vout=1 (second output) recieves the newly minted tokens.
|
||||
if (thisVin.vout === 1) {
|
||||
tokenQty = inTokenData.qty
|
||||
} else {
|
||||
tokenQty = null
|
||||
}
|
||||
|
||||
//
|
||||
} else {
|
||||
console.log(
|
||||
'Unexpected code path in Transaction.get(). What is the txType?'
|
||||
)
|
||||
console.log(inTokenData)
|
||||
throw new Error('Unexpected code path')
|
||||
}
|
||||
|
||||
if (tokenQty) {
|
||||
// const realQty =
|
||||
// Number(tokenQty) / Math.pow(10, txDetails.tokenDecimals)
|
||||
|
||||
// Calculate the real quantity using a BigNumber, then convert it to a
|
||||
// floating point number.
|
||||
let realQty = new BigNumber(tokenQty).dividedBy(
|
||||
10 ** parseInt(txDetails.tokenDecimals)
|
||||
)
|
||||
realQty = realQty.toString()
|
||||
// realQty = parseFloat(realQty)
|
||||
|
||||
thisVin.tokenQtyStr = realQty
|
||||
thisVin.tokenQty = parseFloat(realQty)
|
||||
// txDetails.vin[i].tokenQty = tokenQty
|
||||
|
||||
// Add token ID to input
|
||||
thisVin.tokenId = inTokenData.tokenId
|
||||
} else {
|
||||
thisVin.tokenQty = null
|
||||
}
|
||||
} catch (err) {
|
||||
// If decodeOpReturn() throws an error, then this input is not
|
||||
// from an SLP transaction and can be ignored.
|
||||
// thisVin.tokenQty = null
|
||||
thisVin.tokenQty = null
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, validate the SLP TX.
|
||||
// this.slpUtils.waterfallValidateTxid(txid, usrObj)
|
||||
txDetails.isValidSLPTx = await this.slpUtils.waterfallValidateTxid(txid)
|
||||
|
||||
// TODO: Convert the block hash to a block height. Add block height
|
||||
// value to the transaction.
|
||||
} catch (err) {
|
||||
// console.log('Error: ', err)
|
||||
|
||||
// This case handles rate limit errors.
|
||||
if (err.response && err.response.data && err.response.data.error) {
|
||||
throw new Error(err.response.data.error)
|
||||
}
|
||||
|
||||
// If decoding the op_return fails, then it's not an SLP transaction,
|
||||
// and the non-hyrated TX details can be returned.
|
||||
return txDetails
|
||||
}
|
||||
|
||||
return txDetails
|
||||
} catch (err) {
|
||||
// console.error('Error in transactions.js/get(): ', err)
|
||||
|
||||
// This case handles rate limit errors.
|
||||
if (err.response && err.response.data && err.response.data.error) {
|
||||
throw new Error(err.response.data.error)
|
||||
}
|
||||
|
||||
if (err.error) throw new Error(err.error)
|
||||
throw err
|
||||
}
|
||||
async get (txid) {
|
||||
// console.log('transaction.get() txid: ', txid)
|
||||
return await this.psfSlpIndexer.tx(txid)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Transaction.get3() get3()
|
||||
* @apiName get3
|
||||
* @api Transaction.getTokenInfo() getTokenInfo()
|
||||
* @apiName getTokenInfo
|
||||
* @apiGroup Transaction
|
||||
* @apiDescription
|
||||
* Returns an object of transaction data, including addresses for input UTXOs.
|
||||
* If it is a SLP token transaction, the token information for inputs and
|
||||
* outputs will also be included.
|
||||
* Given the TXID of a token transaction, it will return data about that
|
||||
* token by retrieving the data from the Genesis transaction and docoding
|
||||
* the OP_RETURN.
|
||||
*
|
||||
* This is an API heavy call. This function will only work with a single txid.
|
||||
* It does not yet support an array of TXIDs.
|
||||
*
|
||||
* This is the same as get(), except it omits DAG validation of the TXID.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let txData = await bchjs.Transaction.get2("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098");
|
||||
* let txData = await bchjs.Transaction.getTokenInfo("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098");
|
||||
* console.log(txData);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*/
|
||||
async get3 (txid) {
|
||||
try {
|
||||
if (typeof txid !== 'string') {
|
||||
throw new Error(
|
||||
'Input to Transaction.get() must be a string containing a TXID.'
|
||||
)
|
||||
}
|
||||
|
||||
// Get TX data
|
||||
const txDetails = await this.rawTransaction.getTxData(txid)
|
||||
// console.log(`txDetails: ${JSON.stringify(txDetails, null, 2)}`)
|
||||
|
||||
// Get the block height the transaction was mined in.
|
||||
const blockHeader = await this.blockchain.getBlockHeader(
|
||||
txDetails.blockhash
|
||||
)
|
||||
txDetails.blockheight = blockHeader.height
|
||||
// console.log(`blockHeader: ${JSON.stringify(blockHeader, null, 2)}`)
|
||||
|
||||
// Set default as not an SLP tx
|
||||
txDetails.isSlpTx = false
|
||||
|
||||
// Get Token Data
|
||||
const txTokenData = await this.getTokenInfo(txid)
|
||||
// console.log(`txTokenData: ${JSON.stringify(txTokenData, null, 2)}`)
|
||||
|
||||
// If not a token, return the tx data. Processing is complete.
|
||||
if (!txTokenData) return txDetails
|
||||
|
||||
// Mark TX as an SLP tx. This does not mean it's valid, it just means
|
||||
// the OP_RETURN passes a basic check.
|
||||
txDetails.isSlpTx = true
|
||||
|
||||
// Get Genesis data
|
||||
const genesisData = await this.getTokenInfo(txTokenData.tokenId)
|
||||
// console.log(`genesisData: ${JSON.stringify(genesisData, null, 2)}`)
|
||||
|
||||
// Add token information to the tx details object.
|
||||
txDetails.tokenTxType = txTokenData.txType
|
||||
txDetails.tokenId = txTokenData.tokenId
|
||||
txDetails.tokenTicker = genesisData.ticker
|
||||
txDetails.tokenName = genesisData.name
|
||||
txDetails.tokenDecimals = genesisData.decimals
|
||||
txDetails.tokenUri = genesisData.documentUri
|
||||
txDetails.tokenDocHash = genesisData.documentHash
|
||||
// console.log(`txDetails before processing input and outputs: ${JSON.stringify(txDetails, null, 2)}`)
|
||||
|
||||
// Process TX Outputs
|
||||
// Add the token quantity to each output.
|
||||
// 'i' starts at 1, because vout[0] is the OP_RETURN
|
||||
for (let i = 0; i < txDetails.vout.length; i++) {
|
||||
const thisVout = txDetails.vout[i]
|
||||
if (txTokenData.txType === 'SEND') {
|
||||
// console.log(
|
||||
// `output txTokenData: ${JSON.stringify(txTokenData, null, 2)}`
|
||||
// )
|
||||
|
||||
// First output is OP_RETURN, so tokenQty is null.
|
||||
if (i === 0) {
|
||||
thisVout.tokenQty = null
|
||||
thisVout.tokenQtyStr = null
|
||||
continue
|
||||
}
|
||||
|
||||
// Non SLP outputs.
|
||||
if (i > txTokenData.amounts.length) {
|
||||
thisVout.tokenQty = null
|
||||
thisVout.tokenQtyStr = null
|
||||
continue
|
||||
}
|
||||
|
||||
const rawQty = txTokenData.amounts[i - 1]
|
||||
|
||||
// Calculate the real quantity using a BigNumber, then convert it to a
|
||||
// floating point number.
|
||||
let realQty = new BigNumber(rawQty).dividedBy(
|
||||
10 ** parseInt(txDetails.tokenDecimals)
|
||||
)
|
||||
realQty = realQty.toString()
|
||||
// realQty = parseFloat(realQty)
|
||||
|
||||
txDetails.vout[i].tokenQtyStr = realQty
|
||||
txDetails.vout[i].tokenQty = parseFloat(realQty)
|
||||
|
||||
// console.log(
|
||||
// `thisVout ${i}: ${JSON.stringify(txDetails.vout[i], null, 2)}`
|
||||
// )
|
||||
} else if (
|
||||
txTokenData.txType === 'GENESIS' ||
|
||||
txTokenData.txType === 'MINT'
|
||||
) {
|
||||
// console.log(
|
||||
// `output txTokenData: ${JSON.stringify(txTokenData, null, 2)}`
|
||||
// )
|
||||
|
||||
let tokenQty = 0 // Default value
|
||||
|
||||
// Only vout[1] of a Genesis or Mint transaction represents the tokens.
|
||||
// Any other outputs in that transaction are normal BCH UTXOs.
|
||||
if (i === 1) {
|
||||
tokenQty = txTokenData.qty
|
||||
// console.log(`tokenQty: ${JSON.stringify(tokenQty, null, 2)}`)
|
||||
|
||||
// Calculate the real quantity using a BigNumber, then convert it to a
|
||||
// floating point number.
|
||||
let realQty = new BigNumber(tokenQty).dividedBy(
|
||||
10 ** parseInt(txDetails.tokenDecimals)
|
||||
)
|
||||
realQty = realQty.toString()
|
||||
// realQty = parseFloat(realQty)
|
||||
|
||||
thisVout.tokenQtyStr = realQty
|
||||
thisVout.tokenQty = parseFloat(realQty)
|
||||
// console.log(`thisVout[${i}]: ${JSON.stringify(thisVout, null, 2)}`)
|
||||
} else if (i === txTokenData.mintBatonVout) {
|
||||
// Optional Mint baton
|
||||
thisVout.tokenQtyStr = '0'
|
||||
thisVout.tokenQty = 0
|
||||
thisVout.isMintBaton = true
|
||||
} else {
|
||||
thisVout.tokenQtyStr = '0'
|
||||
thisVout.tokenQty = 0
|
||||
}
|
||||
} else {
|
||||
throw new Error('Unknown SLP TX type for TX')
|
||||
}
|
||||
}
|
||||
|
||||
// Process TX inputs
|
||||
for (let i = 0; i < txDetails.vin.length; i++) {
|
||||
const thisVin = txDetails.vin[i]
|
||||
// console.log(`thisVin[${i}]: ${JSON.stringify(thisVin, null, 2)}`)
|
||||
|
||||
const vinTokenData = await this.getTokenInfo(thisVin.txid)
|
||||
// console.log(
|
||||
// `vinTokenData ${i}: ${JSON.stringify(vinTokenData, null, 2)}`
|
||||
// )
|
||||
|
||||
// Corner case: Ensure the token ID is the same.
|
||||
const vinTokenIdIsTheSame = vinTokenData.tokenId === txDetails.tokenId
|
||||
|
||||
// If the input is not a token input, or if the tokenID is not the same,
|
||||
// then mark the token output as null.
|
||||
if (!vinTokenData || !vinTokenIdIsTheSame) {
|
||||
thisVin.tokenQty = 0
|
||||
thisVin.tokenQtyStr = '0'
|
||||
thisVin.tokenId = null
|
||||
continue
|
||||
}
|
||||
|
||||
if (vinTokenData.txType === 'SEND') {
|
||||
// console.log(
|
||||
// `SEND vinTokenData ${i}: ${JSON.stringify(vinTokenData, null, 2)}`
|
||||
// )
|
||||
|
||||
const tokenQty = vinTokenData.amounts[thisVin.vout - 1]
|
||||
// console.log(`tokenQty: ${JSON.stringify(tokenQty, null, 2)}`)
|
||||
|
||||
// Calculate the real quantity using a BigNumber, then convert it to a
|
||||
// floating point number.
|
||||
let realQty = new BigNumber(tokenQty).dividedBy(
|
||||
10 ** parseInt(txDetails.tokenDecimals)
|
||||
)
|
||||
realQty = realQty.toString()
|
||||
// realQty = parseFloat(realQty)
|
||||
|
||||
thisVin.tokenQtyStr = realQty
|
||||
thisVin.tokenQty = parseFloat(realQty)
|
||||
thisVin.tokenId = vinTokenData.tokenId
|
||||
} else if (vinTokenData.txType === 'MINT') {
|
||||
// console.log(
|
||||
// `MINT vinTokenData ${i}: ${JSON.stringify(vinTokenData, null, 2)}`
|
||||
// )
|
||||
|
||||
let tokenQty = 0 // Default value
|
||||
|
||||
// Only vout[1] of a Genesis transaction represents the tokens.
|
||||
// Any other outputs in that transaction are normal BCH UTXOs.
|
||||
if (thisVin.vout === 1) {
|
||||
tokenQty = vinTokenData.qty
|
||||
// console.log(`tokenQty: ${JSON.stringify(tokenQty, null, 2)}`)
|
||||
|
||||
// Calculate the real quantity using a BigNumber, then convert it to a
|
||||
// floating point number.
|
||||
let realQty = new BigNumber(tokenQty).dividedBy(
|
||||
10 ** parseInt(txDetails.tokenDecimals)
|
||||
)
|
||||
realQty = realQty.toString()
|
||||
// realQty = parseFloat(realQty)
|
||||
|
||||
thisVin.tokenQtyStr = realQty
|
||||
thisVin.tokenQty = parseFloat(realQty)
|
||||
thisVin.tokenId = vinTokenData.tokenId
|
||||
} else if (thisVin.vout === vinTokenData.mintBatonVout) {
|
||||
// Optional Mint baton
|
||||
thisVin.tokenQtyStr = '0'
|
||||
thisVin.tokenQty = 0
|
||||
thisVin.tokenId = vinTokenData.tokenId
|
||||
thisVin.isMintBaton = true
|
||||
} else {
|
||||
thisVin.tokenQtyStr = '0'
|
||||
thisVin.tokenQty = 0
|
||||
thisVin.tokenId = null
|
||||
}
|
||||
} else if (vinTokenData.txType === 'GENESIS') {
|
||||
// console.log(
|
||||
// `GENESIS vinTokenData ${i}: ${JSON.stringify(
|
||||
// vinTokenData,
|
||||
// null,
|
||||
// 2
|
||||
// )}`
|
||||
// )
|
||||
|
||||
let tokenQty = 0 // Default value
|
||||
|
||||
// Only vout[1] of a Genesis transaction represents the tokens.
|
||||
// Any other outputs in that transaction are normal BCH UTXOs.
|
||||
if (thisVin.vout === 1) {
|
||||
tokenQty = vinTokenData.qty
|
||||
// console.log(`tokenQty: ${JSON.stringify(tokenQty, null, 2)}`)
|
||||
|
||||
// Calculate the real quantity using a BigNumber, then convert it to a
|
||||
// floating point number.
|
||||
let realQty = new BigNumber(tokenQty).dividedBy(
|
||||
10 ** parseInt(txDetails.tokenDecimals)
|
||||
)
|
||||
realQty = realQty.toString()
|
||||
// realQty = parseFloat(realQty)
|
||||
|
||||
thisVin.tokenQtyStr = realQty
|
||||
thisVin.tokenQty = parseFloat(realQty)
|
||||
thisVin.tokenId = vinTokenData.tokenId
|
||||
} else if (thisVin.vout === vinTokenData.mintBatonVout) {
|
||||
// Optional Mint baton
|
||||
thisVin.tokenQtyStr = '0'
|
||||
thisVin.tokenQty = 0
|
||||
thisVin.tokenId = vinTokenData.tokenId
|
||||
thisVin.isMintBaton = true
|
||||
} else {
|
||||
thisVin.tokenQtyStr = '0'
|
||||
thisVin.tokenQty = 0
|
||||
thisVin.tokenId = null
|
||||
}
|
||||
} else {
|
||||
console.log(
|
||||
`Unknown vinTokenData: ${JSON.stringify(vinTokenData, null, 2)}`
|
||||
)
|
||||
throw new Error('Unknown token type in input')
|
||||
}
|
||||
}
|
||||
|
||||
return txDetails
|
||||
} catch (err) {
|
||||
console.error('Error in get3()')
|
||||
|
||||
// This case handles rate limit errors.
|
||||
if (err.response && err.response.data && err.response.data.error) {
|
||||
throw new Error(err.response.data.error)
|
||||
}
|
||||
|
||||
if (err.error) throw new Error(err.error)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// A wrapper for decodeOpReturn(). Returns false if txid is not an SLP tx.
|
||||
// Returns the token data if the txid is an SLP tx.
|
||||
async getTokenInfo (txid) {
|
||||
|
||||
+5
-4
@@ -281,16 +281,17 @@ class Util {
|
||||
|
||||
// Array of blocks.
|
||||
} else if (Array.isArray(address)) {
|
||||
const options = {
|
||||
const options1 = {
|
||||
method: 'POST',
|
||||
url: `${this.restURL}util/validateAddress`,
|
||||
data: {
|
||||
addresses: address
|
||||
},
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
// headers: {
|
||||
// authorization: `Token ${this.apiToken}`
|
||||
// }
|
||||
}
|
||||
const options = Object.assign({}, options1, this.axiosOptions)
|
||||
const response = await axios(options)
|
||||
|
||||
return response.data
|
||||
|
||||
+43
-9
@@ -125,6 +125,7 @@ class UTXO {
|
||||
thisUtxo.qty = thisSlpUtxo.qty
|
||||
thisUtxo.tokenId = thisSlpUtxo.tokenId
|
||||
thisUtxo.address = thisSlpUtxo.address
|
||||
thisUtxo.tokenType = thisSlpUtxo.tokenType
|
||||
|
||||
break
|
||||
}
|
||||
@@ -151,16 +152,38 @@ class UTXO {
|
||||
|
||||
// Get token UTXOs
|
||||
let type1TokenUtxos = utxos.filter(
|
||||
x => x.isSlp === true && x.type === 'token'
|
||||
x => x.isSlp === true && x.type === 'token' && x.tokenType === 1
|
||||
)
|
||||
|
||||
// Hydrate the UTXOs with additional token data.
|
||||
type1TokenUtxos = await this.hydrateTokenData(type1TokenUtxos)
|
||||
|
||||
// Collect and hydrate any type1 baton UTXOs
|
||||
const bchUtxos = utxos.filter(x => x.isSlp === false)
|
||||
const type1BatonUtxos = utxos.filter(
|
||||
x => x.isSlp === true && x.type === 'baton'
|
||||
let type1BatonUtxos = utxos.filter(
|
||||
x => x.isSlp === true && x.type === 'baton' && x.tokenType === 1
|
||||
)
|
||||
type1BatonUtxos = await this.hydrateTokenData(type1BatonUtxos)
|
||||
|
||||
// Collect and hydrate NFT Group tokens
|
||||
let nftGroupTokenUtxos = utxos.filter(
|
||||
x => x.isSlp === true && x.type === 'token' && x.tokenType === 129
|
||||
)
|
||||
nftGroupTokenUtxos = await this.hydrateTokenData(nftGroupTokenUtxos)
|
||||
|
||||
// Collect and hydrate any Group baton UTXOs
|
||||
let groupBatonUtxos = utxos.filter(
|
||||
x => x.isSlp === true && x.type === 'baton' && x.tokenType === 129
|
||||
)
|
||||
groupBatonUtxos = await this.hydrateTokenData(groupBatonUtxos)
|
||||
|
||||
// Collect and hydrate NFT child tokens
|
||||
let nftChildTokenUtxos = utxos.filter(
|
||||
x => x.isSlp === true && x.type === 'token' && x.tokenType === 65
|
||||
)
|
||||
nftChildTokenUtxos = await this.hydrateTokenData(nftChildTokenUtxos)
|
||||
|
||||
// Isolate any UTXOs that are marked null by the SLP indexer.
|
||||
const nullUtxos = utxos.filter(x => x.isSlp === null)
|
||||
|
||||
const outObj = {
|
||||
@@ -171,7 +194,13 @@ class UTXO {
|
||||
tokens: type1TokenUtxos,
|
||||
mintBatons: type1BatonUtxos
|
||||
},
|
||||
nft: {} // Allocated for future support of NFT spec.
|
||||
group: {
|
||||
tokens: nftGroupTokenUtxos,
|
||||
mintBatons: groupBatonUtxos
|
||||
},
|
||||
nft: {
|
||||
tokens: nftChildTokenUtxos
|
||||
}
|
||||
},
|
||||
nullUtxos
|
||||
}
|
||||
@@ -225,11 +254,16 @@ class UTXO {
|
||||
thisUtxo.documentHash = genData[0].tokenData.documentHash
|
||||
thisUtxo.decimals = genData[0].tokenData.decimals
|
||||
|
||||
// Calculate the real token quantity
|
||||
const qty = new BigNumber(thisUtxo.qty).dividedBy(
|
||||
10 ** parseInt(thisUtxo.decimals)
|
||||
)
|
||||
thisUtxo.qtyStr = qty.toString()
|
||||
if (thisUtxo.type !== 'baton') {
|
||||
// Calculate the real token quantity
|
||||
const qty = new BigNumber(thisUtxo.qty).dividedBy(
|
||||
10 ** parseInt(thisUtxo.decimals)
|
||||
)
|
||||
thisUtxo.qtyStr = qty.toString()
|
||||
|
||||
// tokenQty is property expected by SLP.tokentype1.js library
|
||||
thisUtxo.tokenQty = thisUtxo.qtyStr
|
||||
}
|
||||
}
|
||||
|
||||
return utxoAry
|
||||
|
||||
@@ -124,6 +124,25 @@ describe('#psf-slp-indexer', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('#getTokenData', () => {
|
||||
it('should get token data', async () => {
|
||||
const tokenId =
|
||||
'f055256b938f1ecfa270459d6f12c7c8c82b66d3263c03d5074445a2b1a498a3'
|
||||
|
||||
// bchjs.PsfSlpIndexer.restURL = 'http://localhost:3000/v5/'
|
||||
const result = await bchjs.PsfSlpIndexer.getTokenData(tokenId)
|
||||
// console.log('result: ', result)
|
||||
|
||||
assert.property(result, 'genesisData')
|
||||
assert.property(result, 'immutableData')
|
||||
assert.property(result, 'mutableData')
|
||||
|
||||
assert.isObject(result.genesisData)
|
||||
assert.isString(result.immutableData)
|
||||
assert.isString(result.mutableData)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Promise-based sleep function
|
||||
|
||||
@@ -24,5 +24,14 @@ describe('#Transaction', () => {
|
||||
assert.property(result.txData, 'vout')
|
||||
assert.equal(result.txData.isValidSlp, false)
|
||||
})
|
||||
|
||||
it('should handle a coinbase transaction', async () => {
|
||||
const txid = 'cca1d2dd3a533d2f501448dec03face2cb2814afd59a533a611e9a2909f2302b'
|
||||
|
||||
const details = await bchjs.Transaction.get(txid)
|
||||
// console.log(`details: ${JSON.stringify(details, null, 2)}`)
|
||||
|
||||
assert.property(details.txData, 'txid')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -83,10 +83,8 @@ describe('#UTXO', () => {
|
||||
assert.equal(result.slpUtxos.type1.mintBatons.length, 0)
|
||||
})
|
||||
|
||||
// TODO: NFTs are currently not identified as different than normal BCH UTXOs.
|
||||
// The psf-slp-indexer needs to be updated to fix this issue.
|
||||
it('should handle minting batons', async () => {
|
||||
const addr = 'simpleledger:qrm0c67wwqh0w7wjxua2gdt2xggnm90xwsr5k22euj'
|
||||
it('should handle Type1 minting batons', async () => {
|
||||
const addr = 'simpleledger:qz5l5yzz9r09hw9aadcz53elp2knx6gyg5qk3s8md7'
|
||||
|
||||
const result = await bchjs.Utxo.get(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
@@ -105,13 +103,23 @@ describe('#UTXO', () => {
|
||||
assert.equal(result.slpUtxos.type1.tokens.length, 0)
|
||||
})
|
||||
|
||||
it('should handle Group NFTs', async () => {
|
||||
const addr = 'bitcoincash:qrnghwrfgccf3s5e9wnglzxegcnhje9rkcwv2eka33'
|
||||
it('should filter Group tokens and mint batons', async () => {
|
||||
const addr = 'bitcoincash:qzeqcrpe5fcnslv8rfqjq4gh4gzdwytmdc4qmh0ztv'
|
||||
|
||||
const result = await bchjs.Utxo.get(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.equal(result.nullUtxos.length, 0)
|
||||
assert.isAbove(result.slpUtxos.group.tokens.length, 0)
|
||||
assert.isAbove(result.slpUtxos.group.mintBatons.length, 0)
|
||||
})
|
||||
|
||||
it('should filter NFTs', async () => {
|
||||
const addr = 'simpleledger:qq7vp2kvejsql898a2760kuq6xz00h0a5vuwu9lywu'
|
||||
|
||||
const result = await bchjs.Utxo.get(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isAbove(result.slpUtxos.nft.tokens.length, 0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -144,10 +144,17 @@ const tokenData01 = {
|
||||
qty: {}
|
||||
}
|
||||
|
||||
const tokenData = {
|
||||
genesisData: tokenStats.tokenData,
|
||||
immutableData: 'ipfs://bafybeidzfi3sictag4noy746gniyiwwcgio565xuzelmjfwxnga6qyiyai',
|
||||
mutableData: 'ipfs://bafybeie6t5uyupddc7azms737xg4hxrj7i5t5ov3lb5g2qeehaujj6ak64'
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
tokenStats,
|
||||
txData,
|
||||
balance,
|
||||
status,
|
||||
tokenData01
|
||||
tokenData01,
|
||||
tokenData
|
||||
}
|
||||
|
||||
@@ -336,4 +336,79 @@ describe('#PsfSlpIndexer', () => {
|
||||
assert.equal(result, false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#getTokenData', () => {
|
||||
it('should GET token data', async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, 'post').resolves({ data: mockData.tokenData })
|
||||
|
||||
const tokenId =
|
||||
'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2'
|
||||
const result = await bchjs.PsfSlpIndexer.getTokenData(tokenId)
|
||||
assert.property(result, 'genesisData')
|
||||
assert.property(result, 'immutableData')
|
||||
assert.property(result, 'mutableData')
|
||||
|
||||
assert.isObject(result.genesisData)
|
||||
assert.isString(result.immutableData)
|
||||
assert.isString(result.mutableData)
|
||||
|
||||
assert.property(result.genesisData, 'type')
|
||||
assert.property(result.genesisData, 'ticker')
|
||||
assert.property(result.genesisData, 'name')
|
||||
assert.property(result.genesisData, 'tokenId')
|
||||
assert.property(result.genesisData, 'documentUri')
|
||||
assert.property(result.genesisData, 'documentHash')
|
||||
assert.property(result.genesisData, 'decimals')
|
||||
assert.property(result.genesisData, 'mintBatonIsActive')
|
||||
assert.property(result.genesisData, 'tokensInCirculationBN')
|
||||
assert.property(result.genesisData, 'tokensInCirculationStr')
|
||||
assert.property(result.genesisData, 'blockCreated')
|
||||
assert.property(result.genesisData, 'totalBurned')
|
||||
assert.property(result.genesisData, 'totalMinted')
|
||||
})
|
||||
|
||||
it('should throw an error for improper input', async () => {
|
||||
try {
|
||||
const tokenId = 12345
|
||||
|
||||
await bchjs.PsfSlpIndexer.getTokenData(tokenId)
|
||||
assert.equal(true, false, 'Unexpected result!')
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(err.message, 'Input tokenId must be a string.')
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle axios error', async () => {
|
||||
try {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, 'post').throws(new Error('test error'))
|
||||
|
||||
const tokenId =
|
||||
'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2'
|
||||
await bchjs.PsfSlpIndexer.getTokenData(tokenId)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
assert.equal(true, false, 'Unexpected result!')
|
||||
} catch (err) {
|
||||
assert.include(err.message, 'test error')
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle request error', async () => {
|
||||
try {
|
||||
// Stub the network call.
|
||||
const testErr = new Error()
|
||||
testErr.response = { data: { status: 422 } }
|
||||
sandbox.stub(axios, 'post').throws(testErr)
|
||||
|
||||
const tokenId =
|
||||
'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2'
|
||||
await bchjs.PsfSlpIndexer.getTokenData(tokenId)
|
||||
assert.equal(true, false, 'Unexpected result!')
|
||||
} catch (err) {
|
||||
assert.equal(err.status, 422)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,707 +5,23 @@
|
||||
// Public npm libraries
|
||||
const assert = require('chai').assert
|
||||
const sinon = require('sinon')
|
||||
const cloneDeep = require('lodash.clonedeep')
|
||||
// const cloneDeep = require('lodash.clonedeep')
|
||||
|
||||
const BCHJS = require('../../src/bch-js')
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
const mockDataLib = require('./fixtures/transaction-mock.js')
|
||||
// const mockDataLib = require('./fixtures/transaction-mock.js')
|
||||
|
||||
describe('#TransactionLib', () => {
|
||||
let sandbox, mockData
|
||||
let sandbox
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = sinon.createSandbox()
|
||||
|
||||
mockData = cloneDeep(mockDataLib)
|
||||
// mockData = cloneDeep(mockDataLib)
|
||||
})
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
describe('#getOld', () => {
|
||||
it('should throw an error if txid is not specified', async () => {
|
||||
try {
|
||||
await bchjs.Transaction.getOld()
|
||||
|
||||
assert.fail('Unexpected code path!')
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
'Input to Transaction.get() must be a string containing a TXID.'
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('should get details about a non-SLP transaction', async () => {
|
||||
const txid =
|
||||
'2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
|
||||
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.nonSlpTxDetails)
|
||||
|
||||
const result = await bchjs.Transaction.getOld(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[0].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert that added properties exist.
|
||||
assert.property(result.vin[0], 'address')
|
||||
assert.property(result.vin[0], 'value')
|
||||
assert.property(result, 'isValidSLPTx')
|
||||
assert.equal(result.isValidSLPTx, false)
|
||||
})
|
||||
|
||||
it('should get details about a SLP transaction', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.slpTxDetails)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.mockOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.mockOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.mockOpReturnData03)
|
||||
.onCall(3)
|
||||
.rejects(new Error('No OP_RETURN'))
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'waterfallValidateTxid')
|
||||
.resolves(true)
|
||||
|
||||
const txid =
|
||||
'266844d53e46bbd7dd37134688dffea6e54d944edff27a0add63dd0908839bc1'
|
||||
|
||||
const result = await bchjs.Transaction.getOld(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert that added properties exist.
|
||||
assert.property(result.vout[0], 'tokenQty')
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.property(result.vin[0], 'address')
|
||||
assert.property(result.vin[0], 'value')
|
||||
assert.property(result.vin[0], 'tokenQty')
|
||||
assert.property(result, 'isValidSLPTx')
|
||||
assert.equal(result.isValidSLPTx, true)
|
||||
})
|
||||
|
||||
it('should catch and throw error on network error', async () => {
|
||||
try {
|
||||
const txid =
|
||||
'2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
|
||||
|
||||
// Force an error
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.rejects(new Error('test error'))
|
||||
|
||||
await bchjs.Transaction.getOld(txid)
|
||||
|
||||
assert.fail('Unexpected code path')
|
||||
} catch (err) {
|
||||
assert.include(err.message, 'test error')
|
||||
}
|
||||
})
|
||||
|
||||
// This test case was created in response to a bug. When the input TX
|
||||
// was a Genesis SLP transaction, the inputs of the transaction were not
|
||||
// being hydrated properly.
|
||||
it('should get input details when input is a genesis tx', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.genesisTestInputTx)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.genesisTestOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.genesisTestOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.genesisTestOpReturnData02)
|
||||
.onCall(3)
|
||||
.resolves(mockData.genesisTestOpReturnData02)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'waterfallValidateTxid')
|
||||
.resolves(true)
|
||||
|
||||
const txid =
|
||||
'874306bda204d3a5dd15e03ea5732cccdca4c33a52df35162cdd64e30ea7f04e'
|
||||
|
||||
const result = await bchjs.Transaction.getOld(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert that added properties exist.
|
||||
assert.property(result.vout[0], 'tokenQty')
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.property(result.vin[0], 'address')
|
||||
assert.property(result.vin[0], 'value')
|
||||
assert.property(result.vin[0], 'tokenQty')
|
||||
assert.property(result, 'isValidSLPTx')
|
||||
assert.equal(result.isValidSLPTx, true)
|
||||
|
||||
// Assert inputs values unique to a Genesis input have the proper values.
|
||||
assert.equal(result.vin[0].tokenQty, 10000000)
|
||||
assert.equal(result.vin[1].tokenQty, null)
|
||||
})
|
||||
|
||||
it('should get input details when input is a mint tx', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.mintTestInputTx)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.mintTestOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.mintTestOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.mintTestOpReturnData02)
|
||||
.onCall(3)
|
||||
.resolves(mockData.mintTestOpReturnData03)
|
||||
.onCall(4)
|
||||
.resolves(mockData.mintTestOpReturnData03)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'waterfallValidateTxid')
|
||||
.resolves(true)
|
||||
|
||||
const txid =
|
||||
'4640a734063ea79fa587a3cac38a70a2f6f3db0011e23514024185982110d0fa'
|
||||
|
||||
const result = await bchjs.Transaction.getOld(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert that added properties exist.
|
||||
assert.property(result.vout[0], 'tokenQty')
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.property(result.vin[0], 'address')
|
||||
assert.property(result.vin[0], 'value')
|
||||
assert.property(result.vin[0], 'tokenQty')
|
||||
assert.property(result, 'isValidSLPTx')
|
||||
assert.equal(result.isValidSLPTx, true)
|
||||
|
||||
// Assert inputs values unique to a Mint input have the proper values.
|
||||
assert.equal(result.vin[0].tokenQty, 43545.34534)
|
||||
assert.equal(result.vin[1].tokenQty, 2.34123)
|
||||
assert.equal(result.vin[2].tokenQty, null)
|
||||
})
|
||||
|
||||
// This test case was generated from the problematic transaction that
|
||||
// used inputs in a 'non-standard' way.
|
||||
it('should correctly assign quantities to mixed mint inputs', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.sendTestInputTx01)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.sendTestOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.sendTestOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.sendTestOpReturnData03)
|
||||
.onCall(3)
|
||||
.resolves(mockData.sendTestOpReturnData03)
|
||||
.onCall(4)
|
||||
.resolves(mockData.sendTestOpReturnData04)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'waterfallValidateTxid')
|
||||
.resolves(true)
|
||||
|
||||
const txid =
|
||||
'6bc111fbf5b118021d68355ca19a0e77fa358dd931f284b2550f79a51ab4792a'
|
||||
|
||||
const result = await bchjs.Transaction.getOld(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert that added properties exist.
|
||||
assert.property(result.vout[0], 'tokenQty')
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.property(result.vin[0], 'address')
|
||||
assert.property(result.vin[0], 'value')
|
||||
assert.property(result.vin[0], 'tokenQty')
|
||||
assert.property(result, 'isValidSLPTx')
|
||||
assert.equal(result.isValidSLPTx, true)
|
||||
|
||||
// Assert inputs values unique to a Mint input have the proper values.
|
||||
assert.equal(result.vin[0].tokenQty, 100000000)
|
||||
assert.equal(result.vin[1].tokenQty, null)
|
||||
assert.equal(result.vin[2].tokenQty, 99000000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#get3', () => {
|
||||
it('should throw an error if txid is not specified', async () => {
|
||||
try {
|
||||
await bchjs.Transaction.get3()
|
||||
|
||||
assert.fail('Unexpected code path!')
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
'Input to Transaction.get() must be a string containing a TXID.'
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('should get details about a non-SLP transaction', async () => {
|
||||
const txid =
|
||||
'2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
|
||||
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.nonSlpTxDetails)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.blockchain, 'getBlockHeader')
|
||||
.resolves({ height: 602405 })
|
||||
sandbox.stub(bchjs.Transaction, 'getTokenInfo').resolves(false)
|
||||
|
||||
const result = await bchjs.Transaction.get3(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[0].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert that added properties exist.
|
||||
assert.property(result.vin[0], 'address')
|
||||
assert.property(result.vin[0], 'value')
|
||||
|
||||
// Assert blockheight is added
|
||||
assert.equal(result.blockheight, 602405)
|
||||
assert.equal(result.isSlpTx, false)
|
||||
})
|
||||
|
||||
it('should get details about a SLP SEND tx with SEND input', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.slpTxDetails)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.blockchain, 'getBlockHeader')
|
||||
.resolves({ height: 603424 })
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.mockOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.mockOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.mockOpReturnData03)
|
||||
.onCall(3)
|
||||
.rejects(new Error('No OP_RETURN'))
|
||||
|
||||
const txid =
|
||||
'266844d53e46bbd7dd37134688dffea6e54d944edff27a0add63dd0908839bc1'
|
||||
|
||||
const result = await bchjs.Transaction.get3(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert outputs have expected properties
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.equal(result.vout[0].tokenQtyStr, null)
|
||||
assert.equal(result.vout[1].tokenQty, 1)
|
||||
assert.equal(result.vout[1].tokenQtyStr, '1')
|
||||
assert.equal(result.vout[2].tokenQty, 998833)
|
||||
assert.equal(result.vout[2].tokenQtyStr, '998833')
|
||||
assert.equal(result.vout[3].tokenQty, null)
|
||||
assert.equal(result.vout[3].tokenQtyStr, null)
|
||||
|
||||
// Assert that inputs have expected properties
|
||||
assert.equal(result.vin[0].tokenQtyStr, '998834')
|
||||
assert.equal(result.vin[0].tokenQty, 998834)
|
||||
assert.equal(
|
||||
result.vin[0].tokenId,
|
||||
'497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7'
|
||||
)
|
||||
assert.equal(result.vin[1].tokenQtyStr, '0')
|
||||
assert.equal(result.vin[1].tokenQty, 0)
|
||||
assert.equal(result.vin[1].tokenId, null)
|
||||
|
||||
// Assert blockheight is added
|
||||
assert.equal(result.blockheight, 603424)
|
||||
assert.equal(result.isSlpTx, true)
|
||||
})
|
||||
|
||||
it('should catch and throw error on network error', async () => {
|
||||
try {
|
||||
const txid =
|
||||
'2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
|
||||
|
||||
// Force an error
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.rejects(new Error('test error'))
|
||||
|
||||
await bchjs.Transaction.get3(txid)
|
||||
|
||||
assert.fail('Unexpected code path')
|
||||
} catch (err) {
|
||||
assert.include(err.message, 'test error')
|
||||
}
|
||||
})
|
||||
|
||||
// This test case was created in response to a bug. When the input TX
|
||||
// was a Genesis SLP transaction, the inputs of the transaction were not
|
||||
// being hydrated properly.
|
||||
it('should get details about a SLP SEND tx with GENSIS input', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.genesisTestInputTx)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.blockchain, 'getBlockHeader')
|
||||
.resolves({ height: 543409 })
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.genesisTestOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.genesisTestOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.genesisTestOpReturnData02)
|
||||
.onCall(3)
|
||||
.resolves(mockData.genesisTestOpReturnData02)
|
||||
|
||||
const txid =
|
||||
'874306bda204d3a5dd15e03ea5732cccdca4c33a52df35162cdd64e30ea7f04e'
|
||||
|
||||
const result = await bchjs.Transaction.get3(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert outputs have expected properties and values
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.equal(result.vout[0].tokenQtyStr, null)
|
||||
assert.equal(result.vout[1].tokenQty, 5000000)
|
||||
assert.equal(result.vout[1].tokenQtyStr, '5000000')
|
||||
assert.equal(result.vout[2].tokenQty, 5000000)
|
||||
assert.equal(result.vout[2].tokenQtyStr, '5000000')
|
||||
assert.equal(result.vout[3].tokenQty, null)
|
||||
assert.equal(result.vout[3].tokenQtyStr, null)
|
||||
|
||||
// Assert inputs have expected properties and values
|
||||
assert.equal(result.vin[0].tokenQty, 10000000)
|
||||
assert.equal(result.vin[0].tokenQtyStr, '10000000')
|
||||
assert.equal(
|
||||
result.vin[0].tokenId,
|
||||
'323a1e35ae0b356316093d20f2d9fbc995d19314b5c0148b78dc8d9c0dab9d35'
|
||||
)
|
||||
assert.equal(result.vin[1].tokenQty, 0)
|
||||
assert.equal(result.vin[1].tokenQtyStr, '0')
|
||||
assert.equal(result.vin[1].tokenId, null)
|
||||
|
||||
// Assert blockheight is added
|
||||
assert.equal(result.blockheight, 543409)
|
||||
assert.equal(result.isSlpTx, true)
|
||||
})
|
||||
|
||||
it('should get details about a SLP SEND tx with MINT (and GENESIS) input', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.mintTestInputTx)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.blockchain, 'getBlockHeader')
|
||||
.resolves({ height: 543614 })
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.mintTestOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.mintTestOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.mintTestOpReturnData02)
|
||||
.onCall(3)
|
||||
.resolves(mockData.mintTestOpReturnData03)
|
||||
.onCall(4)
|
||||
.resolves(mockData.mintTestOpReturnData03)
|
||||
|
||||
const txid =
|
||||
'4640a734063ea79fa587a3cac38a70a2f6f3db0011e23514024185982110d0fa'
|
||||
|
||||
const result = await bchjs.Transaction.get3(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert expected output properties and values exist.
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.equal(result.vout[1].tokenQty, 43547.68657)
|
||||
assert.equal(result.vout[1].tokenQtyStr, '43547.68657')
|
||||
assert.equal(result.vout[2].tokenQty, null)
|
||||
|
||||
// Assert expected input properties and values exist.
|
||||
assert.equal(result.vin[0].tokenQty, 43545.34534)
|
||||
assert.equal(result.vin[0].tokenQtyStr, '43545.34534')
|
||||
assert.equal(
|
||||
result.vin[0].tokenId,
|
||||
'938cc18e618967d787897bbc64b9a8d201b94ec7c69b1a9949eab0433ba5cdf8'
|
||||
)
|
||||
assert.equal(result.vin[1].tokenQty, 2.34123)
|
||||
assert.equal(result.vin[1].tokenQtyStr, '2.34123')
|
||||
assert.equal(
|
||||
result.vin[1].tokenId,
|
||||
'938cc18e618967d787897bbc64b9a8d201b94ec7c69b1a9949eab0433ba5cdf8'
|
||||
)
|
||||
assert.equal(result.vin[2].tokenQty, 0)
|
||||
assert.equal(result.vin[2].tokenQtyStr, '0')
|
||||
assert.equal(result.vin[2].tokenId, null)
|
||||
|
||||
// Assert blockheight is added
|
||||
assert.equal(result.blockheight, 543614)
|
||||
assert.equal(result.isSlpTx, true)
|
||||
})
|
||||
|
||||
// This test case was generated from the problematic transaction that
|
||||
// used inputs in a 'non-standard' way.
|
||||
it('should get details about a SLP SEND tx with MINT (and SEND) input', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.sendTestInputTx01)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.blockchain, 'getBlockHeader')
|
||||
.resolves({ height: 543957 })
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.sendTestOpReturnData01)
|
||||
.onCall(1)
|
||||
.resolves(mockData.sendTestOpReturnData02)
|
||||
.onCall(2)
|
||||
.resolves(mockData.sendTestOpReturnData03)
|
||||
.onCall(3)
|
||||
.resolves(mockData.sendTestOpReturnData03)
|
||||
.onCall(4)
|
||||
.resolves(mockData.sendTestOpReturnData04)
|
||||
|
||||
const txid =
|
||||
'6bc111fbf5b118021d68355ca19a0e77fa358dd931f284b2550f79a51ab4792a'
|
||||
|
||||
const result = await bchjs.Transaction.get3(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert the outputs have expected properties and values.
|
||||
assert.equal(result.vout[0].tokenQty, null)
|
||||
assert.equal(result.vout[1].tokenQty, 1000000)
|
||||
assert.equal(result.vout[1].tokenQtyStr, '1000000')
|
||||
assert.equal(result.vout[2].tokenQty, 198000000)
|
||||
assert.equal(result.vout[2].tokenQtyStr, '198000000')
|
||||
assert.equal(result.vout[3].tokenQty, null)
|
||||
|
||||
// Assert the inputs have expected properties and values.
|
||||
assert.equal(result.vin[0].tokenQty, 100000000)
|
||||
assert.equal(result.vin[0].tokenQtyStr, '100000000')
|
||||
assert.equal(
|
||||
result.vin[0].tokenId,
|
||||
'550d19eb820e616a54b8a73372c4420b5a0567d8dc00f613b71c5234dc884b35'
|
||||
)
|
||||
assert.equal(result.vin[1].tokenQty, 0)
|
||||
assert.equal(result.vin[1].tokenQtyStr, 0)
|
||||
assert.equal(result.vin[1].tokenId, null)
|
||||
assert.equal(result.vin[2].tokenQty, 99000000)
|
||||
assert.equal(result.vin[2].tokenQtyStr, '99000000')
|
||||
assert.equal(
|
||||
result.vin[2].tokenId,
|
||||
'550d19eb820e616a54b8a73372c4420b5a0567d8dc00f613b71c5234dc884b35'
|
||||
)
|
||||
|
||||
// Assert blockheight is added
|
||||
assert.equal(result.blockheight, 543957)
|
||||
assert.equal(result.isSlpTx, true)
|
||||
})
|
||||
|
||||
// This was a problematic TX
|
||||
it('should process MINT TX with GENESIS input', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.mintTestInputTx02)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.blockchain, 'getBlockHeader')
|
||||
.resolves({ height: 543614 })
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.slpUtils, 'decodeOpReturn')
|
||||
.onCall(0)
|
||||
.resolves(mockData.mintTestOpReturnData04)
|
||||
.onCall(1)
|
||||
.resolves(mockData.mintTestOpReturnData05)
|
||||
.onCall(2)
|
||||
.resolves(mockData.mintTestOpReturnData05)
|
||||
.onCall(3)
|
||||
.resolves(mockData.mintTestOpReturnData05)
|
||||
.onCall(4)
|
||||
.resolves(mockData.mintTestOpReturnData05)
|
||||
.onCall(5)
|
||||
.resolves(mockData.mintTestOpReturnData05)
|
||||
|
||||
const txid =
|
||||
'ee9d3cf5153599c134147e3fac9844c68e216843f4452a1ce15a29452af6db34'
|
||||
|
||||
const result = await bchjs.Transaction.get3(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert outputs have expected properties and values
|
||||
assert.equal(result.vout[0].tokenQty, 0)
|
||||
assert.equal(result.vout[0].tokenQty, '0')
|
||||
assert.equal(result.vout[1].tokenQty, 2.34123)
|
||||
assert.equal(result.vout[1].tokenQty, '2.34123')
|
||||
assert.equal(result.vout[2].tokenQty, 0)
|
||||
assert.equal(result.vout[2].tokenQty, '0')
|
||||
assert.equal(result.vout[2].isMintBaton, true)
|
||||
assert.equal(result.vout[3].tokenQty, 0)
|
||||
assert.equal(result.vout[3].tokenQty, '0')
|
||||
|
||||
// Assert inputs have expected properties and values
|
||||
assert.equal(result.vin[0].tokenQty, 0)
|
||||
assert.equal(result.vin[0].tokenQtyStr, '0')
|
||||
assert.equal(result.vin[0].tokenId, null)
|
||||
assert.equal(result.vin[1].tokenQty, 0)
|
||||
assert.equal(result.vin[1].tokenQtyStr, '0')
|
||||
assert.equal(
|
||||
result.vin[1].tokenId,
|
||||
'938cc18e618967d787897bbc64b9a8d201b94ec7c69b1a9949eab0433ba5cdf8'
|
||||
)
|
||||
assert.equal(result.vin[1].isMintBaton, true)
|
||||
|
||||
// Assert added TX data exists.
|
||||
assert.equal(result.blockheight, 543614)
|
||||
assert.equal(result.isSlpTx, true)
|
||||
})
|
||||
|
||||
// It should process a GENESIS tx
|
||||
it('should process a GENESIS tx', async () => {
|
||||
// Mock dependencies
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.rawTransaction, 'getTxData')
|
||||
.resolves(mockData.genesisTestInputTx02)
|
||||
sandbox
|
||||
.stub(bchjs.Transaction.blockchain, 'getBlockHeader')
|
||||
.resolves({ height: 571212 })
|
||||
sandbox
|
||||
.stub(bchjs.Transaction, 'getTokenInfo')
|
||||
.onCall(0)
|
||||
.resolves(mockData.genesisTestOpReturn03)
|
||||
.onCall(1)
|
||||
.resolves(mockData.genesisTestOpReturn03)
|
||||
.onCall(2)
|
||||
.resolves(false)
|
||||
.onCall(3)
|
||||
.resolves(false)
|
||||
.onCall(4)
|
||||
.resolves(false)
|
||||
|
||||
const txid =
|
||||
'4de69e374a8ed21cbddd47f2338cc0f479dc58daa2bbe11cd604ca488eca0ddf'
|
||||
|
||||
const result = await bchjs.Transaction.get3(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
// Assert that there are stanardized properties.
|
||||
assert.property(result, 'txid')
|
||||
assert.property(result, 'vin')
|
||||
assert.property(result, 'vout')
|
||||
assert.property(result.vout[0], 'value')
|
||||
assert.property(result.vout[1].scriptPubKey, 'addresses')
|
||||
|
||||
// Assert output have expected properties and values
|
||||
assert.equal(result.vout[0].tokenQty, 0)
|
||||
assert.equal(result.vout[0].tokenQtyStr, '0')
|
||||
assert.equal(result.vout[0].isMintBaton, true)
|
||||
assert.equal(result.vout[1].tokenQty, 1000000000)
|
||||
assert.equal(result.vout[1].tokenQtyStr, '1000000000')
|
||||
assert.equal(result.vout[2].tokenQty, 0)
|
||||
assert.equal(result.vout[2].tokenQtyStr, '0')
|
||||
|
||||
// Assert input have expected properties and values
|
||||
assert.equal(result.vin[0].tokenQty, 0)
|
||||
assert.equal(result.vin[0].tokenQtyStr, '0')
|
||||
assert.equal(result.vin[0].tokenId, null)
|
||||
assert.equal(result.vin[1].tokenQty, 0)
|
||||
assert.equal(result.vin[1].tokenQtyStr, '0')
|
||||
assert.equal(result.vin[1].tokenId, null)
|
||||
|
||||
// Assert added TX data exists.
|
||||
assert.equal(result.blockheight, 571212)
|
||||
assert.equal(result.isSlpTx, true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#get', () => {
|
||||
it('should proxy psf-slp-indexer', async () => {
|
||||
// console.log('bchjs.Transaction: ', bchjs.Transaction)
|
||||
|
||||
Reference in New Issue
Block a user