@exodus/bitcoin-plugin 1.32.1 → 1.32.2

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/CHANGELOG.md CHANGED
@@ -3,6 +3,18 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [1.32.2](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-plugin@1.32.1...@exodus/bitcoin-plugin@1.32.2) (2025-03-19)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+
12
+ * fix: remove brc20 dead code (#5286)
13
+
14
+ * fix: spelling (#5284)
15
+
16
+
17
+
6
18
  ## [1.32.1](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-plugin@1.32.0...@exodus/bitcoin-plugin@1.32.1) (2025-01-27)
7
19
 
8
20
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-plugin",
3
- "version": "1.32.1",
3
+ "version": "1.32.2",
4
4
  "description": "Bitcoin plugin for Exodus SDK powered wallets",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -23,14 +23,12 @@
23
23
  "dependencies": {
24
24
  "@exodus/asset-lib": "^5.0.0",
25
25
  "@exodus/bip44-constants": "^195.0.0",
26
- "@exodus/bitcoin-api": "^2.30.0",
26
+ "@exodus/bitcoin-api": "^2.31.1",
27
27
  "@exodus/bitcoin-lib": "^2.4.2",
28
28
  "@exodus/bitcoin-meta": "^2.0.1",
29
29
  "@exodus/bitcoinjs": "^1.1.0",
30
- "@exodus/crypto": "^1.0.0-rc.13",
31
30
  "@exodus/fetch": "^1.3.0",
32
31
  "@exodus/models": "^12.0.1",
33
- "@exodus/text-encoding-utf8": "^1.0.2",
34
32
  "@exodus/web3-bitcoin-utils": "^2.3.3",
35
33
  "coininfo": "^5.1.0",
36
34
  "lodash": "^4.17.21",
@@ -58,5 +56,5 @@
58
56
  "type": "git",
59
57
  "url": "git+https://github.com/ExodusMovement/assets.git"
60
58
  },
61
- "gitHead": "ca80bc54107fb73e965defe4948136e7130a8f02"
59
+ "gitHead": "f1b6ccb198231db1fb6c9c51a0173967ec4efd1f"
62
60
  }
@@ -33,18 +33,10 @@ import { createGetSupportedPurposes, getDefaultAddressPath } from './compatibili
33
33
  import { createCustomFeesApi } from './custom-fees.js'
34
34
  import { bitcoinFeeDataFactory } from './fee-data.js'
35
35
  import BitcoinFeeMonitor from './fee-monitor.js'
36
- import { brc20BalancesAndFeeAdapterFactory } from './ordinals/brc-20-balances-and-fee-adapter.js'
37
- import { brc20ApiClientFactory, DEFAULT_BRC_20_URL } from './ordinals/brc-20-client.js'
38
- import { createTokenFactory } from './ordinals/create-token-factory.js'
39
- import { inscriptionsServiceFactory } from './ordinals/inscriptions-service.js'
40
36
  import { nftsApiFactory } from './ordinals/nfts.js'
41
37
  import { DEFAULT_ORDINAL_CHAIN_INDEX } from './ordinals/ordinals-constants.js'
42
- import { reloadBrc20TokenBalances } from './ordinals/reload-brc20-token-balances.js'
43
- import { tickInscriptionIdIndexerFactory } from './ordinals/tick-inscription-id-indexer.js'
44
38
  import { createWeb3API } from './web3/index.js'
45
39
 
46
- const DEFAULT_TICKS_BETWEEN_BRC20_FETCHES = 30
47
-
48
40
  export const createBitcoinAssetFactory =
49
41
  ({ asset, apiUrl: defaultApiUrl, coinInfoNetwork, isTestnet = false }) =>
50
42
  (
@@ -56,9 +48,6 @@ export const createBitcoinAssetFactory =
56
48
  allowUnconfirmedRbfEnabledUtxos = false,
57
49
  ordinalChainIndex = DEFAULT_ORDINAL_CHAIN_INDEX,
58
50
  ordinalsEnabled = false,
59
- brc20Enabled = false,
60
- brc20Url = DEFAULT_BRC_20_URL,
61
- brc20TickInterval = DEFAULT_TICKS_BETWEEN_BRC20_FETCHES,
62
51
  gapLimit = 10,
63
52
  refreshGapLimit = 25,
64
53
  feeDataCustomValues,
@@ -74,10 +63,7 @@ export const createBitcoinAssetFactory =
74
63
  assert(asset, 'asset is required')
75
64
  assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
76
65
  assert(apiUrl, 'apiUrl is required')
77
- assert(
78
- brc20Enabled ? ordinalsEnabled : true,
79
- 'if brc20Enabled is true then ordinalsEnabled must be true'
80
- )
66
+
81
67
  const coinInfo = _coinInfo(coinInfoNetwork || asset.name)
82
68
 
83
69
  const insightClient = new InsightAPIClient(apiUrl)
@@ -109,7 +95,6 @@ export const createBitcoinAssetFactory =
109
95
  moveFunds: true,
110
96
  multipleAddresses: true,
111
97
  nfts: ordinalsEnabled,
112
- customTokens: brc20Enabled,
113
98
  isTestnet,
114
99
  signWithSigner: true,
115
100
  supportsCustomFees: true,
@@ -120,7 +105,7 @@ export const createBitcoinAssetFactory =
120
105
  addressApi: address,
121
106
  })
122
107
 
123
- const baseFeeResolver = new GetFeeResolver({
108
+ const { getFee, getAvailableBalance, canBumpTx, getSpendableBalance } = new GetFeeResolver({
124
109
  getFeeEstimator,
125
110
  allowUnconfirmedRbfEnabledUtxos,
126
111
  utxosDescendingOrder,
@@ -132,17 +117,12 @@ export const createBitcoinAssetFactory =
132
117
  overrideDefaults: feeDataCustomValues,
133
118
  })
134
119
 
135
- const baseGetBalances = getBalancesFactory({
120
+ const getBalances = getBalancesFactory({
136
121
  feeData,
137
- getSpendableBalance: baseFeeResolver.getSpendableBalance,
122
+ getSpendableBalance,
138
123
  ordinalsEnabled,
139
124
  })
140
125
 
141
- const brc20Client = brc20Enabled ? brc20ApiClientFactory({ brc20Url }) : undefined
142
- const tickInscriptionIdIndexer = brc20Enabled
143
- ? tickInscriptionIdIndexerFactory({ brc20Client })
144
- : undefined
145
-
146
126
  const baseGetPrepareSendTx = getPrepareSendTransaction({
147
127
  getFeeEstimator,
148
128
  allowUnconfirmedRbfEnabledUtxos,
@@ -152,7 +132,7 @@ export const createBitcoinAssetFactory =
152
132
  changeAddressType,
153
133
  })
154
134
 
155
- const baseSendTx = createAndBroadcastTXFactory({
135
+ const sendTx = createAndBroadcastTXFactory({
156
136
  getFeeEstimator,
157
137
  allowUnconfirmedRbfEnabledUtxos,
158
138
  ordinalsEnabled,
@@ -160,29 +140,6 @@ export const createBitcoinAssetFactory =
160
140
  assetClientInterface,
161
141
  changeAddressType,
162
142
  })
163
- const inscriptionsService = brc20Enabled
164
- ? inscriptionsServiceFactory({
165
- asset,
166
- network: coinInfo.toBitcoinJS(),
167
- ordinalChainIndex,
168
- })
169
- : undefined
170
-
171
- const { getFee, getBalances, getAvailableBalance, canBumpTx, getSpendableBalance, sendTx } =
172
- brc20Enabled
173
- ? brc20BalancesAndFeeAdapterFactory({
174
- assetClientInterface,
175
- inscriptionsService,
176
- ...baseFeeResolver,
177
- getBalances: baseGetBalances,
178
- sendTx: baseSendTx,
179
- tickInscriptionIdIndexer,
180
- })
181
- : {
182
- ...baseFeeResolver,
183
- getBalances: baseGetBalances,
184
- sendTx: baseSendTx,
185
- }
186
143
 
187
144
  const prepareForSigning = createPrepareForSigning({
188
145
  assetName: asset.name,
@@ -227,19 +184,14 @@ export const createBitcoinAssetFactory =
227
184
  const accountStateClass = createAccountState({
228
185
  asset,
229
186
  ordinalsEnabled,
230
- brc20Enabled,
231
187
  })
232
188
 
233
189
  const nfts = ordinalsEnabled
234
190
  ? nftsApiFactory({ ordinalChainIndex, asset, assetClientInterface })
235
191
  : undefined
236
192
 
237
- const { createToken, getTokens, validateAssetId } = brc20Enabled
238
- ? createTokenFactory({ address, bip44, keys, getBalances }, [])
239
- : {}
240
-
241
193
  const createHistoryMonitor = (args) => {
242
- const monitor = createBitcoinMonitor({
194
+ return createBitcoinMonitor({
243
195
  assetClientInterface,
244
196
  insightClient,
245
197
  ordinalsEnabled,
@@ -249,27 +201,6 @@ export const createBitcoinAssetFactory =
249
201
  refreshGapLimit,
250
202
  ...args,
251
203
  })
252
-
253
- if (brc20Enabled) {
254
- monitor.addHook('after-tick', async ({ walletAccount }) => {
255
- const brc20UpdateTick = monitor.tickCount[walletAccount] % brc20TickInterval === 0
256
- if (brc20UpdateTick) {
257
- const { unknownDeployInscriptionIds } = await reloadBrc20TokenBalances({
258
- walletAccount,
259
- asset,
260
- ordinalChainIndex,
261
- brc20Client,
262
- assetClientInterface,
263
- tickInscriptionIdIndexer,
264
- })
265
- if (unknownDeployInscriptionIds.length > 0) {
266
- monitor.emit('unknown-tokens', unknownDeployInscriptionIds)
267
- }
268
- }
269
- })
270
- }
271
-
272
- return monitor
273
204
  }
274
205
 
275
206
  const addressHasHistory = async (address) => {
@@ -372,9 +303,6 @@ export const createBitcoinAssetFactory =
372
303
  getFee,
373
304
  moveFunds,
374
305
  nfts,
375
- createToken,
376
- getTokens,
377
- validateAssetId,
378
306
  web3: createWeb3API({
379
307
  assetClientInterface,
380
308
  baseAssetName: asset.name,
@@ -398,7 +326,6 @@ export const createBitcoinAssetFactory =
398
326
  canBumpTx,
399
327
  getAvailableBalance,
400
328
  getSpendableBalance,
401
- inscriptions: inscriptionsService,
402
329
  prepareSendTx: baseGetPrepareSendTx,
403
330
  createBatchTx,
404
331
  encodeMultisigContract,
@@ -412,9 +339,6 @@ export const createBitcoinAssetFactory =
412
339
  allowUnconfirmedRbfEnabledUtxos,
413
340
  ordinalChainIndex,
414
341
  ordinalsEnabled,
415
- brc20Enabled,
416
- brc20Url,
417
- brc20TickInterval,
418
342
  gapLimit,
419
343
  refreshGapLimit,
420
344
  feeDataCustomValues,
@@ -1,8 +1,3 @@
1
- // Ordinal postage is the amount of sats left in an inscription for future transferring fee
2
- // Wallet may use some postage when transferring an ordinal utxos or consume the fee from another regular utxos
3
- // In general, wallets don't spend the postage.
4
- export const DEFAULT_BRC20_POSTAGE = 546
5
-
6
1
  export const DEFAULT_ORDINAL_POSTAGE = 10_000
7
2
 
8
3
  // What's the taproot chain index to use as the default ordinal address (as in purpose 86, m/2/0).
@@ -1,212 +0,0 @@
1
- import { getOrdinalsUtxos } from '@exodus/bitcoin-api'
2
- import { BumpType } from '@exodus/bitcoin-lib'
3
- import { Address, UtxoCollection } from '@exodus/models'
4
- import assert from 'minimalistic-assert'
5
-
6
- import { brc20Utils } from './brc-20-utils.js'
7
- import { createBrc20Command } from './create-brc-20-command.js'
8
-
9
- export const brc20BalancesAndFeeAdapterFactory = ({
10
- assetClientInterface,
11
- inscriptionsService,
12
- getBalances,
13
- getFee,
14
- getAvailableBalance,
15
- canBumpTx,
16
- getSpendableBalance,
17
- sendTx,
18
- tickInscriptionIdIndexer,
19
- }) => {
20
- assert(inscriptionsService, 'inscriptionsService is required')
21
- assert(getBalances, 'getBalances is required')
22
- assert(getFee, 'getFee is required')
23
- assert(getAvailableBalance, 'getAvailableBalance is required')
24
- assert(canBumpTx, 'canBumpTx is required')
25
- assert(getSpendableBalance, 'getSpendableBalance is required')
26
- assert(sendTx, 'sendTx is required')
27
- assert(tickInscriptionIdIndexer, 'unknownDeployInscriptionIds is required')
28
-
29
- const { isToken, getTokenBalance } = brc20Utils
30
-
31
- const isInscription = ({ options }) => {
32
- return !options?.feeOpts?.inscriptionIds?.length
33
- }
34
-
35
- const sendBrc20 = async ({ asset: token, walletAccount, address, amount, options }) => {
36
- const { broadcastInscription, createBrc20Inscription } = inscriptionsService
37
-
38
- const { customFee, isSendAll } = options || {}
39
-
40
- const asset = token.baseAsset
41
- const accountState = await assetClientInterface.getAccountState({
42
- walletAccount,
43
- assetName: asset.name,
44
- })
45
-
46
- const tick = await tickInscriptionIdIndexer.getBrc20TickFromAsset(token)
47
-
48
- const tokenAmount =
49
- (isSendAll ? getTokenBalance({ asset: token, accountState }) : amount) || token.currency.ZERO
50
-
51
- if (tokenAmount.lte(token.currency.ZERO)) {
52
- throw new Error(
53
- `Cannot send ${tokenAmount.toDefaultString({ unit: true })} amount for asset :${
54
- token.name
55
- }. Tick: ${tick}`
56
- )
57
- }
58
-
59
- const { inscriptionIds, newInscriptions } = createBrc20Command({
60
- asset: token,
61
- amount: tokenAmount,
62
- accountState,
63
- })
64
-
65
- for (const newInscription of newInscriptions) {
66
- const inscription = createBrc20Inscription({
67
- op: 'transfer',
68
- tick,
69
- amt: newInscription.amount.toDefaultString({ unit: false }),
70
- })
71
-
72
- const inscriptionResult = await broadcastInscription({
73
- asset,
74
- assetClientInterface,
75
- walletAccount,
76
- receiverWalletAccount: walletAccount,
77
- inscription,
78
- customFee,
79
- })
80
-
81
- inscriptionIds.push(inscriptionResult.inscriptionId)
82
- }
83
-
84
- return sendTx({
85
- asset: token,
86
- walletAccount,
87
- address,
88
- amount: tokenAmount,
89
- options: {
90
- ...options,
91
- isRbfAllowed: false,
92
- brc20: { inscriptionIds },
93
- },
94
- })
95
- }
96
-
97
- const getFeeBrc20 = ({
98
- asset: token,
99
- accountState,
100
- txSet,
101
- feeData,
102
- amount,
103
- customFee,
104
- isSendAll,
105
- }) => {
106
- const { getInscriptionFees, createBrc20Inscription } = inscriptionsService
107
-
108
- const asset = token.baseAsset
109
-
110
- const availableBalance = getTokenBalance({ asset: token, accountState })
111
-
112
- const tokenAmount = (isSendAll ? availableBalance : amount) || token.currency.ZERO
113
-
114
- if (tokenAmount.lte(token.currency.ZERO) || availableBalance.lt(tokenAmount)) {
115
- return { fee: asset.currency.ZERO }
116
- }
117
-
118
- const { inscriptionIds, newInscriptions } = createBrc20Command({
119
- asset: token,
120
- amount: tokenAmount,
121
- accountState,
122
- })
123
-
124
- const newInscriptionFees = []
125
-
126
- let index = 0
127
- for (const newInscription of newInscriptions) {
128
- const inscription = createBrc20Inscription({
129
- op: 'transfer',
130
- tick: 'abcd',
131
- amt: newInscription.amount.toDefaultString({ unit: false }),
132
- })
133
- const newInscriptionFee = getInscriptionFees({
134
- asset,
135
- getFee,
136
- txSet,
137
- inscription,
138
- customFee,
139
- accountState,
140
- feeData,
141
- })
142
- newInscriptionFees.push(newInscriptionFee)
143
- const inscriptionId = `new_inscription_${index++}`
144
- newInscription.inscriptionId = inscriptionId
145
- inscriptionIds.push(inscriptionId) // this is just to count how many utxos needs to be send in the last txs
146
- }
147
-
148
- const ordinalsUtxos = getOrdinalsUtxos({ accountState, asset })
149
-
150
- const mockedOrdinalsUtxos = ordinalsUtxos.union(
151
- UtxoCollection.fromArray(
152
- newInscriptions.map(({ address, inscriptionId }, index) => {
153
- return {
154
- address: Address.create(address),
155
- txId: inscriptionId,
156
- confirmations: 1,
157
- value: '600 satoshis',
158
- vout: 0,
159
- script: '5120d96a4516786abc536ac4445887262770134f2ab139012856c1f3fdd13c1b02ac', // dummy taproot script
160
- inscriptions: [{ inscriptionId, offset: 0 }],
161
- }
162
- }),
163
- { currency: asset.currency }
164
- )
165
- )
166
- const { fee: lastSendingFee } = getFee({
167
- asset,
168
- accountState: {
169
- ...accountState,
170
- ordinalsUtxos: mockedOrdinalsUtxos,
171
- },
172
- txSet,
173
- feeData,
174
- amount: asset.currency.ZERO,
175
- customFee,
176
- brc20: { inscriptionIds },
177
- })
178
-
179
- const fee = newInscriptionFees.reduce(
180
- (total, newInscriptionFee) => total.add(newInscriptionFee.totalFee),
181
- lastSendingFee
182
- )
183
-
184
- return { fee, lastSendingFee, newInscriptionFees }
185
- }
186
-
187
- return {
188
- canBumpTx: (args) => {
189
- return isToken(args) ? { bumpType: BumpType.NONE } : canBumpTx(args)
190
- },
191
-
192
- getSpendableBalance: (args) => {
193
- return isToken(args) ? getTokenBalance(args) : getSpendableBalance(args)
194
- },
195
-
196
- getFee: (args) => {
197
- return isToken(args) ? getFeeBrc20(args) : getFee(args)
198
- },
199
-
200
- getAvailableBalance: (args) => {
201
- return isToken(args) ? getTokenBalance(args) : getAvailableBalance(args)
202
- },
203
-
204
- getBalances: (args) => {
205
- return isToken(args) ? { balance: getTokenBalance(args) } : getBalances(args)
206
- },
207
-
208
- sendTx: (...args) => {
209
- return isToken(args[0]) && isInscription(...args) ? sendBrc20(...args) : sendTx(...args)
210
- },
211
- }
212
- }
@@ -1,120 +0,0 @@
1
- import { fetchival } from '@exodus/fetch'
2
- import assert from 'minimalistic-assert'
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
- export 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
- // eslint-disable-next-line unicorn/no-useless-promise-resolve-reject
15
- return Promise.reject(new Error(`${err.message}. Error: ${responseText.slice(0, 200)}`)) // trying to get error more info from body)
16
- } catch {}
17
- }
18
-
19
- throw new Error(err.message)
20
- }
21
-
22
- export const brc20ApiClientFactory = ({
23
- brc20Url = DEFAULT_BRC_20_URL,
24
- ordinalsApiKey = DEFAULT_ORDINALS_API_KEY,
25
- } = {}) => {
26
- let baseUrl = brc20Url
27
-
28
- const setUrl = (newBaseUrl) => {
29
- baseUrl = newBaseUrl || DEFAULT_BRC_20_URL
30
- }
31
-
32
- const request = (path, queryParams) => {
33
- const headers = {
34
- Accept: 'application/json',
35
- 'Content-Type': 'application/json',
36
- }
37
- if (ordinalsApiKey) headers.Authorization = `Bearer ${ordinalsApiKey}`
38
-
39
- return fetchival(baseUrl + path, { headers, timeout: HTTP_POST_TIMEOUT })
40
- .get(queryParams)
41
- .catch(improveErrorMessage)
42
- }
43
-
44
- const getOwnerTickBalances = async ({ address }) => {
45
- assert(address, 'address is required')
46
- return request(`/v2/ord/brc20/balances/${encodeURIComponent(address)}`)
47
- }
48
-
49
- const getTickerInfo = async ({ tick }) => {
50
- assert(tick, 'tick is required')
51
- return request(`/v2/ord/brc20/tokens/${encodeURIComponent(tick)}`)
52
- }
53
-
54
- const getTickerInfoByDeployInscriptionId = async ({ deployInscriptionId }) => {
55
- assert(deployInscriptionId, 'deployInscriptionId is required')
56
- return request(
57
- `/v2/ord/btc/brc20/deployed_inscription/${encodeURIComponent(deployInscriptionId)}`
58
- )
59
- }
60
-
61
- const paginatedTransactionHistory = async (queryParams) => {
62
- const address = queryParams.address
63
- assert(address, 'address is required')
64
- const events = []
65
- const limit = queryParams.limit || 40
66
- let offset = queryParams.offset || 0
67
- let response
68
- do {
69
- response = await request(`/v2/ord/brc20/history/${encodeURIComponent(address)}`, {
70
- limit,
71
- offset,
72
- })
73
- offset = offset + limit
74
- events.push(...response.results)
75
- } while (offset < response.total)
76
-
77
- // remap to previous event shape that later logic expects
78
- return events.map((event) => {
79
- const brc20OwnerAvailableBalance = Number(event.available_balance)
80
- const brc20OwnerTransferBalance = Number(event.transferrable_balance)
81
- assert(!isNaN(brc20OwnerAvailableBalance))
82
- assert(!isNaN(brc20OwnerTransferBalance))
83
- const brc20Op =
84
- event.type === 'inscribe-transfer'
85
- ? 'transfer'
86
- : event.type === 'inscribe-mint'
87
- ? 'mint'
88
- : event.type === null
89
- ? 'unknown'
90
- : event.type
91
-
92
- return {
93
- brc20Tick: event.ticker,
94
- inscriptionId: event.inscription_id,
95
- inscriptionNumber: event.inscription_number,
96
- txId: event.tx_id,
97
- createdAt: new Date(event.block_time * 1000).toISOString(),
98
- owner: address,
99
- transferFrom: event.from,
100
- transferTo: event.to,
101
- brc20Op,
102
- brc20Amt: event.amount,
103
- brc20OwnerAvailableBalance, // todo use NUs for adding these
104
- brc20OwnerTransferBalance, // todo use NUs for adding these
105
- }
106
- })
107
- }
108
-
109
- const getTokenTransactionHistory = ({ ticker, offset, limit, address }) => {
110
- return paginatedTransactionHistory({ ticker, offset, limit, address })
111
- }
112
-
113
- return {
114
- setUrl,
115
- getOwnerTickBalances,
116
- getTickerInfo,
117
- getTickerInfoByDeployInscriptionId,
118
- getTokenTransactionHistory,
119
- }
120
- }
@@ -1,137 +0,0 @@
1
- import { getOrdinalsUtxos } from '@exodus/bitcoin-api'
2
- import lodash from 'lodash'
3
- import assert from 'minimalistic-assert'
4
-
5
- const { sumBy } = lodash
6
-
7
- export const brc20Utils = {
8
- getKnownInscriptionIds: ({ asset, accountState }) => {
9
- assert(accountState, 'accountState is required')
10
- assert(asset, 'asset is required')
11
- return getOrdinalsUtxos({ accountState, asset })
12
- .toArray()
13
- .flatMap((utxo) => utxo.inscriptions?.map((i) => i.inscriptionId))
14
- },
15
-
16
- getAllTransferableList: ({ accountState, asset }) => {
17
- assert(accountState, 'accountState is required')
18
- assert(asset, 'asset is required')
19
- const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
20
- const knownInscriptionIds = brc20Utils.getKnownInscriptionIds({ asset, accountState })
21
- return assetBalances
22
- .flatMap((item) => item.transferableList)
23
- .map((item) => {
24
- const sent = item.sent
25
- const ordinalUtxoKnown = knownInscriptionIds.includes(item.inscriptionId)
26
- return {
27
- inscriptionId: item.inscriptionId,
28
- inscriptionNumber: item.inscriptionNumber,
29
- txId: item.txId,
30
- amount: asset.currency.defaultUnit(item.brc20Amt),
31
- sent,
32
- isOrdinalUtxoKnown: ordinalUtxoKnown,
33
- valid: !sent && ordinalUtxoKnown,
34
- }
35
- })
36
- .sort((a, b) => {
37
- // valid first, then by inscription number descending
38
- if (a.valid && !b.valid) return -1
39
- if (!a.valid && b.valid) return 1
40
- return b.inscriptionNumber - a.inscriptionNumber
41
- })
42
- },
43
-
44
- getTransferableList: ({ asset, accountState }) => {
45
- const transferableList = brc20Utils.getAllTransferableList({ asset, accountState })
46
- // return the list of transferable inscription items that we hold of the utxos
47
- return transferableList
48
- .filter((item) => item.valid)
49
- .sort((a, b) => {
50
- // let's consume old ones first!
51
- return a.inscriptionNumber - b.inscriptionNumber
52
- })
53
- },
54
-
55
- getInTransitBalance: ({ asset, accountState }) => {
56
- const transferableList = brc20Utils.getAllTransferableList({ asset, accountState })
57
- const inTransitList = transferableList.filter((item) => !item.isOrdinalUtxoKnown && !item.sent)
58
- return inTransitList.reduce((amount, item) => amount.add(item.amount), asset.currency.ZERO)
59
- },
60
-
61
- isToken: ({ asset }) => {
62
- assert(asset, 'asset must be provided')
63
- return asset.name !== asset.baseAsset.name
64
- },
65
-
66
- getTokenBalance: ({ asset, accountState }) => {
67
- assert(asset, 'asset must be provided')
68
- assert(accountState, 'accountState must be provided')
69
- assert(brc20Utils.isToken({ asset }), `${asset.name} is must be a token`)
70
- const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
71
- const sum = sumBy(assetBalances, 'brc20OwnerTotalBalance')
72
- return asset.currency
73
- .defaultUnit(sum || 0)
74
- .sub(brc20Utils.getInTransitBalance({ asset, accountState }))
75
- .clampLowerZero()
76
- },
77
-
78
- getAvailableBalance: ({ asset, accountState }) => {
79
- assert(asset, 'asset must be provided')
80
- assert(accountState, 'accountState must be provided')
81
- assert(brc20Utils.isToken({ asset }), `${asset.name} is must be a token`)
82
- const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
83
- const sum = sumBy(assetBalances, 'brc20OwnerAvailableBalance')
84
- return asset.currency.defaultUnit(sum || 0)
85
- },
86
-
87
- getTransferableBalance: ({ asset, accountState }) => {
88
- assert(asset, 'asset must be provided')
89
- assert(accountState, 'accountState must be provided')
90
- assert(brc20Utils.isToken({ asset }), `${asset.name} is must be a token`)
91
- const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
92
- const sum = sumBy(assetBalances, 'brc20OwnerTransferBalance')
93
- return asset.currency
94
- .defaultUnit(sum || 0)
95
- .sub(brc20Utils.getInTransitBalance({ asset, accountState }))
96
- .clampLowerZero()
97
- },
98
-
99
- getAllSublists(transferableList) {
100
- const result = []
101
-
102
- const generateSublists = (sublist, index) => {
103
- if (index === transferableList.length) {
104
- result.push(sublist)
105
- return
106
- }
107
-
108
- // Include the current element in the sublist
109
- generateSublists([...sublist, transferableList[index]], index + 1)
110
-
111
- // Exclude the current element from the sublist
112
- generateSublists(sublist, index + 1)
113
- }
114
-
115
- generateSublists([], 0)
116
- return result
117
- },
118
-
119
- findTransferableItems({ transferableList, amount, currency }) {
120
- const sublists = brc20Utils
121
- .getAllSublists(transferableList)
122
- .map((transferableItems) => {
123
- const transferableItemsAmount = transferableItems.reduce(
124
- (acc, item) => acc.add(item.amount),
125
- currency.ZERO
126
- )
127
- return { transferableItemsAmount, transferableItems }
128
- })
129
- .filter((item) => item.transferableItemsAmount.lte(amount))
130
- const found = sublists.find((item) => item.transferableItemsAmount.equals(amount))
131
- if (found) {
132
- return found
133
- }
134
-
135
- return sublists.sort((a, b) => b.transferableItems.length - a.transferableItems.length)[0]
136
- },
137
- }
@@ -1,51 +0,0 @@
1
- import assert from 'minimalistic-assert'
2
-
3
- import { brc20Utils } from './brc-20-utils.js'
4
-
5
- export const createBrc20Command = ({ asset, amount, accountState }) => {
6
- assert(asset.name !== asset.baseAsset.name, `${asset.name} should be a token!`)
7
-
8
- const brc20BalanceMultipleAddresses = accountState?.brc20Balances?.[asset.name] || {}
9
- const balance = brc20Utils.getTokenBalance({ asset, accountState })
10
- const transferableList = brc20Utils.getTransferableList({ asset, accountState })
11
- assert(
12
- balance.gte(amount),
13
- `Not enough ${asset.name} balance. Wanted ${amount.toDefaultString({
14
- unit: true,
15
- })}, but got ${balance.toDefaultString({ unit: true })}`
16
- )
17
-
18
- const transferableItemsResult = brc20Utils.findTransferableItems({
19
- transferableList,
20
- amount,
21
- currency: asset.currency,
22
- })
23
- const brc20 = {
24
- inscriptionIds: transferableItemsResult.transferableItems.map((i) => i.inscriptionId),
25
- }
26
-
27
- let requireInscriptionAmount = amount.sub(transferableItemsResult.transferableItemsAmount)
28
-
29
- brc20.newInscriptions = Object.entries(brc20BalanceMultipleAddresses)
30
- .map(([address, assetBalance]) => {
31
- const availableBalance = asset.currency.defaultUnit(assetBalance.brc20OwnerAvailableBalance)
32
- const amount = requireInscriptionAmount.gt(availableBalance)
33
- ? availableBalance
34
- : requireInscriptionAmount
35
- requireInscriptionAmount = requireInscriptionAmount.sub(amount)
36
- return {
37
- amount,
38
- address,
39
- }
40
- })
41
- .filter((i) => i.amount.gt(asset.currency.ZERO))
42
-
43
- assert(
44
- balance.gte(amount),
45
- `Not enough ${asset.name} balance. Wanted ${amount.toDefaultString({
46
- unit: true,
47
- })}, but got ${balance.toDefaultString({ unit: true })}`
48
- )
49
-
50
- return brc20
51
- }
@@ -1,31 +0,0 @@
1
- export function validateAssetId(assetId) {
2
- if (typeof assetId !== 'string') return false
3
- const rgx = /^[\da-f]{64}i\d+$/
4
- return rgx.test(assetId)
5
- }
6
-
7
- export const createTokenFactory = ({ address, bip44, keys, getBalances }, networkAssets) => {
8
- const createToken = ({ features: providedFeatures, ...tokenDef }) => {
9
- const features = { ...providedFeatures }
10
- return {
11
- ...tokenDef,
12
- api: {
13
- getBalances,
14
- features,
15
- hasFeature: (feature) => !!features[feature],
16
- },
17
- address,
18
- bip44,
19
- keys,
20
- }
21
- }
22
-
23
- return {
24
- validateAssetId,
25
- createToken,
26
- getTokens: () =>
27
- Object.values(networkAssets)
28
- .filter((asset) => asset.name !== asset.baseAsset.name)
29
- .map(createToken),
30
- }
31
- }
@@ -1,377 +0,0 @@
1
- import { getOrdinalsUtxos, toAsyncSigner } from '@exodus/bitcoin-api'
2
- import { getTxSequence } from '@exodus/bitcoin-lib'
3
- import * as bitcoinjsLib from '@exodus/bitcoinjs'
4
- import { randomBytes } from '@exodus/crypto/randomBytes'
5
- import { privateKeyToPublicKey, publicKeyToX } from '@exodus/crypto/secp256k1'
6
- import { TextEncoder } from '@exodus/text-encoding-utf8'
7
- import assert from 'minimalistic-assert'
8
-
9
- import { DEFAULT_BRC20_POSTAGE, DEFAULT_ORDINAL_POSTAGE } from './ordinals-constants.js'
10
-
11
- const encoder = new TextEncoder()
12
- export function createInscriptionScript({ xOnlyPublicKey, inscription }) {
13
- assert(xOnlyPublicKey instanceof Buffer, `xOnlyPublicKey must be a Buffer`)
14
- assert(inscription, `inscription is required`)
15
- assert(inscription.content instanceof Buffer, `inscription.content must be a Buffer`)
16
- assert(inscription.contentType instanceof Buffer, `inscription.content must be a Buffer`)
17
- const protocolId = Buffer.from(encoder.encode('ord'))
18
- return [
19
- xOnlyPublicKey,
20
- bitcoinjsLib.opcodes.OP_CHECKSIG,
21
- bitcoinjsLib.opcodes.OP_0,
22
- bitcoinjsLib.opcodes.OP_IF,
23
- protocolId,
24
- 1,
25
- 1, // double 1 to avoid hitting asMinimalOP
26
- inscription.contentType,
27
- bitcoinjsLib.opcodes.OP_0,
28
- inscription.content,
29
- bitcoinjsLib.opcodes.OP_ENDIF,
30
- ]
31
- }
32
-
33
- export const inscriptionsServiceFactory = ({ network, ordinalChainIndex }) => {
34
- assert(network, 'network is required')
35
- assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
36
-
37
- function createInscription({ contentType, content, postage }) {
38
- assert(Number.isSafeInteger(postage), 'postage must be a Safe integer')
39
- assert(contentType, 'contentType is required integer')
40
- assert(content, 'content is required integer')
41
-
42
- return {
43
- contentType: Buffer.from(encoder.encode(contentType)),
44
- content: Buffer.from(content),
45
- postage,
46
- }
47
- }
48
-
49
- function createTextInscription({ text, postage = DEFAULT_ORDINAL_POSTAGE }) {
50
- const contentType = 'text/plain;charset=utf-8'
51
- const content = encoder.encode(text)
52
- return createInscription({ contentType, content, postage })
53
- }
54
-
55
- function createBrc20Inscription({
56
- op,
57
- tick,
58
- amt,
59
- max,
60
- lim,
61
- dec,
62
- postage = DEFAULT_BRC20_POSTAGE,
63
- }) {
64
- let body
65
-
66
- assert(['deploy', 'mint', 'transfer'].includes(op), `invalid brc20 op ${op}`)
67
- assert(typeof tick === 'string', 'tick is required')
68
-
69
- if (['mint', 'transfer'].includes(op)) {
70
- assert(typeof amt === 'string', 'amt is required')
71
- body = { p: 'brc-20', op, tick, amt }
72
- } else {
73
- assert(typeof max === 'string', 'max is required')
74
- assert(typeof lim === 'string', 'lim is required')
75
- body = { p: 'brc-20', op, tick, max, lim, dec }
76
- }
77
-
78
- const contentType = 'text/plain;charset=utf-8'
79
- const content = encoder.encode(JSON.stringify(body))
80
- return createInscription({ contentType, content, postage })
81
- }
82
-
83
- function createCommitTxData({ publicKey, inscription }) {
84
- assert(publicKey, 'encodePublic is required')
85
- assert(inscription, 'inscription is required')
86
- const xOnlyPublicKey = publicKeyToX({ publicKey, format: 'buffer' })
87
- const script = createInscriptionScript({ xOnlyPublicKey, inscription })
88
-
89
- const outputScript = bitcoinjsLib.script.compile(script)
90
-
91
- const scriptTree = {
92
- output: outputScript,
93
- }
94
-
95
- const scriptTaproot = bitcoinjsLib.payments.p2tr({
96
- internalPubkey: xOnlyPublicKey,
97
- scriptTree,
98
- redeem: scriptTree,
99
- network,
100
- })
101
-
102
- const tapleaf = scriptTaproot.hash.toString('hex')
103
-
104
- const revealAddress = scriptTaproot.address
105
- const tpubkey = scriptTaproot.pubkey.toString('hex')
106
- const cblock = scriptTaproot.witness?.[scriptTaproot.witness.length - 1].toString('hex')
107
-
108
- return {
109
- script,
110
- tapleaf,
111
- tpubkey,
112
- cblock,
113
- revealAddress,
114
- scriptTaproot,
115
- outputScript,
116
- }
117
- }
118
-
119
- function createPsbt({ scriptTaproot, outputScript, cblock, commitTxResult, amount, toAddress }) {
120
- const tapLeafScript = {
121
- leafVersion: scriptTaproot.redeemVersion, // 192 0xc0
122
- script: outputScript,
123
- controlBlock: Buffer.from(cblock, 'hex'),
124
- }
125
-
126
- const psbt = new bitcoinjsLib.Psbt({ network })
127
- psbt.addInput({
128
- hash: commitTxResult.txId,
129
- index: commitTxResult.sendUtxoIndex,
130
- witnessUtxo: { value: commitTxResult.sendAmount, script: scriptTaproot.output },
131
- tapLeafScript: [tapLeafScript],
132
- sequence: getTxSequence(false),
133
- })
134
-
135
- psbt.addOutput({
136
- value: amount, // generally 1000 for nfts, 549 for brc20
137
- address: toAddress.toString(),
138
- })
139
- return { tapLeafScript, psbt }
140
- }
141
-
142
- function finalizePsbt({ psbt, signature, commitTxData, tapLeafScript }) {
143
- const customFinalizer = () => {
144
- const witness = [
145
- Buffer.from(signature, 'hex'),
146
- commitTxData.outputScript,
147
- tapLeafScript.controlBlock,
148
- ]
149
-
150
- return {
151
- finalScriptWitness: bitcoinjsLib.witnessStackToScriptWitness(witness),
152
- }
153
- }
154
-
155
- psbt.finalizeInput(0, customFinalizer)
156
- return psbt.extractTransaction()
157
- }
158
-
159
- const estimationStaticData = {
160
- toAddress: 'bc1p4vgmzfzu642zxj04525xr8szd446ydct3y44dqc7wg88wd8e4v9qzaz7k9',
161
- publicKey: Buffer.from(
162
- '041b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f70beaf8f588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8d1',
163
- 'hex'
164
- ),
165
- txId: '2222222222222222222222222222222222222222222222222222222222222222',
166
- signature: Buffer.alloc(64, 3),
167
- }
168
-
169
- const estimateTxSize = ({ inscription }) => {
170
- const { publicKey, txId, toAddress, signature } = estimationStaticData
171
-
172
- const commitTxData = createCommitTxData({ publicKey, inscription })
173
-
174
- const amount = inscription.postage
175
-
176
- const commitTxResult = {
177
- txId,
178
- sendUtxoIndex: 0,
179
- sendAmount: 100_000,
180
- }
181
-
182
- const { tapLeafScript, psbt } = createPsbt({
183
- commitTxResult,
184
- amount,
185
- toAddress,
186
- ...commitTxData,
187
- })
188
-
189
- const tx = finalizePsbt({ signature, commitTxData, tapLeafScript, psbt })
190
-
191
- return tx.virtualSize()
192
- }
193
-
194
- async function createRevealTx({ commitTxData, commitTxResult, toAddress, privateKey, amount }) {
195
- assert(commitTxData, `commitTxData is required`)
196
- assert(commitTxResult, `commitTxResult is required`)
197
- assert(toAddress, `toAddress is required`)
198
- assert(privateKey instanceof Buffer, `privateKey must be a Buffer`)
199
- assert(typeof amount === 'number', `amount must be a number`)
200
-
201
- const { tapLeafScript, psbt } = createPsbt({
202
- commitTxResult,
203
- amount,
204
- toAddress,
205
- ...commitTxData,
206
- })
207
-
208
- const publicKey = privateKeyToPublicKey({ privateKey, format: 'buffer' })
209
- await psbt.signInputAsync(0, toAsyncSigner({ privateKey, publicKey }))
210
-
211
- const signature = psbt.data.inputs[0].tapScriptSig[0].signature.toString('hex')
212
-
213
- const tx = finalizePsbt({ amount, signature, commitTxData, tapLeafScript, psbt })
214
-
215
- const virtualSize = tx.virtualSize()
216
- const rawTx = tx.toBuffer().toString('hex')
217
- const txId = tx.getId()
218
- const vout = 0
219
- const script = tx.outs[vout].script.toString('hex')
220
- const inscriptionId = `${txId}i0`
221
-
222
- return {
223
- txId,
224
- rawTx,
225
- inscriptionId,
226
- signature,
227
- virtualSize,
228
- vout,
229
- script,
230
- value: amount,
231
- }
232
- }
233
-
234
- const resolveMinersFee = ({ inscription, customFee, feeData, asset }) => {
235
- assert(Number.isSafeInteger(inscription.postage), 'inscription.postage must be a safe integer')
236
- const txSize = estimateTxSize({ inscription })
237
- const feePerKB = customFee || feeData.feePerKB
238
- const minersFeeBaseUnit = Math.ceil((feePerKB.toBaseNumber() * txSize) / 1000)
239
- assert(Number.isSafeInteger(minersFeeBaseUnit), 'minersFeeBaseUnit must be a safe integer')
240
- return asset.currency.baseUnit(minersFeeBaseUnit)
241
- }
242
-
243
- const broadcastInscription = async ({
244
- asset,
245
- 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
246
- receiverWalletAccount, // Optional: send the inscription to a different portfolio
247
- receiverAddress, // Optional: send the inscription to a third party wallet
248
- assetClientInterface,
249
- inscription,
250
- privateKey = randomBytes(32),
251
- customFee,
252
- }) => {
253
- assert(asset, 'asset is required')
254
- assert(walletAccount, 'walletAccount is required')
255
- assert(assetClientInterface, 'assetClientInterface is required')
256
- assert(inscription, 'inscription is required')
257
-
258
- const assetName = asset.name
259
-
260
- const resolvedReceiverWalletAccount = receiverWalletAccount || walletAccount
261
-
262
- const accountState = await assetClientInterface.getAccountState({
263
- assetName,
264
- walletAccount: resolvedReceiverWalletAccount,
265
- })
266
-
267
- const toAddress =
268
- receiverAddress ||
269
- (await assetClientInterface.getAddress({
270
- assetName,
271
- walletAccount: resolvedReceiverWalletAccount,
272
- purpose: 86,
273
- chainIndex: ordinalChainIndex,
274
- addressIndex: 0,
275
- }))
276
-
277
- const postage = inscription.postage
278
-
279
- const publicKey = privateKeyToPublicKey({ privateKey, compressed: false, format: 'buffer' })
280
- const commitTxData = createCommitTxData({ publicKey, inscription })
281
-
282
- const feeData = await assetClientInterface.getFeeConfig({ assetName })
283
-
284
- const minersFee = resolveMinersFee({ inscription, customFee, feeData, asset })
285
- const commitAmount = minersFee.add(asset.currency.baseUnit(postage))
286
-
287
- const commitTxResult = await asset.api.sendTx({
288
- asset,
289
- walletAccount,
290
- address: commitTxData.revealAddress,
291
- amount: commitAmount,
292
- options: { isRbfAllowed: false, customFee },
293
- })
294
-
295
- const revealTx = await createRevealTx({
296
- commitTxData,
297
- amount: postage,
298
- commitTxResult,
299
- toAddress,
300
- privateKey,
301
- })
302
-
303
- if (!receiverAddress && resolvedReceiverWalletAccount) {
304
- // only add the utxo
305
- const storedOrdinalsUtxos = getOrdinalsUtxos({ accountState, asset })
306
-
307
- const ordinalsUtxos = storedOrdinalsUtxos.addUtxo({
308
- txId: revealTx.txId,
309
- address: toAddress,
310
- vout: revealTx.vout,
311
- script: revealTx.script,
312
- value: asset.currency.baseUnit(revealTx.value),
313
- confirmations: 0,
314
- inscriptions: [{ inscriptionId: revealTx.inscriptionId, offset: 0 }],
315
- inscriptionIndexed: false,
316
- rbfEnabled: false,
317
- })
318
-
319
- await assetClientInterface.updateAccountState({
320
- assetName,
321
- walletAccount: resolvedReceiverWalletAccount,
322
- newData: { ordinalsUtxos },
323
- })
324
- }
325
-
326
- await asset.api.broadcastTx(revealTx.rawTx)
327
- return { ...revealTx, ...commitTxData }
328
- }
329
-
330
- const getInscriptionFees = ({
331
- accountState,
332
- asset,
333
- customFee,
334
- feeData,
335
- getFee,
336
- inscription,
337
- txSet,
338
- }) => {
339
- assert(accountState, 'accountState is required')
340
- assert(asset, 'asset is required')
341
- assert(feeData, 'feeData is required')
342
- assert(getFee, 'getFee is required')
343
- assert(inscription, 'inscription is required')
344
- assert(txSet, 'txSet is required')
345
-
346
- const minersFee = resolveMinersFee({ inscription, customFee, feeData, asset })
347
- const postageFee = asset.currency.baseUnit(inscription.postage)
348
- // Total fees: postage + fee of sending from wallet => inscribe taproot address + fee of sending inscribe taproot address => wallet
349
- const { fee: foundInscriptionFee } = getFee({
350
- asset,
351
- accountState,
352
- txSet,
353
- feeData,
354
- amount: minersFee.add(postageFee),
355
- customFee,
356
- isSendAll: false,
357
- receiveAddress: 'P2TR',
358
- })
359
-
360
- return {
361
- totalFee: foundInscriptionFee.add(minersFee).add(postageFee),
362
- foundInscriptionFee,
363
- minersFee,
364
- postageFee,
365
- }
366
- }
367
-
368
- return {
369
- createTextInscription,
370
- createBrc20Inscription,
371
- createCommitTxData,
372
- createRevealTx,
373
- broadcastInscription,
374
- estimateTxSize,
375
- getInscriptionFees,
376
- }
377
- }
@@ -1,158 +0,0 @@
1
- import lodash from 'lodash'
2
- import assert from 'minimalistic-assert'
3
-
4
- import { getInscriptionAddresses } from './get-inscription-addresses.js'
5
-
6
- const { groupBy, mapValues } = lodash
7
-
8
- const toTxLog = ({ historyItem, baseAsset, asset }) => {
9
- const amount = asset.currency.defaultUnit(historyItem.brc20Amt || 0)
10
-
11
- const isSend = historyItem.brc20Op === 'send'
12
- const isReceive = historyItem.brc20Op === 'receive'
13
- const isMint = historyItem.brc20Op === 'mint'
14
- const isTransfer = historyItem.brc20Op === 'transfer'
15
-
16
- const data = { operation: historyItem.brc20Op }
17
- return {
18
- txId: historyItem.txId,
19
- date: new Date(historyItem.createdAt),
20
- confirmations: 1,
21
- data: isSend
22
- ? {
23
- ...data,
24
- sent: [
25
- {
26
- address: historyItem.transferTo,
27
- amount: amount.toDefaultString({ unit: true }),
28
- },
29
- ],
30
- }
31
- : data,
32
- selfSend: isTransfer, // transfer is self inscribed ordinal that hasn't been sent yet
33
- from: isReceive ? [historyItem.transferFrom] : undefined,
34
- addresses: isReceive || isMint ? [historyItem.owner] : undefined,
35
- dropped: false,
36
- coinAmount: isSend ? amount.negate() : amount,
37
- coinName: asset.name,
38
- feeAmount: baseAsset.currency.defaultUnit(0), // unsure a possible value
39
- feeCoinName: baseAsset.name,
40
- currencies: { [baseAsset.name]: baseAsset.currency, [asset.name]: asset.currency },
41
- }
42
- }
43
-
44
- export const reloadBrc20TokenBalances = async ({
45
- brc20Client,
46
- assetClientInterface,
47
- walletAccount,
48
- asset,
49
- ordinalChainIndex,
50
- tickInscriptionIdIndexer,
51
- }) => {
52
- assert(brc20Client, 'brc20Client is required')
53
- assert(assetClientInterface, 'assetClientInterface is required')
54
- assert(asset, 'asset is required')
55
- assert(walletAccount, 'walletAccount is required')
56
- assert(tickInscriptionIdIndexer, 'tickInscriptionIdIndexer is required')
57
- assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
58
- const addresses = await getInscriptionAddresses({
59
- assetClientInterface,
60
- walletAccount,
61
- asset,
62
- ordinalChainIndex,
63
- })
64
-
65
- const assets = await assetClientInterface.getAssetsForNetwork({ baseAssetName: asset.name })
66
-
67
- const assetByAssetId = Object.values(assets)
68
- .filter((asset) => asset.assetId)
69
- .reduce((map, token) => {
70
- map.set(token.assetId, token)
71
- return map
72
- }, new Map())
73
-
74
- const unknownDeployInscriptionIds = new Set()
75
-
76
- const historyLists = await Promise.all(
77
- addresses.map(async (address) => {
78
- const tokensHistoryList = await brc20Client.getTokenTransactionHistory({ address })
79
- const history = await Promise.all(
80
- tokensHistoryList.map(async (token) => {
81
- const deployInscriptionId = await tickInscriptionIdIndexer.getDeployInscriptionId(
82
- token.brc20Tick
83
- )
84
- const assetName = assetByAssetId.get(deployInscriptionId)?.name
85
- if (assetName) {
86
- return { ...token, address, assetName, deployInscriptionId }
87
- }
88
-
89
- unknownDeployInscriptionIds.add(deployInscriptionId)
90
- })
91
- )
92
- return history.filter(Boolean)
93
- })
94
- )
95
- const brc20History = historyLists.flat()
96
-
97
- const eventsByAssetNameAndAddress = mapValues(
98
- groupBy(brc20History, (event) => event.assetName),
99
- (anotherList) => groupBy(anotherList, (event) => event.address)
100
- )
101
-
102
- const brc20Balances = mapValues(eventsByAssetNameAndAddress, (eventsByAddress) => {
103
- return mapValues(eventsByAddress, (events) => {
104
- const { brc20OwnerAvailableBalance, brc20OwnerTransferBalance, brc20Tick } = events[0]
105
-
106
- const sentList = new Set(
107
- events.filter((event) => event.brc20Op === 'send').map((event) => event.inscriptionId)
108
- )
109
-
110
- const transferableList = events
111
- .filter((event) => event.brc20Op === 'transfer')
112
- .map((event) => {
113
- return {
114
- inscriptionId: event.inscriptionId,
115
- inscriptionNumber: event.inscriptionNumber,
116
- brc20Amt: event.brc20Amt,
117
- txId: event.txId,
118
- sent: sentList.has(event.inscriptionId),
119
- }
120
- })
121
- return {
122
- brc20Tick,
123
- brc20OwnerAvailableBalance,
124
- brc20OwnerTransferBalance,
125
- brc20OwnerTotalBalance: brc20OwnerAvailableBalance + brc20OwnerTransferBalance,
126
- transferableList,
127
- }
128
- })
129
- })
130
-
131
- const allLogItems = brc20History
132
- .filter(({ assetName }) => assetName)
133
- .map((historyItem) => {
134
- return toTxLog({ historyItem, baseAsset: asset, asset: assets[historyItem.assetName] })
135
- })
136
-
137
- const logItemsByAsset = groupBy(allLogItems, 'coinName')
138
-
139
- await Promise.all(
140
- Object.entries(logItemsByAsset).map(([assetName, txs]) => {
141
- return assetClientInterface.updateTxLogAndNotify({
142
- assetName,
143
- walletAccount,
144
- txs,
145
- })
146
- })
147
- )
148
-
149
- await assetClientInterface.updateAccountState({
150
- assetName: asset.name,
151
- walletAccount,
152
- newData: { brc20Balances },
153
- })
154
-
155
- return {
156
- unknownDeployInscriptionIds: [...unknownDeployInscriptionIds],
157
- }
158
- }
@@ -1,49 +0,0 @@
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.token.id
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
-
45
- return getBrc20Tick(deployInscriptionId)
46
- }
47
-
48
- return { getBrc20TickFromAsset, getDeployInscriptionId, getBrc20Tick }
49
- }