@exodus/bitcoin-plugin 1.3.0 → 1.4.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.
Files changed (39) hide show
  1. package/jest.config.js +7 -0
  2. package/package.json +2 -3
  3. package/src/__tests__/address.test.js +142 -0
  4. package/src/__tests__/balances.test.js +67 -0
  5. package/src/__tests__/bitcoin-private-seed-safe-report.json +2754 -0
  6. package/src/__tests__/bitcoin-signing.test.js +184 -0
  7. package/src/__tests__/fee-data.test.js +61 -0
  8. package/src/__tests__/fee-estimator.test.js +174 -0
  9. package/src/__tests__/fixtures/segwit-all-unsigned-tx.js +87 -0
  10. package/src/__tests__/fixtures/segwit-legacy-change-unsigned-tx.js +38 -0
  11. package/src/__tests__/fixtures/segwit-segwit-change-unsigned-tx.js +96 -0
  12. package/src/__tests__/fixtures/taproot-15000sats-unsigned-tx.js +149 -0
  13. package/src/__tests__/fixtures/taproot-all-unsigned-tx.js +231 -0
  14. package/src/__tests__/fixtures/taproot-unsigned-tx.js +85 -0
  15. package/src/__tests__/get-size.test.js +71 -0
  16. package/src/__tests__/index.test.js +65 -0
  17. package/src/__tests__/keys.test.js +97 -0
  18. package/src/__tests__/monitor.integration.test.js +170 -0
  19. package/src/__tests__/move-funds.test.js +408 -0
  20. package/src/__tests__/parse-unsigned-tx.test.js +46 -0
  21. package/src/__tests__/reports/unit-test-safe-report.json +2790 -0
  22. package/src/__tests__/send-tx.test.js +145 -0
  23. package/src/__tests__/sign-tx.test.js +32 -0
  24. package/src/__tests__/unsigned-btclike-desktop.json +40 -0
  25. package/src/__tests__/wallet.test.js +78 -0
  26. package/src/create-asset.js +59 -7
  27. package/src/ordinals/__tests__/brc-20-client.integration.test.js +86 -0
  28. package/src/ordinals/__tests__/brc-20-utils.test.js +165 -0
  29. package/src/ordinals/__tests__/fixtures/inscriptions-send-usigned-tx.js +125 -0
  30. package/src/ordinals/__tests__/fixtures/nft-send-usigned-tx.js +97 -0
  31. package/src/ordinals/__tests__/monitor-ordinals-enabled-safe-report-with-inscriptions.json +2908 -0
  32. package/src/ordinals/__tests__/monitor-ordinals-enabled-safe-report.json +2906 -0
  33. package/src/ordinals/__tests__/monitor-ordinals-enabled.integration.test.js +16 -0
  34. package/src/ordinals/__tests__/nfts-api.test.js +221 -0
  35. package/src/ordinals/__tests__/ordinals-send-tx.test.js +103 -0
  36. package/src/ordinals/brc-20-balances-and-fee-adapter.js +41 -0
  37. package/src/ordinals/brc-20-utils.js +79 -0
  38. package/src/ordinals/create-token-factory.js +30 -0
  39. package/src/ordinals/reload-brc20-token-balances.js +154 -0
@@ -0,0 +1,16 @@
1
+ import { createAsset } from '../../index'
2
+
3
+ import { getPrivateSeed, monitorIntegrationTester } from '@exodus/assets-testing'
4
+ import * as path from 'path'
5
+ const asset = createAsset({ ordinalChainIndex: 2, ordinalsEnabled: true })
6
+
7
+ const safeReportFile = path.join(__dirname, 'monitor-ordinals-enabled-safe-report.json')
8
+ const walletAccountCount = 4
9
+ describe(`bitcoin with ordinals enabled integration test`, () => {
10
+ monitorIntegrationTester({
11
+ asset,
12
+ seed: getPrivateSeed(),
13
+ walletAccountCount,
14
+ safeReportFile,
15
+ })
16
+ })
@@ -0,0 +1,221 @@
1
+ import { createAsset } from '../../index'
2
+ import { getPrivateSeed, walletTester } from '@exodus/assets-testing'
3
+ import path from 'path'
4
+ const asset = createAsset({ ordinalChainIndex: 2, ordinalsEnabled: true })
5
+
6
+ const beforeSafeReportFile = path.join(__dirname, './monitor-ordinals-enabled-safe-report.json')
7
+ const afterSafeReportFile = path.join(
8
+ __dirname,
9
+ './monitor-ordinals-enabled-safe-report-with-inscriptions.json'
10
+ )
11
+
12
+ describe(`bitcoin.nfts enabled can update utxos`, () => {
13
+ walletTester({
14
+ asset,
15
+ seed: getPrivateSeed(),
16
+ walletAccountCount: 4,
17
+ importSafeReportFile: beforeSafeReportFile,
18
+ tests: {
19
+ 'load all nfts from proxy server': async ({ assetClientInterface, assertSafeReport }) => {
20
+ const walletAccount = 'exodus_1'
21
+
22
+ // forcing setting up aci in nfts
23
+ asset.api.createHistoryMonitor({ asset, assetClientInterface })
24
+
25
+ const addresses = await asset.api.nfts.getNftsAddresses({
26
+ assetClientInterface,
27
+ walletAccount: walletAccount,
28
+ })
29
+ expect(addresses).toEqual([
30
+ 'bc1pe59l2tsfe6t5x6wrcgtsaxy3nrpnky8chq4cvf7zndat99f8t4xsetgm4w',
31
+ 'bc1pkhrae7jrlj3wnz0vpm09tffndpu40vh6y4tl42pt2zdhfms575msdfwuew',
32
+ 'bc1qgxz38crda20mlre427ygezgu67kqvqfr4heayn',
33
+ 'bc1qux2sjzksvgzwu2wdlvgtm8ggfp0azwff53yar6',
34
+ 'bc1qpk5g380fe5u0tfd8gz9h3lsga402q49kf2c5ny',
35
+ ])
36
+ // const proxy = new NftsProxyApi({ baseUrl: 'https://nfts-proxy-d.exodus.io/v2' })
37
+ // const nfts = (
38
+ // await Promise.all(addresses.map((address) => proxy.api.bitcoin.getNftsByOwner(address)))
39
+ // ).flat(
40
+ //
41
+ const nfts = [
42
+ {
43
+ network: 'bitcoin',
44
+ attributes: [],
45
+ collectionName: '',
46
+ image:
47
+ 'https://fetch-n-cache.a.exodus.io/?url=https%3A%2F%2Ford-mirror.magiceden.dev%2Fcontent%2F45199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0&maxage=2678400&apikey=nftproxy_zDKMFoRw6e8xrWCmXNccium43xLz4xxt9vWNBCfHMr',
48
+ name: '#7010622',
49
+ number: 7010622,
50
+ owner: 'bc1pe59l2tsfe6t5x6wrcgtsaxy3nrpnky8chq4cvf7zndat99f8t4xsetgm4w',
51
+ id: 'bitcoin:45199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
52
+ tokenId: '45199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
53
+ contentType: 'text/plain;charset=utf-8',
54
+ output: 'fad4bdad739a21e409b5d3e0c3a9d5fb1ac188cd1ec9b172ee8912dde7063c91:0',
55
+ inscriptionNumber: 7010622,
56
+ },
57
+ {
58
+ network: 'bitcoin',
59
+ attributes: [],
60
+ number: 7010623,
61
+ owner: 'bc1qpk5g380fe5u0tfd8gz9h3lsga402q49kf2c5ny',
62
+ id: 'bitcoin:11199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
63
+ tokenId: '11199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
64
+ contentType: 'text/plain;charset=utf-8',
65
+ output: 'd2627ebefccc448fea0dfaa8e8b365f3d96f3fc32c0551ed539f4329312e54ad:1',
66
+ inscriptionNumber: 7010622,
67
+ },
68
+ {
69
+ network: 'bitcoin',
70
+ attributes: [],
71
+ number: 7010624,
72
+ owner: 'bc1qpk5g380fe5u0tfd8gz9h3lsga402q49kf2c5ny',
73
+ id: 'bitcoin:22299d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
74
+ tokenId: '22299d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
75
+ contentType: 'text/plain;charset=utf-8',
76
+ output: '1111ebefccc448fea0dfaa8e8b365f3d96f3fc32c0551ed539f4329312e54ad:1', // Utxos is not in the list! AKA Ordinal NFTs in transit out
77
+ inscriptionNumber: 7010622,
78
+ },
79
+ ]
80
+
81
+ const assetName = asset.name
82
+ const beforeAccountState = await assetClientInterface.getAccountState({
83
+ walletAccount,
84
+ assetName: assetName,
85
+ })
86
+
87
+ expect(beforeAccountState.utxos.toJSON()).toEqual({
88
+ bc1qgxz38crda20mlre427ygezgu67kqvqfr4heayn: {
89
+ address: 'bc1qgxz38crda20mlre427ygezgu67kqvqfr4heayn',
90
+ path: 'm/0/0',
91
+ utxos: [
92
+ {
93
+ confirmations: 1,
94
+ rbfEnabled: true,
95
+ script: '0014418513e06dea9fbf8f3557888c891cd7ac060123',
96
+ txId: '4be8bec21742975ffa27145d6683637c2bc8e8ad7b29bedfdb013a844603bbac',
97
+ value: '0.00933282 BTC',
98
+ vout: 0,
99
+ },
100
+ ],
101
+ },
102
+ bc1qpk5g380fe5u0tfd8gz9h3lsga402q49kf2c5ny: {
103
+ address: 'bc1qpk5g380fe5u0tfd8gz9h3lsga402q49kf2c5ny',
104
+ path: 'm/1/3',
105
+ utxos: [
106
+ {
107
+ confirmations: 1,
108
+ script: '00140da8889de9cd38f5a5a7408b78fe08ed5ea054b6',
109
+ txId: 'd2627ebefccc448fea0dfaa8e8b365f3d96f3fc32c0551ed539f4329312e54ad',
110
+ value: '0.00083929 BTC',
111
+ vout: 1,
112
+ },
113
+ ],
114
+ },
115
+ bc1qux2sjzksvgzwu2wdlvgtm8ggfp0azwff53yar6: {
116
+ address: 'bc1qux2sjzksvgzwu2wdlvgtm8ggfp0azwff53yar6',
117
+ path: 'm/1/0',
118
+ utxos: [
119
+ {
120
+ confirmations: 1,
121
+ rbfEnabled: true,
122
+ script: '0014e195090ad06204ee29cdfb10bd9d08485fd13929',
123
+ txId: '43771d0143ccfd5df0e5784127e4e54b40bc93172ff6ffab311ffec9abfe9ebc',
124
+ value: '0.00210842 BTC',
125
+ vout: 2,
126
+ },
127
+ ],
128
+ },
129
+ })
130
+ expect(beforeAccountState.ordinalsUtxos.toJSON()).toEqual({
131
+ bc1pe59l2tsfe6t5x6wrcgtsaxy3nrpnky8chq4cvf7zndat99f8t4xsetgm4w: {
132
+ address: 'bc1pe59l2tsfe6t5x6wrcgtsaxy3nrpnky8chq4cvf7zndat99f8t4xsetgm4w',
133
+ path: 'm/2/0',
134
+ utxos: [
135
+ {
136
+ confirmations: 1,
137
+ rbfEnabled: true,
138
+ script: '5120cd0bf52e09ce974369c3c2170e989198c33b10f8b82b8627c29b7ab295275d4d',
139
+ txId: 'fad4bdad739a21e409b5d3e0c3a9d5fb1ac188cd1ec9b172ee8912dde7063c91',
140
+ value: '0.00006673 BTC',
141
+ vout: 0,
142
+ },
143
+ ],
144
+ },
145
+ })
146
+
147
+ const postProcessedNfts = await asset.api.nfts.postProcessNfts({ nfts, walletAccount })
148
+ expect(postProcessedNfts).toEqual(nfts.slice(0, 2))
149
+
150
+ const afterAccountState = await assetClientInterface.getAccountState({
151
+ walletAccount,
152
+ assetName: assetName,
153
+ })
154
+
155
+ expect(afterAccountState.utxos.toJSON()).toEqual({
156
+ bc1qgxz38crda20mlre427ygezgu67kqvqfr4heayn: {
157
+ address: 'bc1qgxz38crda20mlre427ygezgu67kqvqfr4heayn',
158
+ path: 'm/0/0',
159
+ utxos: [
160
+ {
161
+ confirmations: 1,
162
+ rbfEnabled: true,
163
+ script: '0014418513e06dea9fbf8f3557888c891cd7ac060123',
164
+ txId: '4be8bec21742975ffa27145d6683637c2bc8e8ad7b29bedfdb013a844603bbac',
165
+ value: '0.00933282 BTC',
166
+ vout: 0,
167
+ },
168
+ ],
169
+ },
170
+ bc1qux2sjzksvgzwu2wdlvgtm8ggfp0azwff53yar6: {
171
+ address: 'bc1qux2sjzksvgzwu2wdlvgtm8ggfp0azwff53yar6',
172
+ path: 'm/1/0',
173
+ utxos: [
174
+ {
175
+ confirmations: 1,
176
+ rbfEnabled: true,
177
+ script: '0014e195090ad06204ee29cdfb10bd9d08485fd13929',
178
+ txId: '43771d0143ccfd5df0e5784127e4e54b40bc93172ff6ffab311ffec9abfe9ebc',
179
+ value: '0.00210842 BTC',
180
+ vout: 2,
181
+ },
182
+ ],
183
+ },
184
+ })
185
+ expect(afterAccountState.ordinalsUtxos.toJSON()).toEqual({
186
+ bc1pe59l2tsfe6t5x6wrcgtsaxy3nrpnky8chq4cvf7zndat99f8t4xsetgm4w: {
187
+ address: 'bc1pe59l2tsfe6t5x6wrcgtsaxy3nrpnky8chq4cvf7zndat99f8t4xsetgm4w',
188
+ path: 'm/2/0',
189
+ utxos: [
190
+ {
191
+ confirmations: 1,
192
+ inscriptionId: '45199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
193
+ rbfEnabled: true,
194
+ script: '5120cd0bf52e09ce974369c3c2170e989198c33b10f8b82b8627c29b7ab295275d4d',
195
+ txId: 'fad4bdad739a21e409b5d3e0c3a9d5fb1ac188cd1ec9b172ee8912dde7063c91',
196
+ value: '0.00006673 BTC',
197
+ vout: 0,
198
+ },
199
+ ],
200
+ },
201
+ bc1qpk5g380fe5u0tfd8gz9h3lsga402q49kf2c5ny: {
202
+ address: 'bc1qpk5g380fe5u0tfd8gz9h3lsga402q49kf2c5ny',
203
+ path: 'm/1/3',
204
+ utxos: [
205
+ {
206
+ confirmations: 1,
207
+ inscriptionId: '11199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
208
+ script: '00140da8889de9cd38f5a5a7408b78fe08ed5ea054b6',
209
+ txId: 'd2627ebefccc448fea0dfaa8e8b365f3d96f3fc32c0551ed539f4329312e54ad',
210
+ value: '0.00083929 BTC',
211
+ vout: 1,
212
+ },
213
+ ],
214
+ },
215
+ })
216
+
217
+ await assertSafeReport({ safeReportFile: afterSafeReportFile, override: false })
218
+ },
219
+ },
220
+ })
221
+ })
@@ -0,0 +1,103 @@
1
+ import shuffle from 'lodash/shuffle'
2
+
3
+ import { createAsset } from '../../index'
4
+ import { getPrivateSeed, walletTester } from '@exodus/assets-testing'
5
+ import path from 'path'
6
+
7
+ import { getSchnorrEntropy } from '@exodus/bitcoin-api/src/tx-sign/default-entropy'
8
+
9
+ import { sendTxTest } from '@exodus/bitcoin-api/src/__tests__/tx-send-testing-utils'
10
+ import inscriptionsSendUsignedTx from './fixtures/inscriptions-send-usigned-tx'
11
+ import nftSendUsignedTx from './fixtures/nft-send-usigned-tx'
12
+
13
+ const asset = createAsset({ ordinalChainIndex: 2, ordinalsEnabled: true, brc20Enabled: true })
14
+
15
+ // Tell jest to mock this import
16
+ jest.mock('lodash/shuffle')
17
+ jest.mock('@exodus/bitcoin-api/src/insight-api-client/index')
18
+ jest.mock('@exodus/bitcoin-api/src/tx-sign/default-entropy')
19
+
20
+ // avoid shuffle so order and tx hash can be asserted
21
+ shuffle.mockImplementation((list) => {
22
+ return list
23
+ })
24
+
25
+ getSchnorrEntropy.mockImplementation(() => {
26
+ return Buffer.from('1230000000000000000000000000000000000000000000000000000000000000', 'hex')
27
+ })
28
+
29
+ const importSafeReportFile = path.join(
30
+ __dirname,
31
+ './monitor-ordinals-enabled-safe-report-with-inscriptions.json'
32
+ )
33
+
34
+ describe(`bitcoin inscriptions tx-send test`, () => {
35
+ beforeEach(() => {
36
+ jest.spyOn(asset.api, 'signTx')
37
+ asset.insightClient.fetchBlockHeight.mockImplementation(async () => {
38
+ return 768520
39
+ })
40
+ })
41
+
42
+ afterEach(() => {
43
+ jest.clearAllMocks()
44
+ jest.restoreAllMocks()
45
+ })
46
+
47
+ walletTester({
48
+ asset,
49
+ seed: getPrivateSeed(),
50
+ importSafeReportFile,
51
+ walletAccountCount: 4,
52
+ tests: {
53
+ 'can send 2 inscriptions from wallet 1': async ({ assetClientInterface, asset }) => {
54
+ const address = 'bc1pkhrae7jrlj3wnz0vpm09tffndpu40vh6y4tl42pt2zdhfms575msdfwuew'
55
+
56
+ const expectedBalance = asset.currency.parse('1136644 satoshis')
57
+ const expectedFee = asset.currency.parse('13328 satoshis')
58
+
59
+ // sending 2 transfer of a brc20
60
+ const brc20 = {
61
+ inscriptionIds: [
62
+ '11199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
63
+ '45199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
64
+ ],
65
+ }
66
+
67
+ const params = {
68
+ assetClientInterface,
69
+ asset,
70
+ address,
71
+ options: { multipleAddressesEnabled: false, isSendAll: false, brc20 },
72
+ expectedBalance,
73
+ expectedFee,
74
+ expectedTxData: inscriptionsSendUsignedTx,
75
+ }
76
+ await sendTxTest(params)
77
+ },
78
+
79
+ 'can send 1 nft from wallet 1': async ({ assetClientInterface, asset }) => {
80
+ const address = 'bc1pkhrae7jrlj3wnz0vpm09tffndpu40vh6y4tl42pt2zdhfms575msdfwuew'
81
+
82
+ const expectedBalance = asset.currency.parse('1136644 satoshis')
83
+ const expectedFee = asset.currency.parse('10404 satoshis')
84
+
85
+ // sending 2 transfer of a brc20
86
+ const nft = {
87
+ tokenId: '11199d28c76a6d2b82c35772ed4d1d7b5156dfe7aa385490ac0799c95187038fi0',
88
+ }
89
+
90
+ const params = {
91
+ assetClientInterface,
92
+ asset,
93
+ address,
94
+ options: { multipleAddressesEnabled: false, isSendAll: false, nft },
95
+ expectedBalance,
96
+ expectedFee,
97
+ expectedTxData: nftSendUsignedTx,
98
+ }
99
+ await sendTxTest(params)
100
+ },
101
+ },
102
+ })
103
+ })
@@ -0,0 +1,41 @@
1
+ import assert from 'minimalistic-assert'
2
+ import { BumpType } from '@exodus/bitcoin-lib/lib/selectors/get-can-bump-tx-factory'
3
+ import { brc20Utils } from './brc-20-utils'
4
+
5
+ export const brc20BalancesAndFeeAdapterFactory = ({
6
+ getBalances,
7
+ getFee,
8
+ getAvailableBalance,
9
+ canBumpTx,
10
+ getSpendableBalance,
11
+ }) => {
12
+ assert(getBalances, 'getBalances is required')
13
+ assert(getFee, 'getFee is required')
14
+ assert(getAvailableBalance, 'getAvailableBalance is required')
15
+ assert(canBumpTx, 'canBumpTx is required')
16
+ assert(getSpendableBalance, 'getSpendableBalance is required')
17
+
18
+ const { isToken, getTokenBalance } = brc20Utils
19
+
20
+ return {
21
+ canBumpTx: (args) => {
22
+ return isToken(args) ? { bumpType: BumpType.NONE } : canBumpTx(args)
23
+ },
24
+
25
+ getSpendableBalance: (args) => {
26
+ return isToken(args) ? getTokenBalance(args) : getSpendableBalance(args)
27
+ },
28
+
29
+ getFee: (args) => {
30
+ return isToken(args) ? getFee({ ...args, asset: args.asset.baseAsset }) : getFee(args)
31
+ },
32
+
33
+ getAvailableBalance: (args) => {
34
+ return isToken(args) ? getTokenBalance(args) : getAvailableBalance(args)
35
+ },
36
+
37
+ getBalances: (args) => {
38
+ return isToken(args) ? { balance: getTokenBalance(args) } : getBalances(args)
39
+ },
40
+ }
41
+ }
@@ -0,0 +1,79 @@
1
+ import assert from 'minimalistic-assert'
2
+ import { getOrdinalsUtxos } from '@exodus/bitcoin-api'
3
+ import { sumBy } from 'lodash'
4
+
5
+ export const brc20Utils = {
6
+ getKnownInscriptionIds: ({ asset, accountState }) => {
7
+ assert(accountState, 'accountState is required')
8
+ assert(asset, 'asset is required')
9
+ return getOrdinalsUtxos({ accountState, asset })
10
+ .toArray()
11
+ .map((utxo) => utxo.inscriptionId)
12
+ },
13
+
14
+ getAllTransferableList: ({ accountState, asset }) => {
15
+ assert(accountState, 'accountState is required')
16
+ assert(asset, 'asset is required')
17
+ const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
18
+ return assetBalances
19
+ .flatMap((item) => item.transferableList)
20
+ .map((item) => ({
21
+ inscriptionId: item.inscriptionId,
22
+ txId: item.txId,
23
+ amount: asset.currency.defaultUnit(item.brc20Amt),
24
+ }))
25
+ },
26
+
27
+ getTransferableList: ({ asset, accountState }) => {
28
+ const knownInscriptionIds = brc20Utils.getKnownInscriptionIds({ asset, accountState })
29
+ const transferableList = brc20Utils.getAllTransferableList({ asset, accountState })
30
+ // return the list of transferable inscription items that we hold of the utxos
31
+ return transferableList.filter((item) => knownInscriptionIds.includes(item.inscriptionId))
32
+ },
33
+
34
+ getInTransitBalance: ({ asset, accountState }) => {
35
+ const knownInscriptionIds = brc20Utils.getKnownInscriptionIds({ asset, accountState })
36
+ const transferableList = brc20Utils.getAllTransferableList({ asset, accountState })
37
+ return transferableList
38
+ .filter((item) => !knownInscriptionIds.includes(item.inscriptionId))
39
+ .reduce((amount, item) => amount.add(item.amount), asset.currency.ZERO)
40
+ },
41
+
42
+ isToken: ({ asset }) => {
43
+ assert(asset, 'asset must be provided')
44
+ return asset.name !== asset.baseAsset.name
45
+ },
46
+
47
+ getTokenBalance: ({ asset, accountState }) => {
48
+ assert(asset, 'asset must be provided')
49
+ assert(accountState, 'accountState must be provided')
50
+ assert(brc20Utils.isToken({ asset }), `${asset.name} is must be a token`)
51
+ const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
52
+ const sum = sumBy(assetBalances, 'brc20OwnerTotalBalance')
53
+ return asset.currency
54
+ .defaultUnit(sum || 0)
55
+ .sub(brc20Utils.getInTransitBalance({ asset, accountState }))
56
+ .clampLowerZero()
57
+ },
58
+
59
+ getAvailableBalance: ({ asset, accountState }) => {
60
+ assert(asset, 'asset must be provided')
61
+ assert(accountState, 'accountState must be provided')
62
+ assert(brc20Utils.isToken({ asset }), `${asset.name} is must be a token`)
63
+ const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
64
+ const sum = sumBy(assetBalances, 'brc20OwnerAvailableBalance')
65
+ return asset.currency.defaultUnit(sum || 0)
66
+ },
67
+
68
+ getTransferableBalance: ({ asset, accountState }) => {
69
+ assert(asset, 'asset must be provided')
70
+ assert(accountState, 'accountState must be provided')
71
+ assert(brc20Utils.isToken({ asset }), `${asset.name} is must be a token`)
72
+ const assetBalances = Object.values(accountState?.brc20Balances?.[asset.name] || {})
73
+ const sum = sumBy(assetBalances, 'brc20OwnerTransferBalance')
74
+ return asset.currency
75
+ .defaultUnit(sum || 0)
76
+ .sub(brc20Utils.getInTransitBalance({ asset, accountState }))
77
+ .clampLowerZero()
78
+ },
79
+ }
@@ -0,0 +1,30 @@
1
+ function validateAssetId(assetId) {
2
+ if (typeof assetId !== 'string') return false
3
+ const rgx = /^[A-Za-z0-9]{4}$/ // 4 letters/numbers tickers
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
+ return {
23
+ validateAssetId,
24
+ createToken,
25
+ getTokens: () =>
26
+ Object.values(networkAssets)
27
+ .filter((asset) => asset.name !== asset.baseAsset.name)
28
+ .map(createToken),
29
+ }
30
+ }
@@ -0,0 +1,154 @@
1
+ import assert from 'minimalistic-assert'
2
+ import { getInscriptionAddresses } from './get-inscription-addresses'
3
+ import { groupBy, mapValues } from 'lodash'
4
+ import { updateAccountStateUtxos } from './ordinals-account-state-utils'
5
+ const toTxLog = ({ historyItem, baseAsset, asset }) => {
6
+ const amount = asset.currency.defaultUnit(historyItem.brc20Amt || 0)
7
+
8
+ const isSend = historyItem.brc20Op === 'send'
9
+ const isReceive = historyItem.brc20Op === 'receive'
10
+
11
+ const data = { nftId: historyItem.inscriptionId, operation: historyItem.brc20Op }
12
+ return {
13
+ txId: historyItem.txId,
14
+ date: new Date(historyItem.createdAt),
15
+ confirmations: 1,
16
+ data: isSend
17
+ ? {
18
+ ...data,
19
+ sent: [
20
+ {
21
+ address: historyItem.owner, // not right probably
22
+ amount: amount,
23
+ },
24
+ ],
25
+ }
26
+ : data,
27
+ from: isReceive ? [historyItem.owner] : undefined, // from is wrong!!! Unknown the from!!!
28
+ addresses: isReceive ? [historyItem.address] : undefined,
29
+ dropped: false,
30
+ coinAmount: amount,
31
+ coinName: asset.name,
32
+ feeAmount: baseAsset.currency.defaultUnit(0), // unsure a possible value
33
+ feeCoinName: baseAsset.name,
34
+ currencies: { [baseAsset.name]: baseAsset.currency, [asset.name]: asset.currency },
35
+ }
36
+ }
37
+
38
+ export const reloadBrc20TokenBalances = async ({
39
+ brc20Client,
40
+ assetClientInterface,
41
+ walletAccount,
42
+ asset,
43
+ ordinalChainIndex,
44
+ }) => {
45
+ assert(brc20Client, 'brc20Client is required')
46
+ assert(assetClientInterface, 'assetClientInterface is required')
47
+ assert(asset, 'asset is required')
48
+ assert(walletAccount, 'walletAccount is required')
49
+ assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
50
+ const addresses = await getInscriptionAddresses({
51
+ assetClientInterface,
52
+ walletAccount,
53
+ asset,
54
+ ordinalChainIndex,
55
+ })
56
+
57
+ const assets = await assetClientInterface.getAssetsForNetwork({ baseAssetName: asset.name })
58
+
59
+ const assetByAssetId = Object.values(assets)
60
+ .filter((asset) => asset.assetId)
61
+ .reduce((map, token) => {
62
+ map.set(token.assetId, token)
63
+ return map
64
+ }, new Map())
65
+
66
+ const unknownBrc20Ticks = new Set()
67
+ const knownInscriptionIds = new Set()
68
+
69
+ const brc20History = (
70
+ await Promise.all(
71
+ addresses.map(async (address) => {
72
+ const tokensHistoryList = await brc20Client.getTokenTransactionHistory({ owner: address })
73
+ return tokensHistoryList
74
+ .map((token) => {
75
+ knownInscriptionIds.add(token.inscriptionId.toLowerCase())
76
+ const assetName = assetByAssetId.get(token.brc20Tick)?.name
77
+ if (assetName) {
78
+ return { ...token, address, assetName }
79
+ } else {
80
+ unknownBrc20Ticks.add(token.brc20Tick)
81
+ return undefined
82
+ }
83
+ })
84
+ .filter(Boolean)
85
+ })
86
+ )
87
+ ).flat()
88
+
89
+ const eventsByAssetNameAndAddress = mapValues(
90
+ groupBy(brc20History, (event) => event.assetName),
91
+ (anotherList) => groupBy(anotherList, (event) => event.address)
92
+ )
93
+
94
+ const brc20Balances = mapValues(eventsByAssetNameAndAddress, (eventsByAddress) => {
95
+ return mapValues(eventsByAddress, (events) => {
96
+ const { brc20OwnerAvailableBalance, brc20OwnerTransferBalance, brc20Tick } = events[0]
97
+
98
+ const sentList = events
99
+ .filter((event) => event.brc20Op === 'send')
100
+ .map((event) => event.inscriptionId)
101
+
102
+ const transferableList = events
103
+ .filter((event) => event.brc20Op === 'transfer' && !sentList.includes(event.inscriptionId))
104
+ .map((event) => {
105
+ return {
106
+ inscriptionId: event.inscriptionId,
107
+ inscriptionNumber: event.inscriptionNumber,
108
+ brc20Amt: event.brc20Amt,
109
+ txId: event.txId,
110
+ }
111
+ })
112
+ return {
113
+ brc20Tick,
114
+ brc20OwnerAvailableBalance,
115
+ brc20OwnerTransferBalance,
116
+ brc20OwnerTotalBalance: brc20OwnerAvailableBalance + brc20OwnerTransferBalance,
117
+ transferableList,
118
+ }
119
+ })
120
+ })
121
+
122
+ const allLogItems = brc20History
123
+ .filter(({ assetName }) => assetName)
124
+ .map((historyItem) => {
125
+ return toTxLog({ historyItem, baseAsset: asset, asset: assets[historyItem.assetName] })
126
+ })
127
+
128
+ const logItemsByAsset = groupBy(allLogItems, 'coinName')
129
+
130
+ await Promise.all(
131
+ Object.entries(logItemsByAsset).map(([assetName, txs]) => {
132
+ return assetClientInterface.updateTxLogAndNotify({
133
+ assetName,
134
+ walletAccount,
135
+ txs,
136
+ })
137
+ })
138
+ )
139
+
140
+ await updateAccountStateUtxos({
141
+ asset,
142
+ walletAccount,
143
+ assetClientInterface,
144
+ knownInscriptionIds: [...knownInscriptionIds],
145
+ ordinalChainIndex,
146
+ moreNewData: {
147
+ brc20Balances,
148
+ },
149
+ })
150
+
151
+ return {
152
+ unknownBrc20Ticks: [...unknownBrc20Ticks],
153
+ }
154
+ }