@exodus/bitcoin-plugin 1.0.16 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-plugin",
3
- "version": "1.0.16",
3
+ "version": "1.3.0",
4
4
  "description": "Exodus bitcoin-plugin",
5
5
  "main": "src/index.js",
6
6
  "files": [
@@ -19,12 +19,12 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@exodus/asset-lib": "^3.7.1",
22
- "@exodus/bitcoin-api": "^2.3.16",
22
+ "@exodus/bitcoin-api": "^2.4.0",
23
23
  "@exodus/bitcoin-lib": "^2.2.8",
24
24
  "minimalistic-assert": "^1.0.1"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@exodus/keychain": "^3.0.0"
28
28
  },
29
- "gitHead": "ea21eb60e35f84cf2086ae0304bf9fa8ce4058b1"
29
+ "gitHead": "de21cbd727cb6cbe4fac07b58cc6e3fa8af318ff"
30
30
  }
@@ -23,14 +23,23 @@ import {
23
23
  import { bitcoinFeeDataFactory } from './fee-data'
24
24
  import BitcoinFeeMonitor from './fee-monitor'
25
25
  import assert from 'minimalistic-assert'
26
+ import { DEFAULT_ORDINAL_CHAIN_INDEX } from './ordinals/ordinals-constants'
27
+ import { nftsApiFactory } from './ordinals/nfts'
26
28
 
27
29
  export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) => ({
28
30
  allowUnconfirmedRbfEnabledUtxos = false,
31
+ ordinalChainIndex = DEFAULT_ORDINAL_CHAIN_INDEX,
32
+ ordinalsEnabled = false,
33
+ brc20Enabled = false,
29
34
  overrideCallback = ({ asset }) => asset,
30
35
  } = {}) => {
31
36
  assert(asset, 'asset is required')
37
+ assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
32
38
  assert(apiUrl, 'apiUrl is required')
33
-
39
+ assert(
40
+ brc20Enabled ? ordinalsEnabled : true,
41
+ 'if brc20Enabled is true then ordinalsEnabled must be true'
42
+ )
34
43
  const coinInfo = _coinInfo(coinInfoNetwork || asset.name)
35
44
 
36
45
  const insightClient = new InsightAPIClient(apiUrl)
@@ -61,6 +70,7 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
61
70
  feesApi: true,
62
71
  moveFunds: true,
63
72
  multipleAddresses: true,
73
+ nfts: ordinalsEnabled,
64
74
  }
65
75
 
66
76
  const getFeeEstimator = getFeeEstimatorFactory({
@@ -103,7 +113,24 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
103
113
 
104
114
  const getBalances = getBalancesFactory({ feeData, getSpendableBalance })
105
115
 
106
- const accountStateClass = createAccountState({ asset })
116
+ const accountStateClass = createAccountState({ asset: asset, ordinalsEnabled, brc20Enabled })
117
+
118
+ const nfts = ordinalsEnabled ? nftsApiFactory({ ordinalChainIndex, asset }) : undefined
119
+
120
+ const createHistoryMonitor = (args) => {
121
+ const monitor = createBitcoinMonitor({
122
+ insightClient,
123
+ ordinalsEnabled,
124
+ ordinalChainIndex,
125
+ apiUrl,
126
+ ...args,
127
+ })
128
+ const assetClientInterface = args.assetClientInterface
129
+ if (ordinalsEnabled) {
130
+ nfts.initialize({ assetClientInterface })
131
+ }
132
+ return monitor
133
+ }
107
134
 
108
135
  const addressHasHistory = async (address) => {
109
136
  assert(typeof address === 'string', 'Address is required')
@@ -111,13 +138,24 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
111
138
  return !!result?.items.length
112
139
  }
113
140
 
141
+ const txLogFilter = (tx) => {
142
+ const isDroppedBitcoinTx = tx.dropped
143
+ const isWaitingRbf = tx.data && tx.data.replacedBy && tx.pending
144
+ return !isDroppedBitcoinTx && !isWaitingRbf
145
+ }
146
+
147
+ const getTxLogFilter = () => {
148
+ return txLogFilter
149
+ }
150
+
114
151
  const api = {
152
+ getTxLogFilter,
115
153
  addressHasHistory,
116
154
  defaultAddressPath: 'm/0/0',
117
155
  broadcastTx: (...args) => insightClient.broadcastTx(...args),
118
156
  createFeeMonitor: (args) =>
119
157
  new BitcoinFeeMonitor({ ...args, insight: () => insightClient, assetName: asset.name }),
120
- createHistoryMonitor: (args) => createBitcoinMonitor({ insightClient, apiUrl, ...args }),
158
+ createHistoryMonitor,
121
159
  features,
122
160
  getFeeData: () => feeData,
123
161
  getBalances,
@@ -135,6 +173,7 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
135
173
  signTx,
136
174
  getFee,
137
175
  moveFunds,
176
+ nfts,
138
177
  }
139
178
 
140
179
  const fullAsset = {
@@ -0,0 +1,95 @@
1
+ import assert from 'minimalistic-assert'
2
+ import { fetchival } from '@exodus/fetch'
3
+ import ms from 'ms'
4
+
5
+ const HTTP_POST_TIMEOUT = ms('30s')
6
+ const DEFAULT_ORDINALS_API_KEY = undefined // ME's api key is included in proxy call
7
+ const DEFAULT_BRC_20_URL = 'https://api-mainnet-magiceden.exodus.io/'
8
+
9
+ async function improveErrorMessage(err) {
10
+ if (err.response) {
11
+ try {
12
+ const responseText = await err.response.text()
13
+ if (responseText)
14
+ return Promise.reject(new Error(`${err.message}. Error: ${responseText.slice(0, 200)}`)) // trying to get error more info from body)
15
+ } catch (e) {}
16
+ }
17
+ return Promise.reject(new Error(err.message))
18
+ }
19
+
20
+ export const brc20ApiClientFactory = ({
21
+ brc20Url = DEFAULT_BRC_20_URL,
22
+ ordinalsApiKey = DEFAULT_ORDINALS_API_KEY,
23
+ } = {}) => {
24
+ let baseUrl = brc20Url
25
+
26
+ const setUrl = (newBaseUrl) => {
27
+ baseUrl = newBaseUrl || DEFAULT_BRC_20_URL
28
+ }
29
+
30
+ const request = (path, queryParams) => {
31
+ const headers = {
32
+ Accept: 'application/json',
33
+ 'Content-Type': 'application/json',
34
+ }
35
+ if (ordinalsApiKey) headers.Authorization = `Bearer ${ordinalsApiKey}`
36
+
37
+ return fetchival(baseUrl + path, { headers, timeout: HTTP_POST_TIMEOUT })
38
+ .get(queryParams)
39
+ .catch(improveErrorMessage)
40
+ }
41
+
42
+ const getOwnerTickBalances = async ({ address }) => {
43
+ assert(address, 'address is required')
44
+ return request(`/v2/ord/btc/brc20/owner_balances/${encodeURIComponent(address)}`)
45
+ }
46
+
47
+ const getTickerInfo = async ({ tick }) => {
48
+ assert(tick, 'tick is required')
49
+ return request(`/v2/ord/btc/brc20/tick_infos/${encodeURIComponent(tick)}`)
50
+ }
51
+
52
+ const removeNullUndefined = (obj) =>
53
+ Object.fromEntries(Object.entries(obj).filter(([_, v]) => v !== undefined))
54
+
55
+ const paginatedTransactionHistory = async (queryParams) => {
56
+ const resolvedQueryParams = removeNullUndefined(queryParams)
57
+ const events = []
58
+ const limit = queryParams.limit || 40
59
+ let offset = queryParams.offset || 0
60
+ let response
61
+ do {
62
+ response = await request('/v2/ord/btc/brc20/events', {
63
+ ...resolvedQueryParams,
64
+ limit,
65
+ offset,
66
+ })
67
+ offset = offset + limit
68
+ events.push(...response.events)
69
+ } while (offset < response.total)
70
+
71
+ return events
72
+ }
73
+
74
+ const getTokenTransactionHistory = ({
75
+ tick,
76
+ owner,
77
+ brc20Op,
78
+ showInvalid,
79
+ transactionIds,
80
+ limit,
81
+ offset,
82
+ }) => {
83
+ return paginatedTransactionHistory({
84
+ tick,
85
+ owner,
86
+ brc20Op,
87
+ showInvalid,
88
+ transactionIds,
89
+ limit,
90
+ offset,
91
+ })
92
+ }
93
+
94
+ return { setUrl, getOwnerTickBalances, getTickerInfo, getTokenTransactionHistory }
95
+ }
@@ -0,0 +1,42 @@
1
+ import assert from 'minimalistic-assert'
2
+
3
+ export const getInscriptionAddresses = async ({
4
+ assetClientInterface: aci,
5
+ walletAccount: walletAccountInstance,
6
+ asset,
7
+ ordinalChainIndex,
8
+ }) => {
9
+ assert(aci, 'assetClientInterface is required')
10
+ assert(asset, 'asset is required')
11
+ assert(walletAccountInstance, 'walletAccount is required')
12
+ assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
13
+
14
+ const assetName = asset.name
15
+ const walletAccount = walletAccountInstance.toString()
16
+ const accountState = await aci.getAccountState({ walletAccount, assetName })
17
+
18
+ // all the known utxos addresses are monitored,
19
+ // just in case the user received it to a standard btc address
20
+ const allUtxos = accountState.ordinalsUtxos.union(accountState.utxos)
21
+ const addresses = allUtxos.toArray().map((utxos) => utxos.address)
22
+ const specialAddress1 = await aci.getAddress({
23
+ assetName,
24
+ walletAccount,
25
+ purpose: 86,
26
+ chainIndex: ordinalChainIndex,
27
+ addressIndex: 0,
28
+ })
29
+
30
+ const specialAddress2 = await aci.getAddress({
31
+ assetName,
32
+ walletAccount,
33
+ purpose: 86,
34
+ chainIndex: 0,
35
+ addressIndex: 0,
36
+ })
37
+
38
+ const allAddresses = [specialAddress1, specialAddress2, ...addresses].map((t) =>
39
+ t.address.toString()
40
+ )
41
+ return [...new Set(allAddresses)]
42
+ }
@@ -0,0 +1,65 @@
1
+ import assert from 'minimalistic-assert'
2
+ import { getInscriptionAddresses } from './get-inscription-addresses'
3
+ import { updateAccountStateUtxos } from './ordinals-account-state-utils'
4
+
5
+ export const nftsApiFactory = ({ ordinalChainIndex, asset }) => {
6
+ assert(asset, 'asset is required')
7
+ assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
8
+ let aci // convert to constructor argument when wallet send aci at createAsset time
9
+ return {
10
+ initialize: ({ assetClientInterface }) => {
11
+ aci = assetClientInterface
12
+ },
13
+
14
+ // this extension returns all possible addresses that may contain nfts
15
+ getNftsAddresses: async ({ walletAccount: walletAccountInstance }) => {
16
+ if (!aci) {
17
+ console.warn('bitcoin nfts not initialized yet')
18
+ return []
19
+ }
20
+ return getInscriptionAddresses({
21
+ assetClientInterface: aci,
22
+ walletAccount: walletAccountInstance.toString(),
23
+ ordinalChainIndex,
24
+ asset,
25
+ })
26
+ },
27
+
28
+ /*
29
+ This extension performs 2 operations.
30
+ 1. It updates the utxo.data.inscriptionId if there is a nft found via the monitor
31
+ 2. It removes nfts that are in transit, monitor still founds them even when the utxos doesn't exist (it was spent)
32
+ */
33
+ postProcessNfts: async ({ nfts, walletAccount: walletAccountInstance }) => {
34
+ if (!aci) {
35
+ console.warn('bitcoin nfts not initialized yet')
36
+ return []
37
+ }
38
+
39
+ const outputToInscriptionId = Object.fromEntries(nfts.map((nft) => [nft.output, nft.tokenId]))
40
+
41
+ const { allUpdatedUtxos } = await updateAccountStateUtxos({
42
+ asset,
43
+ walletAccount: walletAccountInstance.toString(),
44
+ assetClientInterface: aci,
45
+ outputToInscriptionId,
46
+ ordinalChainIndex,
47
+ })
48
+ const utxosOutputs = allUpdatedUtxos
49
+ .toArray()
50
+ .map((utxo) => {
51
+ return `${utxo.txId}:${utxo.vout}`.toLowerCase()
52
+ })
53
+ .filter(Boolean)
54
+
55
+ const filteredNfts = nfts.filter((nft) => utxosOutputs.includes(nft.output.toLowerCase()))
56
+ if (filteredNfts.length !== nfts.length) {
57
+ console.log(
58
+ 'Ordinal NFTs in transit',
59
+ nfts.filter((nft) => !utxosOutputs.includes(nft.output.toLowerCase()))
60
+ )
61
+ }
62
+ return filteredNfts
63
+ },
64
+ }
65
+ }
@@ -0,0 +1,55 @@
1
+ import { getOrdinalsUtxos, getUtxos, partitionUtxos } from '@exodus/bitcoin-api'
2
+ import { UtxoCollection } from '@exodus/models'
3
+ import { isEmpty, pickBy } from 'lodash'
4
+ import { getOwnProperty } from '@exodus/basic-utils'
5
+
6
+ export const updateAccountStateUtxos = async ({
7
+ asset,
8
+ walletAccount,
9
+ assetClientInterface: aci,
10
+ outputToInscriptionId,
11
+ ordinalChainIndex,
12
+ moreNewData = {},
13
+ }) => {
14
+ const assetName = asset.name
15
+ const accountState = await aci.getAccountState({ assetName, walletAccount })
16
+ const storedUtxos = getUtxos({ accountState, asset })
17
+ const storedOrdinalsUtxos = getOrdinalsUtxos({ accountState, asset })
18
+
19
+ const allStoredUtxos = storedUtxos.union(storedOrdinalsUtxos)
20
+ const allUpdatedUtxos = UtxoCollection.fromArray(
21
+ allStoredUtxos.toArray().map((utxo) => {
22
+ const inscriptionId = getOwnProperty(
23
+ outputToInscriptionId,
24
+ `${utxo.txId}:${utxo.vout}`.toLowerCase()
25
+ )
26
+ if (inscriptionId) {
27
+ return { ...utxo, inscriptionId }
28
+ }
29
+ return utxo
30
+ }),
31
+ {
32
+ currency: asset.currency,
33
+ }
34
+ )
35
+
36
+ if (!allUpdatedUtxos.equals(allStoredUtxos) || !isEmpty(moreNewData)) {
37
+ const { utxos, ordinalsUtxos } = partitionUtxos({
38
+ allUtxos: allUpdatedUtxos,
39
+ ordinalChainIndex: ordinalChainIndex,
40
+ })
41
+ const utxosData = pickBy(
42
+ {
43
+ utxos,
44
+ ordinalsUtxos,
45
+ },
46
+ Boolean
47
+ )
48
+ await aci.updateAccountState({
49
+ assetName,
50
+ walletAccount,
51
+ newData: { ...utxosData, ...moreNewData },
52
+ })
53
+ }
54
+ return { allUpdatedUtxos }
55
+ }
@@ -0,0 +1,4 @@
1
+ // What's the taproot chain index to use as the default ordinal address (as in purpose 86, m/2/0).
2
+ // Note that it's recommended for exodus wallets to not use 0 as it can hold regular btc (as in purpose 86, m/0/0).
3
+ // If a user syncs an ordinal Wallet (BE) with a non-ordinal Wallet (old Desktop), the non-ordinal wallet may burn ordinals as regular BTC
4
+ export const DEFAULT_ORDINAL_CHAIN_INDEX = 2