@exodus/bitcoin-plugin 1.5.0 → 1.5.1

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.5.0",
3
+ "version": "1.5.1",
4
4
  "description": "Exodus bitcoin-plugin",
5
5
  "main": "src/index.js",
6
6
  "files": [
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@exodus/asset-lib": "^3.7.1",
22
- "@exodus/bitcoin-api": "^2.5.0",
22
+ "@exodus/bitcoin-api": "^2.5.1",
23
23
  "@exodus/bitcoin-lib": "^2.2.8",
24
24
  "bitcoinjs-lib": "^6.1.5",
25
25
  "minimalistic-assert": "^1.0.1"
@@ -27,5 +27,5 @@
27
27
  "devDependencies": {
28
28
  "@exodus/keychain": "^3.0.0"
29
29
  },
30
- "gitHead": "d7b87308c1645a96ba4451f0b40b08ae3c1c29e5"
30
+ "gitHead": "562c288cde1c1d7c7ab2c7bc6b1804ccca9b37f2"
31
31
  }
@@ -30,6 +30,7 @@ import { nftsApiFactory } from './ordinals/nfts'
30
30
  import { brc20BalancesAndFeeAdapterFactory } from './ordinals/brc-20-balances-and-fee-adapter'
31
31
  import { parseCurrency } from '@exodus/bitcoin-api/src/fee/fee-utils'
32
32
  import { inscriptionsServiceFactory } from './ordinals/inscriptions-service'
33
+ import { tickInscriptionIdIndexerFactory } from './ordinals/tick-inscription-id-indexer'
33
34
 
34
35
  export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) => ({
35
36
  allowUnconfirmedRbfEnabledUtxos = false,
@@ -93,6 +94,11 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
93
94
  getSpendableBalance: baseFeeResolver.getSpendableBalance,
94
95
  })
95
96
 
97
+ const brc20Client = brc20Enabled ? brc20ApiClientFactory() : undefined
98
+ const tickInscriptionIdIndexer = brc20Enabled
99
+ ? tickInscriptionIdIndexerFactory({ brc20Client })
100
+ : undefined
101
+
96
102
  const baseSendTx = createAndBroadcastTXFactory({
97
103
  getFeeEstimator,
98
104
  allowUnconfirmedRbfEnabledUtxos,
@@ -118,6 +124,7 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
118
124
  ...baseFeeResolver,
119
125
  getBalances: baseGetBalances,
120
126
  sendTx: baseSendTx,
127
+ tickInscriptionIdIndexer,
121
128
  })
122
129
  : { ...baseFeeResolver, getBalances: baseGetBalances, sendTx: baseSendTx }
123
130
 
@@ -161,8 +168,8 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
161
168
  if (ordinalsEnabled) {
162
169
  nfts.initialize({ assetClientInterface })
163
170
  }
171
+
164
172
  if (brc20Enabled) {
165
- const brc20Client = brc20ApiClientFactory()
166
173
  monitor.addHook('after-tick', async ({ walletAccount }) => {
167
174
  const { unknownDeployInscriptionIds } = await reloadBrc20TokenBalances({
168
175
  walletAccount,
@@ -170,6 +177,7 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
170
177
  ordinalChainIndex,
171
178
  brc20Client,
172
179
  assetClientInterface,
180
+ tickInscriptionIdIndexer,
173
181
  })
174
182
  if (unknownDeployInscriptionIds.length) {
175
183
  monitor.emit('unknown-tokens', unknownDeployInscriptionIds)
@@ -1,6 +1,7 @@
1
1
  import assert from 'minimalistic-assert'
2
2
  import { BumpType } from '@exodus/bitcoin-lib/lib/selectors/get-can-bump-tx-factory'
3
3
  import { brc20Utils } from './brc-20-utils'
4
+ import { createBrc20Command } from './create-brc-20-command'
4
5
 
5
6
  export const brc20BalancesAndFeeAdapterFactory = ({
6
7
  inscriptionsService,
@@ -10,6 +11,7 @@ export const brc20BalancesAndFeeAdapterFactory = ({
10
11
  canBumpTx,
11
12
  getSpendableBalance,
12
13
  sendTx,
14
+ tickInscriptionIdIndexer,
13
15
  }) => {
14
16
  assert(inscriptionsService, 'inscriptionsService is required')
15
17
  assert(getBalances, 'getBalances is required')
@@ -18,6 +20,7 @@ export const brc20BalancesAndFeeAdapterFactory = ({
18
20
  assert(canBumpTx, 'canBumpTx is required')
19
21
  assert(getSpendableBalance, 'getSpendableBalance is required')
20
22
  assert(sendTx, 'sendTx is required')
23
+ assert(tickInscriptionIdIndexer, 'unknownDeployInscriptionIds is required')
21
24
 
22
25
  const { isToken, getTokenBalance } = brc20Utils
23
26
 
@@ -32,22 +35,65 @@ export const brc20BalancesAndFeeAdapterFactory = ({
32
35
  const { broadcastInscription, createBrc20Inscription } = inscriptionsService
33
36
 
34
37
  const asset = token.baseAsset
35
- const inscription = createBrc20Inscription({
36
- op: 'transfer',
37
- tick: token.assetName.split('_')[0], // FIX ME, use the brc20tick on assets properties!!
38
- amt: amount.toDefaultString({ unit: false }),
38
+ const accountState = await assetClientInterface.getAccountState({
39
+ walletAccount,
40
+ assetName: asset.name,
39
41
  })
40
42
 
41
- const customFee = asset.currency.baseUnit(20000) // why 64k is te default?
43
+ const tick = await tickInscriptionIdIndexer.getBrc20TickFromAsset(token)
42
44
 
43
- return broadcastInscription({
44
- asset,
45
- assetClientInterface,
46
- walletAccount,
47
- receiverWalletAccount: walletAccount,
48
- inscription,
49
- customFee,
45
+ const tokenAmount = options.isSendAll ? getTokenBalance({ asset: token, accountState }) : amount
46
+
47
+ if (tokenAmount.lte(token.currency.ZERO)) {
48
+ throw new Error(
49
+ `Cannot send ${tokenAmount.toDefaultString({ unit: true })} amount for asset :${
50
+ token.name
51
+ }. Tick: ${tick}`
52
+ )
53
+ }
54
+
55
+ const brc20Command = createBrc20Command({
56
+ asset: token,
57
+ amount: tokenAmount,
58
+ accountState,
50
59
  })
60
+
61
+ const inscriptionIds = brc20Command.inscriptionIds
62
+
63
+ for (const newInscription of brc20Command.newInscriptions) {
64
+ const customFee = asset.currency.baseUnit(20000) // why 64k is te default?
65
+ const inscription = await createBrc20Inscription({
66
+ op: 'transfer',
67
+ tick,
68
+ amt: newInscription.amount.toDefaultString({ unit: false }),
69
+ })
70
+
71
+ const inscriptionResult = await broadcastInscription({
72
+ asset,
73
+ assetClientInterface,
74
+ walletAccount,
75
+ receiverWalletAccount: walletAccount,
76
+ inscription,
77
+ customFee,
78
+ })
79
+
80
+ inscriptionIds.push(inscriptionResult.inscriptionId)
81
+ }
82
+
83
+ return sendTx(
84
+ {
85
+ asset: token,
86
+ walletAccount,
87
+ address,
88
+ amount: tokenAmount,
89
+ options: {
90
+ ...options,
91
+ isRbfAllowed: false,
92
+ brc20: { inscriptionIds },
93
+ },
94
+ },
95
+ { assetClientInterface }
96
+ )
51
97
  }
52
98
 
53
99
  return {
@@ -76,4 +76,43 @@ export const brc20Utils = {
76
76
  .sub(brc20Utils.getInTransitBalance({ asset, accountState }))
77
77
  .clampLowerZero()
78
78
  },
79
+
80
+ getAllSublists(transferableList) {
81
+ const result = []
82
+
83
+ const generateSublists = (sublist, index) => {
84
+ if (index === transferableList.length) {
85
+ result.push(sublist)
86
+ return
87
+ }
88
+
89
+ // Include the current element in the sublist
90
+ generateSublists([...sublist, transferableList[index]], index + 1)
91
+
92
+ // Exclude the current element from the sublist
93
+ generateSublists(sublist, index + 1)
94
+ }
95
+
96
+ generateSublists([], 0)
97
+ return result
98
+ },
99
+
100
+ findTransferableItems({ transferableList, amount, currency }) {
101
+ const sublists = brc20Utils
102
+ .getAllSublists(transferableList)
103
+ .map((transferableItems) => {
104
+ const transferableItemsAmount = transferableItems.reduce(
105
+ (acc, item) => acc.add(item.amount),
106
+ currency.ZERO
107
+ )
108
+ return { transferableItemsAmount, transferableItems }
109
+ })
110
+ .filter((item) => item.transferableItemsAmount.lte(amount))
111
+ const found = sublists.find((item) => item.transferableItemsAmount.equals(amount))
112
+ if (found) {
113
+ return found
114
+ }
115
+
116
+ return sublists.sort((a, b) => b.transferableItems.length - a.transferableItems.length)[0]
117
+ },
79
118
  }
@@ -0,0 +1,50 @@
1
+ import assert from 'minimalistic-assert'
2
+ import { brc20Utils } from './brc-20-utils'
3
+
4
+ export const createBrc20Command = ({ asset, amount, accountState }) => {
5
+ assert(asset.name !== asset.baseAsset.name, `${asset.name} should be a token!`)
6
+
7
+ const brc20BalanceMultipleAddresses = accountState?.brc20Balances?.[asset.name] || {}
8
+ const balance = brc20Utils.getTokenBalance({ asset, accountState })
9
+ const transferableList = brc20Utils.getTransferableList({ asset, accountState })
10
+ assert(
11
+ balance.gte(amount),
12
+ `Not enough ${asset.name} balance. Wanted ${amount.toDefaultString({
13
+ unit: true,
14
+ })}, but got ${balance.toDefaultString({ unit: true })}`
15
+ )
16
+
17
+ const transferableItemsResult = brc20Utils.findTransferableItems({
18
+ transferableList,
19
+ amount,
20
+ currency: asset.currency,
21
+ })
22
+ const brc20 = {
23
+ inscriptionIds: transferableItemsResult.transferableItems.map((i) => i.inscriptionId),
24
+ }
25
+
26
+ let requireInscriptionAmount = amount.sub(transferableItemsResult.transferableItemsAmount)
27
+
28
+ brc20.newInscriptions = Object.entries(brc20BalanceMultipleAddresses)
29
+ .map(([address, assetBalance]) => {
30
+ const availableBalance = asset.currency.defaultUnit(assetBalance.brc20OwnerAvailableBalance)
31
+ const amount = requireInscriptionAmount.gt(availableBalance)
32
+ ? availableBalance
33
+ : requireInscriptionAmount
34
+ requireInscriptionAmount = requireInscriptionAmount.sub(amount)
35
+ return {
36
+ amount,
37
+ address,
38
+ }
39
+ })
40
+ .filter((i) => i.amount.gt(asset.currency.ZERO))
41
+
42
+ assert(
43
+ balance.gte(amount),
44
+ `Not enough ${asset.name} balance. Wanted ${amount.toDefaultString({
45
+ unit: true,
46
+ })}, but got ${balance.toDefaultString({ unit: true })}`
47
+ )
48
+
49
+ return brc20
50
+ }
@@ -8,7 +8,7 @@ import { DEFAULT_BRC20_POSTAGE, DEFAULT_ORDINAL_POSTAGE } from './ordinals-const
8
8
 
9
9
  import { witnessStackToScriptWitness } from 'bitcoinjs-lib/src/psbt/psbtutils'
10
10
  import getTxSequence from '@exodus/bitcoin-lib/lib/utils/get-tx-sequence'
11
- import { toXOnly, toAsyncSigner, eccFactory } from '@exodus/bitcoin-api'
11
+ import { toXOnly, toAsyncSigner, eccFactory, getOrdinalsUtxos } from '@exodus/bitcoin-api'
12
12
 
13
13
  const encoder = new TextEncoder()
14
14
  export function createInscriptionScript({ xOnlyPublicKey, inscription }) {
@@ -137,7 +137,7 @@ export const inscriptionsServiceFactory = ({ network, ordinalChainIndex }) => {
137
137
 
138
138
  psbt.addOutput({
139
139
  value: amount, // generally 1000 for nfts, 549 for brc20
140
- address: toAddress,
140
+ address: toAddress.toString(),
141
141
  })
142
142
 
143
143
  await psbt.signInputAsync(0, toAsyncSigner({ keyPair: keypair, ecc }))
@@ -164,20 +164,27 @@ export const inscriptionsServiceFactory = ({ network, ordinalChainIndex }) => {
164
164
 
165
165
  const virtualSize = tx.virtualSize()
166
166
 
167
+ const vout = 0
168
+ const script = tx.outs[vout].script.toString('hex')
169
+ const inscriptionId = `${txId}i0`
170
+
167
171
  return {
168
172
  txId,
169
173
  rawTx,
170
- inscriptionId: `${txId}i0`,
174
+ inscriptionId,
171
175
  signature,
172
176
  virtualSize,
177
+ vout,
178
+ script,
179
+ value: amount,
173
180
  }
174
181
  }
175
182
 
176
183
  const broadcastInscription = async ({
177
184
  asset,
178
- walletAccount,
179
- receiverWalletAccount,
180
- receiverAddress,
185
+ walletAccount, // The portfolio that spends the fees when creating the inscription. Also, the portfolio that receives the inscription if the 2 belows are not provided
186
+ receiverWalletAccount, // Optional: send the inscription to a different portfolio
187
+ receiverAddress, // Optional: send the inscription to a third party wallet
181
188
  assetClientInterface,
182
189
  inscription,
183
190
  privateKey = randomBytes(32),
@@ -190,17 +197,17 @@ export const inscriptionsServiceFactory = ({ network, ordinalChainIndex }) => {
190
197
 
191
198
  const assetName = asset.name
192
199
 
200
+ const resolvedReceiverWalletAccount = receiverWalletAccount || walletAccount
201
+
193
202
  const toAddress =
194
203
  receiverAddress ||
195
- (
196
- await assetClientInterface.getAddress({
197
- assetName,
198
- walletAccount: receiverWalletAccount || walletAccount,
199
- purpose: 86,
200
- chainIndex: ordinalChainIndex,
201
- addressIndex: 0,
202
- })
203
- ).toString()
204
+ (await assetClientInterface.getAddress({
205
+ assetName,
206
+ walletAccount: resolvedReceiverWalletAccount,
207
+ purpose: 86,
208
+ chainIndex: ordinalChainIndex,
209
+ addressIndex: 0,
210
+ }))
204
211
 
205
212
  const postage = inscription.postage
206
213
 
@@ -247,6 +254,30 @@ export const inscriptionsServiceFactory = ({ network, ordinalChainIndex }) => {
247
254
  privateKey,
248
255
  })
249
256
 
257
+ if (!receiverAddress && resolvedReceiverWalletAccount) {
258
+ const accountState = await assetClientInterface.getAccountState({
259
+ assetName,
260
+ walletAccount: resolvedReceiverWalletAccount,
261
+ })
262
+ // only add the utxo
263
+ const ordinalsUtxos = getOrdinalsUtxos({ accountState, asset }).addUtxo({
264
+ txId: revealTx.txId,
265
+ address: toAddress,
266
+ vout: revealTx.vout,
267
+ script: revealTx.script,
268
+ value: asset.currency.baseUnit(revealTx.value),
269
+ confirmations: 0,
270
+ inscriptionId: revealTx.inscriptionId,
271
+ rbfEnabled: false,
272
+ })
273
+
274
+ await assetClientInterface.updateAccountState({
275
+ assetName,
276
+ walletAccount: resolvedReceiverWalletAccount,
277
+ newData: { ordinalsUtxos },
278
+ })
279
+ }
280
+
250
281
  await asset.api.broadcastTx(revealTx.rawTx)
251
282
  return { ...revealTx, ...commitTxData }
252
283
  }
@@ -1,4 +1,4 @@
1
- import { getOrdinalsUtxos, getUtxos, partitionUtxos } from '@exodus/bitcoin-api'
1
+ import { getOrdinalsUtxos, getUtxos, partitionUtxos, getOrdinalAddress } from '@exodus/bitcoin-api'
2
2
  import { UtxoCollection } from '@exodus/models'
3
3
  import { isEmpty, pickBy } from 'lodash'
4
4
  import { getOwnProperty } from '@exodus/basic-utils'
@@ -33,10 +33,17 @@ export const updateAccountStateUtxos = async ({
33
33
  }
34
34
  )
35
35
 
36
+ const ordinalAddress = await getOrdinalAddress({
37
+ asset,
38
+ assetClientInterface: aci,
39
+ walletAccount,
40
+ ordinalChainIndex,
41
+ })
42
+
36
43
  if (!allUpdatedUtxos.equals(allStoredUtxos) || !isEmpty(moreNewData)) {
37
44
  const { utxos, ordinalsUtxos } = partitionUtxos({
38
45
  allUtxos: allUpdatedUtxos,
39
- ordinalChainIndex: ordinalChainIndex,
46
+ ordinalAddress,
40
47
  })
41
48
  const utxosData = pickBy(
42
49
  {
@@ -2,7 +2,6 @@ import assert from 'minimalistic-assert'
2
2
  import { getInscriptionAddresses } from './get-inscription-addresses'
3
3
  import { groupBy, mapValues } from 'lodash'
4
4
  import { updateAccountStateUtxos } from './ordinals-account-state-utils'
5
- import { memoizeLruCache } from '@exodus/asset-lib'
6
5
  const toTxLog = ({ historyItem, baseAsset, asset }) => {
7
6
  const amount = asset.currency.defaultUnit(historyItem.brc20Amt || 0)
8
7
 
@@ -42,11 +41,13 @@ export const reloadBrc20TokenBalances = async ({
42
41
  walletAccount,
43
42
  asset,
44
43
  ordinalChainIndex,
44
+ tickInscriptionIdIndexer,
45
45
  }) => {
46
46
  assert(brc20Client, 'brc20Client is required')
47
47
  assert(assetClientInterface, 'assetClientInterface is required')
48
48
  assert(asset, 'asset is required')
49
49
  assert(walletAccount, 'walletAccount is required')
50
+ assert(tickInscriptionIdIndexer, 'tickInscriptionIdIndexer is required')
50
51
  assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
51
52
  const addresses = await getInscriptionAddresses({
52
53
  assetClientInterface,
@@ -55,15 +56,6 @@ export const reloadBrc20TokenBalances = async ({
55
56
  ordinalChainIndex,
56
57
  })
57
58
 
58
- const toDeployInscriptionId = memoizeLruCache(
59
- async (tick) => {
60
- const response = await brc20Client.getTickerInfo({ tick })
61
- return response[0].inscriptionId.toLowerCase()
62
- },
63
- (tick) => tick,
64
- 200
65
- )
66
-
67
59
  const assets = await assetClientInterface.getAssetsForNetwork({ baseAssetName: asset.name })
68
60
 
69
61
  const assetByAssetId = Object.values(assets)
@@ -83,7 +75,9 @@ export const reloadBrc20TokenBalances = async ({
83
75
  return (
84
76
  await Promise.all(
85
77
  tokensHistoryList.map(async (token) => {
86
- const deployInscriptionId = await toDeployInscriptionId(token.brc20Tick)
78
+ const deployInscriptionId = await tickInscriptionIdIndexer.getDeployInscriptionId(
79
+ token.brc20Tick
80
+ )
87
81
  knownInscriptionIds.add(deployInscriptionId)
88
82
  knownInscriptionIds.add(token.inscriptionId.toLowerCase())
89
83
  const assetName = assetByAssetId.get(deployInscriptionId)?.name
@@ -0,0 +1,48 @@
1
+ import assert from 'minimalistic-assert'
2
+
3
+ export const tickInscriptionIdIndexerFactory = ({ brc20Client }) => {
4
+ const deployInscriptionIdToBrc20Tick = new Map()
5
+ const brc20TickToDeployInscriptionId = new Map()
6
+
7
+ const save = ({ deployInscriptionId, brc20Tick }) => {
8
+ deployInscriptionIdToBrc20Tick.set(deployInscriptionId, brc20Tick)
9
+ brc20TickToDeployInscriptionId.set(brc20Tick, deployInscriptionId)
10
+ }
11
+
12
+ const loadDeployInscriptionId = async (brc20Tick) => {
13
+ const response = await brc20Client.getTickerInfo({ tick: brc20Tick })
14
+ const deployInscriptionId = response[0].inscriptionId
15
+ save({ deployInscriptionId, brc20Tick })
16
+ return deployInscriptionId
17
+ }
18
+
19
+ const loadBrc20Tick = async (deployInscriptionId) => {
20
+ const response = await brc20Client.getTickerInfoByDeployInscriptionId({ deployInscriptionId })
21
+ const brc20Tick = response[0].brc20Tick
22
+ save({ deployInscriptionId, brc20Tick })
23
+ return brc20Tick
24
+ }
25
+
26
+ const getDeployInscriptionId = async (brc20Tick) => {
27
+ return brc20TickToDeployInscriptionId.get(brc20Tick) || loadDeployInscriptionId(brc20Tick)
28
+ }
29
+
30
+ const getBrc20Tick = async (deployInscriptionId) => {
31
+ return (
32
+ deployInscriptionIdToBrc20Tick.get(deployInscriptionId) || loadBrc20Tick(deployInscriptionId)
33
+ )
34
+ }
35
+
36
+ const getBrc20TickFromAsset = async (asset) => {
37
+ assert(asset.assetType === 'BRC20_TOKEN', `Asset ${asset.name} is not a brc20 asset`)
38
+ const deployInscriptionId = asset.assetId
39
+ const brc20Tick = asset.brc20Tick // this should always be true once CTR is patched
40
+ if (brc20Tick) {
41
+ save({ deployInscriptionId, brc20Tick })
42
+ return brc20Tick
43
+ }
44
+ return getBrc20Tick(deployInscriptionId)
45
+ }
46
+
47
+ return { getBrc20TickFromAsset, getDeployInscriptionId, getBrc20Tick }
48
+ }