Compare commits

..
32 Commits
Author SHA1 Message Date
Chris Troutner 372d1b099d Merge pull request #244 from Permissionless-Software-Foundation/ct-unstable
fix(address): Adding toEtokenAddress() function
2022-07-10 09:50:44 -07:00
Chris Troutner dbfaf9c4ab fix(address): Adding toEtokenAddress() function 2022-07-10 09:47:49 -07:00
Chris Troutner eaa08f74e7 Merge pull request #243 from Permissionless-Software-Foundation/ct-unstable
fix(test): Updating integration test
2022-05-15 07:53:53 -07:00
Chris Troutner 9ac620ee64 fix(test): Updating integration test 2022-05-15 07:50:57 -07:00
Chris Troutner ac0a4b0407 Merge pull request #242 from Permissionless-Software-Foundation/ct-unstable
feat(Utxo.isValid()): can test if a UTXO has been spent
2022-05-10 09:34:37 -07:00
Chris Troutner 686012037f feat(Utxo.isValid()): can test if a UTXO has been spent 2022-05-10 09:30:57 -07:00
Chris Troutner cfb7b9f779 Merge pull request #241 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Fixing broken UTXO.get() test
2022-05-09 10:35:21 -07:00
Chris Troutner 06e5af4b5d fix(tests): Fixing broken UTXO.get() test 2022-05-09 10:33:06 -07:00
Chris Troutner 249e93a3f4 Merge pull request #240 from Permissionless-Software-Foundation/ct-unstable
fix(test): Updating UTXO integration tests
2022-05-09 10:25:58 -07:00
Chris Troutner 761a2d226c fix(test): Updating UTXO integration tests 2022-05-09 10:24:00 -07:00
Chris Troutner 5e5e636831 Merge pull request #239 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Fixing broken integration tests for token data
2022-05-09 09:49:02 -07:00
Chris Troutner 2adc2dfebb fix(tests): Fixing broken integration tests for token data 2022-05-09 09:45:28 -07:00
Chris Troutner f9bc44ccb7 Merge pull request #238 from Permissionless-Software-Foundation/ct-unstable
fix(token data): Returning CID rather than content itself
2022-05-07 20:59:55 -07:00
Chris Troutner 298b8f56ff Merge branch 'temp-token-data' into ct-unstable 2022-05-07 20:54:49 -07:00
Chris Troutner 139da8cf7b fix(token data): Returning CID rather than content itself 2022-05-07 20:54:20 -07:00
Chris Troutner 08e03c14d8 Merge pull request #234 from Permissionless-Software-Foundation/dh-psfSlpIndexer
feat(slpindexer): Added bchjs.PsfSlpIndexer.getTokenData()
2022-05-07 20:25:15 -07:00
Chris Troutner 7da010e7af Using config.restURL instead of hard-coded URL 2022-05-07 20:20:30 -07:00
Chris Troutner 7b6eebe7c7 Merge branch 'master' into dh-psfSlpIndexer 2022-05-07 20:05:25 -07:00
Chris Troutner 843f5eacef Merge pull request #237 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Added additional integration tests
2022-05-05 12:08:46 -07:00
Chris Troutner 416e302ca5 fix(Utxo.get()): Added additional integration tests 2022-05-05 12:06:59 -07:00
Chris Troutner 1c66da70b6 Merge pull request #236 from Permissionless-Software-Foundation/ct-unstable
fix(mintNFTGroupOpReturn()): Updating to use UTXOs from psf-slp-indexer
2022-05-05 10:45:59 -07:00
Chris Troutner 59e92adf0b fix(mintNFTGroupOpReturn()): Updating to use UTXOs from psf-slp-indexer 2022-05-05 10:43:40 -07:00
Chris Troutner f369411ccb Merge pull request #235 from Permissionless-Software-Foundation/ct-unstable
Updating Utxo.get()
2022-05-05 10:05:36 -07:00
Chris Troutner 0504cf7b8d fix(Utxo.get()): Adding filtering for Group batons 2022-05-05 10:03:35 -07:00
Chris Troutner 88ae47cade fix(Utxo.get()): Adding prototype NFT filtering 2022-05-04 17:44:53 -07:00
Daniel Gonzalez d144b13500 feat(slpindexer): Added bchjs.PsfSlpIndexer.getTokenData() 2022-05-04 18:29:54 -04:00
Chris Troutner 30d58bc337 Merge pull request #233 from Permissionless-Software-Foundation/ct-unstable
fix(readme): Adding backup information
2022-04-30 19:48:24 -07:00
Chris Troutner 651ae3f6ca fix(readme): Adding backup information 2022-04-30 19:37:30 -07:00
Chris Troutner 04cd90f0f4 Merge pull request #232 from Permissionless-Software-Foundation/ct-unstable
Updating README
2022-04-30 16:09:24 -07:00
Chris Troutner 552ee31b79 Adding QR to readme 2022-04-30 16:07:17 -07:00
Chris Troutner affa9619bb fix(README): Updating README 2022-04-30 16:04:22 -07:00
Chris Troutner 39bff131af fix(generateMintOpReturn): Adding additional input validation 2022-04-24 10:28:46 -07:00
14 changed files with 471 additions and 50 deletions
+26 -26
View File
@@ -5,7 +5,7 @@
[![License](https://img.shields.io/npm/l/@psf/bch-js)](https://github.com/Permissionless-Software-Foundation/bch-js/blob/master/LICENSE.md)
[![js-standard-style](https://img.shields.io/badge/javascript-standard%20code%20style-green.svg?style=flat-square)](https://github.com/feross/standard) [![Join the chat at https://gitter.im/Permissionless-Software-Foundation/bch-js](https://badges.gitter.im/Permissionless-Software-Foundation/bch-js.svg)](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

+30 -1
View File
@@ -133,7 +133,7 @@ class Address {
* @api Address.toEcashAddress() toEcashAddress()
* @apiName toEcashAddress
* @apiGroup Address
* @apiDescription Convert legacy to cashAddress format
* @apiDescription Convert legacy to eCash (XEC) format
*
* @apiExample Example usage:
* // mainnet
@@ -158,6 +158,35 @@ class Address {
return ecashAddress.split(':')[1]
}
/**
* @api Address.toEtokenAddress() toEtokenAddress()
* @apiName toEtokenAddress
* @apiGroup Address
* @apiDescription Convert legacy to eToken (XEC) format
*
* @apiExample Example usage:
* // mainnet
* bchjs.Address.toEcashAddress('bitcoincash:qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2')
* // ecash:qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da
*
* // mainnet no prefix
* bchjs.Address.toEcashAddress('bitcoincash:qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2', false)
* // qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da
*
*/
toEtokenAddress (address, prefix = true) {
const decoded = this._decode(address)
const etokenAddress = cashaddr.encode(
'etoken',
decoded.type,
decoded.hash
)
if (prefix) return etokenAddress
return etokenAddress.split(':')[1]
}
/**
* @api Address.ecashtoCashAddress() ecashtoCashAddress()
* @apiName ecashtoCashAddress
+1 -1
View File
@@ -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);
+68 -1
View File
@@ -41,7 +41,7 @@ class PsfSlpIndexer {
this.rawTransaction = new RawTransaction(config)
this.slpUtils = new SlpUtils(config)
// _this = this
// _this = this
}
/**
@@ -374,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
+1 -1
View File
@@ -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]
}
}
+5
View File
@@ -375,6 +375,9 @@ 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
@@ -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
+92 -12
View File
@@ -10,6 +10,7 @@ const Electrumx = require('./electrumx')
const Slp = require('./slp/slp')
const PsfSlpIndexer = require('./psf-slp-indexer')
const BigNumber = require('bignumber.js')
const Blockchain = require('./blockchain')
class UTXO {
constructor (config = {}) {
@@ -18,6 +19,7 @@ class UTXO {
this.slp = new Slp(config)
this.psfSlpIndexer = new PsfSlpIndexer(config)
this.BigNumber = BigNumber
this.blockchain = new Blockchain(config)
}
/**
@@ -125,6 +127,7 @@ class UTXO {
thisUtxo.qty = thisSlpUtxo.qty
thisUtxo.tokenId = thisSlpUtxo.tokenId
thisUtxo.address = thisSlpUtxo.address
thisUtxo.tokenType = thisSlpUtxo.tokenType
break
}
@@ -151,19 +154,37 @@ 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 baton UTXOs
// Collect and hydrate any type1 baton UTXOs
const bchUtxos = utxos.filter(x => x.isSlp === false)
let type1BatonUtxos = utxos.filter(
x => x.isSlp === true && x.type === 'baton'
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)
@@ -175,14 +196,20 @@ class UTXO {
tokens: type1TokenUtxos,
mintBatons: type1BatonUtxos
},
nft: {} // Allocated for future support of NFT spec.
group: {
tokens: nftGroupTokenUtxos,
mintBatons: groupBatonUtxos
},
nft: {
tokens: nftChildTokenUtxos
}
},
nullUtxos
}
return outObj
} catch (err) {
console.error('Error in bchjs.Utxo.get(): ', err)
console.error('Error in bchjs.Utxo.get()')
if (err.error) throw new Error(err.error)
throw err
@@ -229,14 +256,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
// tokenQty is property expected by SLP.tokentype1.js library
thisUtxo.tokenQty = thisUtxo.qtyStr
}
}
return utxoAry
@@ -309,6 +338,57 @@ class UTXO {
return utxos[largestIndex]
}
/**
* @api Utxo.isValid() isValid()
* @apiName isValid
* @apiGroup UTXO
* @apiDescription Validate that UTXO exists and is still spendable.
*
* Given a UTXO, this method will return true if the UTXO is still in the
* mempool and still valid for spending. It will return false if the UTXO
* has been spent.
*
* @apiExample Example usage:
* (async () => {
* try {
* const utxos = await bchjs.Utxo.get('bitcoincash:qq54fgjn3hz0357n8a6guy4demw9xfkjk5jcj0xr0z');
* const isValid = bchjs.Utxo.isValid(utxos.bchUtxos[0])
* console.log(isValid);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // returns
* true
*/
async isValid (utxo) {
try {
// console.log('utxo: ', utxo)
// Convert different properties from different indexers
const txid = utxo.txid || utxo.tx_hash
const vout = utxo.vout | utxo.tx_pos
// Query the full node
const txOut = await this.blockchain.getTxOut(txid, vout, true)
// console.log('txOut: ', txOut)
// Simplify results to either true or false.
let isValid = null
if (txOut === null) {
isValid = false
} else {
isValid = true
}
return isValid
} catch (err) {
console.log('Error in Utxo.isValid()')
throw err
}
}
}
module.exports = UTXO
@@ -124,6 +124,25 @@ describe('#psf-slp-indexer', () => {
}
})
})
describe('#getTokenData', () => {
it('should get token data', async () => {
const tokenId =
'd9aafa7acb514c597caf440ae268b5e4e955f2687e05f044cdf8fd9550d9a27b'
// 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
@@ -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:qrp4mlmsrtwlvjn4seuchvtmus06tuqmpv4awvv7m7'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -105,13 +103,82 @@ 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:qrp4mlmsrtwlvjn4seuchvtmus06tuqmpvex9he79q'
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 = 'bitcoincash:qrp4mlmsrtwlvjn4seuchvtmus06tuqmpvex9he79q'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(result.slpUtxos.nft.tokens.length, 0)
})
})
describe('#isValid', () => {
it('should return true for valid UTXO with fullnode properties', async () => {
const utxo = {
txid: 'b94e1ff82eb5781f98296f0af2488ff06202f12ee92b0175963b8dba688d1b40',
vout: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result)
assert.equal(result, true)
})
it('should return true for valid UTXO with fulcrum properties', async () => {
const utxo = {
tx_hash: 'b94e1ff82eb5781f98296f0af2488ff06202f12ee92b0175963b8dba688d1b40',
tx_pos: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result)
assert.equal(result, true)
})
it('should return true for valid UTXO with fullnode properties', async () => {
const utxo = {
txid: '17754221b29f189532d4fc2ae89fb467ad2dede30fdec4854eb2129b3ba90d7a',
vout: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result)
assert.equal(result, false)
})
it('should return true for valid UTXO with fulcrum properties', async () => {
const utxo = {
tx_hash: '17754221b29f189532d4fc2ae89fb467ad2dede30fdec4854eb2129b3ba90d7a',
tx_pos: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result
assert.equal(result, false)
})
it('should process output of Utxo.get()', async () => {
const utxo = await bchjs.Utxo.get('bitcoincash:qr4yscpw9jgq8ltajfeknpj32kamkf9knujffcdhyq')
// console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
const result = await bchjs.Utxo.isValid(utxo.bchUtxos[0])
assert.equal(result, true)
})
})
})
+40
View File
@@ -935,4 +935,44 @@ describe('#address.js', () => {
})
})
})
describe('#toEcashAddress', () => {
it('should convert a BCH address to an eCash address', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEcashAddress(cashAddr)
// console.log('result: ', result)
assert.equal(result, 'ecash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s8f6wu02p')
})
it('should convert a BCH address to an eCash address without a prefix', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEcashAddress(cashAddr, false)
// console.log('result: ', result)
assert.equal(result, 'qr24z7q6s26d9wr078lr2pxsmxg22cyn9s8f6wu02p')
})
})
describe('#toEtokenAddress', () => {
it('should convert a BCH address to an eToken address', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEtokenAddress(cashAddr)
// console.log('result: ', result)
assert.equal(result, 'etoken:qr24z7q6s26d9wr078lr2pxsmxg22cyn9sfhnv2gwk')
})
it('should convert a BCH address to an eToken address without a prefix', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEtokenAddress(cashAddr, false)
// console.log('result: ', result)
assert.equal(result, 'qr24z7q6s26d9wr078lr2pxsmxg22cyn9sfhnv2gwk')
})
})
})
+8 -1
View File
@@ -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
}
+75
View File
@@ -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)
}
})
})
})
+32
View File
@@ -174,4 +174,36 @@ describe('#utxo', () => {
assert.equal(result.nullUtxos.length, 0)
})
})
describe('#isValid', () => {
it('should return false if getTxOut() returns null', async () => {
// Mock dependencies
sandbox.stub(bchjs.Utxo.blockchain, 'getTxOut').resolves(null)
const utxo = {
tx_hash: '17754221b29f189532d4fc2ae89fb467ad2dede30fdec4854eb2129b3ba90d7a',
tx_pos: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result
assert.equal(result, false)
})
it('should return true if getTxOut() returns non-null output', async () => {
// Mock dependencies
sandbox.stub(bchjs.Utxo.blockchain, 'getTxOut').resolves({ a: 'b' })
const utxo = {
tx_hash: 'b94e1ff82eb5781f98296f0af2488ff06202f12ee92b0175963b8dba688d1b40',
tx_pos: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result
assert.equal(result, true)
})
})
})