@exodus/bitcoin-plugin 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-plugin",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "description": "Exodus bitcoin-plugin",
5
5
  "main": "src/index.js",
6
6
  "files": [
@@ -19,11 +19,13 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@exodus/asset-lib": "^3.7.1",
22
- "@exodus/bitcoin-api": "^2.4.1",
22
+ "@exodus/bitcoin-api": "^2.5.0",
23
23
  "@exodus/bitcoin-lib": "^2.2.8",
24
+ "bitcoinjs-lib": "^6.1.5",
24
25
  "minimalistic-assert": "^1.0.1"
25
26
  },
26
27
  "devDependencies": {
27
28
  "@exodus/keychain": "^3.0.0"
28
- }
29
+ },
30
+ "gitHead": "d7b87308c1645a96ba4451f0b40b08ae3c1c29e5"
29
31
  }
@@ -1,5 +1,5 @@
1
1
  import _coinInfo from 'coininfo'
2
- import * as bitcoinjsLib from '@exodus/bitcoinjs-lib'
2
+ import * as bitcoinjsLib from 'bitcoinjs-lib'
3
3
  import createGetKeyIdentifier from '@exodus/bitcoin-lib/lib/key-identifier'
4
4
 
5
5
  import bip44Constants from '@exodus/bip44-constants/by-ticker'
@@ -8,7 +8,6 @@ import {
8
8
  createBitcoinMonitor,
9
9
  createBtcLikeAddress,
10
10
  createBtcLikeKeys,
11
- eccFactory,
12
11
  getBalancesFactory,
13
12
  getAddressesFromPrivateKeyFactory,
14
13
  getBtcVersions,
@@ -30,6 +29,7 @@ import { brc20ApiClientFactory } from './ordinals/brc-20-client'
30
29
  import { nftsApiFactory } from './ordinals/nfts'
31
30
  import { brc20BalancesAndFeeAdapterFactory } from './ordinals/brc-20-balances-and-fee-adapter'
32
31
  import { parseCurrency } from '@exodus/bitcoin-api/src/fee/fee-utils'
32
+ import { inscriptionsServiceFactory } from './ordinals/inscriptions-service'
33
33
 
34
34
  export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) => ({
35
35
  allowUnconfirmedRbfEnabledUtxos = false,
@@ -51,18 +51,15 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
51
51
  const useBip84 = true
52
52
  const useBip86 = true
53
53
 
54
- const ecc = eccFactory()
55
-
56
54
  const versions = getBtcVersions(coinInfo)
57
55
  const address = createBtcLikeAddress({
58
56
  versions,
59
57
  coinInfo,
60
58
  useBip86,
61
59
  bitcoinjsLib,
62
- ecc,
63
60
  })
64
61
 
65
- const keys = createBtcLikeKeys({ coinInfo, versions, useBip86, ecc })
62
+ const keys = createBtcLikeKeys({ coinInfo, versions, useBip86 })
66
63
  const bip44 = bip44Constants['BTC']
67
64
 
68
65
  const allowedPurposes = [44, 49, 84, 86]
@@ -80,7 +77,6 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
80
77
  }
81
78
 
82
79
  const getFeeEstimator = getFeeEstimatorFactory({
83
- ecc,
84
80
  defaultOutputType: 'P2WSH',
85
81
  addressApi: address,
86
82
  })
@@ -97,21 +93,39 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
97
93
  getSpendableBalance: baseFeeResolver.getSpendableBalance,
98
94
  })
99
95
 
100
- const { getFee, getBalances, getAvailableBalance, canBumpTx, getSpendableBalance } = brc20Enabled
101
- ? brc20BalancesAndFeeAdapterFactory({ ...baseFeeResolver, getBalances: baseGetBalances })
102
- : { ...baseFeeResolver, getBalances: baseGetBalances }
103
-
104
- const sendTx = createAndBroadcastTXFactory({
96
+ const baseSendTx = createAndBroadcastTXFactory({
105
97
  getFeeEstimator,
106
98
  allowUnconfirmedRbfEnabledUtxos,
107
99
  })
100
+ const inscriptionsService = brc20Enabled
101
+ ? inscriptionsServiceFactory({
102
+ asset,
103
+ network: coinInfo.toBitcoinJS(),
104
+ ordinalChainIndex,
105
+ })
106
+ : undefined
107
+
108
+ const {
109
+ getFee,
110
+ getBalances,
111
+ getAvailableBalance,
112
+ canBumpTx,
113
+ getSpendableBalance,
114
+ sendTx,
115
+ } = brc20Enabled
116
+ ? brc20BalancesAndFeeAdapterFactory({
117
+ inscriptionsService,
118
+ ...baseFeeResolver,
119
+ getBalances: baseGetBalances,
120
+ sendTx: baseSendTx,
121
+ })
122
+ : { ...baseFeeResolver, getBalances: baseGetBalances, sendTx: baseSendTx }
108
123
 
109
124
  const signTx = signTxFactory({
110
125
  assetName: asset.name,
111
126
  resolvePurpose: address.resolvePurpose,
112
127
  keys,
113
128
  coinInfo,
114
- ecc,
115
129
  })
116
130
 
117
131
  const moveFunds = moveFundsFactory({
@@ -242,6 +256,7 @@ export const createBitcoinAssetFactory = ({ asset, apiUrl, coinInfoNetwork }) =>
242
256
  canBumpTx,
243
257
  getAvailableBalance,
244
258
  getSpendableBalance,
259
+ inscriptions: inscriptionsService,
245
260
  }
246
261
  return overrideCallback({ asset: fullAsset })
247
262
  }
@@ -3,20 +3,53 @@ import { BumpType } from '@exodus/bitcoin-lib/lib/selectors/get-can-bump-tx-fact
3
3
  import { brc20Utils } from './brc-20-utils'
4
4
 
5
5
  export const brc20BalancesAndFeeAdapterFactory = ({
6
+ inscriptionsService,
6
7
  getBalances,
7
8
  getFee,
8
9
  getAvailableBalance,
9
10
  canBumpTx,
10
11
  getSpendableBalance,
12
+ sendTx,
11
13
  }) => {
14
+ assert(inscriptionsService, 'inscriptionsService is required')
12
15
  assert(getBalances, 'getBalances is required')
13
16
  assert(getFee, 'getFee is required')
14
17
  assert(getAvailableBalance, 'getAvailableBalance is required')
15
18
  assert(canBumpTx, 'canBumpTx is required')
16
19
  assert(getSpendableBalance, 'getSpendableBalance is required')
20
+ assert(sendTx, 'sendTx is required')
17
21
 
18
22
  const { isToken, getTokenBalance } = brc20Utils
19
23
 
24
+ const isInscription = ({ options }) => {
25
+ return !options.feeOpts.inscriptionIds?.length
26
+ }
27
+
28
+ const createAndBroadcastInscription = async (
29
+ { asset: token, walletAccount, address, amount, options },
30
+ { assetClientInterface }
31
+ ) => {
32
+ const { broadcastInscription, createBrc20Inscription } = inscriptionsService
33
+
34
+ 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 }),
39
+ })
40
+
41
+ const customFee = asset.currency.baseUnit(20000) // why 64k is te default?
42
+
43
+ return broadcastInscription({
44
+ asset,
45
+ assetClientInterface,
46
+ walletAccount,
47
+ receiverWalletAccount: walletAccount,
48
+ inscription,
49
+ customFee,
50
+ })
51
+ }
52
+
20
53
  return {
21
54
  canBumpTx: (args) => {
22
55
  return isToken(args) ? { bumpType: BumpType.NONE } : canBumpTx(args)
@@ -37,5 +70,11 @@ export const brc20BalancesAndFeeAdapterFactory = ({
37
70
  getBalances: (args) => {
38
71
  return isToken(args) ? { balance: getTokenBalance(args) } : getBalances(args)
39
72
  },
73
+
74
+ sendTx: (...args) => {
75
+ return isToken(args[0]) && isInscription(...args)
76
+ ? createAndBroadcastInscription(...args)
77
+ : sendTx(...args)
78
+ },
40
79
  }
41
80
  }
@@ -0,0 +1,261 @@
1
+ import assert from 'minimalistic-assert'
2
+ import * as bitcoinjsLib from 'bitcoinjs-lib'
3
+
4
+ import ECPairFactory from 'ecpair'
5
+ import { randomBytes } from '@exodus/crypto/randomBytes'
6
+ import secp256k1 from 'tiny-secp256k1'
7
+ import { DEFAULT_BRC20_POSTAGE, DEFAULT_ORDINAL_POSTAGE } from './ordinals-constants'
8
+
9
+ import { witnessStackToScriptWitness } from 'bitcoinjs-lib/src/psbt/psbtutils'
10
+ import getTxSequence from '@exodus/bitcoin-lib/lib/utils/get-tx-sequence'
11
+ import { toXOnly, toAsyncSigner, eccFactory } from '@exodus/bitcoin-api'
12
+
13
+ const encoder = new TextEncoder()
14
+ export function createInscriptionScript({ xOnlyPublicKey, inscription }) {
15
+ assert(xOnlyPublicKey instanceof Buffer, `xOnlyPublicKey must be a Buffer`)
16
+ assert(inscription, `inscription is required`)
17
+ assert(inscription.content instanceof Buffer, `inscription.content must be a Buffer`)
18
+ assert(inscription.contentType instanceof Buffer, `inscription.content must be a Buffer`)
19
+ const protocolId = Buffer.from(encoder.encode('ord'))
20
+ return [
21
+ xOnlyPublicKey,
22
+ bitcoinjsLib.opcodes.OP_CHECKSIG,
23
+ bitcoinjsLib.opcodes.OP_0,
24
+ bitcoinjsLib.opcodes.OP_IF,
25
+ protocolId,
26
+ 1,
27
+ 1, // double 1 to avoid hitting asMinimalOP
28
+ inscription.contentType,
29
+ bitcoinjsLib.opcodes.OP_0,
30
+ inscription.content,
31
+ bitcoinjsLib.opcodes.OP_ENDIF,
32
+ ]
33
+ }
34
+
35
+ export const inscriptionsServiceFactory = ({ network, ordinalChainIndex }) => {
36
+ const ecc = eccFactory()
37
+ assert(network, 'network is required')
38
+ assert(typeof ordinalChainIndex === 'number', 'ordinalChainIndex must be a number')
39
+
40
+ let ECPair
41
+
42
+ function createTextInscription({ text, postage = DEFAULT_ORDINAL_POSTAGE }) {
43
+ const contentType = Buffer.from(encoder.encode('text/plain;charset=utf-8'))
44
+ const content = Buffer.from(encoder.encode(text))
45
+ return { contentType, content, postage }
46
+ }
47
+
48
+ function createBrc20Inscription({
49
+ op,
50
+ tick,
51
+ amt,
52
+ max,
53
+ lim,
54
+ dec,
55
+ postage = DEFAULT_BRC20_POSTAGE,
56
+ }) {
57
+ let body
58
+
59
+ assert(['deploy', 'mint', 'transfer'].includes(op), `invalid brc20 op ${op}`)
60
+ assert(typeof tick === 'string', 'tick is required')
61
+
62
+ if (['mint', 'transfer'].includes(op)) {
63
+ assert(typeof amt === 'string', 'amt is required')
64
+ body = { p: 'brc-20', op, tick, amt }
65
+ } else {
66
+ assert(typeof max === 'string', 'max is required')
67
+ assert(typeof lim === 'string', 'lim is required')
68
+ body = { p: 'brc-20', op, tick, max, lim, dec }
69
+ }
70
+
71
+ const contentType = Buffer.from(encoder.encode('text/plain;charset=utf-8'))
72
+ const content = Buffer.from(encoder.encode(JSON.stringify(body)))
73
+ return { contentType, content, postage }
74
+ }
75
+
76
+ function createCommitTxData({ publicKey, inscription }) {
77
+ assert(publicKey, 'encodePublic is required')
78
+ assert(inscription, 'inscription is required')
79
+ const xOnlyPublicKey = toXOnly(publicKey)
80
+ const script = createInscriptionScript({ xOnlyPublicKey, inscription })
81
+
82
+ const outputScript = bitcoinjsLib.script.compile(script)
83
+
84
+ const scriptTree = {
85
+ output: outputScript,
86
+ }
87
+
88
+ const scriptTaproot = bitcoinjsLib.payments.p2tr({
89
+ internalPubkey: xOnlyPublicKey,
90
+ scriptTree,
91
+ redeem: scriptTree,
92
+ network,
93
+ })
94
+
95
+ const tapleaf = scriptTaproot.hash.toString('hex')
96
+
97
+ const revealAddress = scriptTaproot.address
98
+ const tpubkey = scriptTaproot.pubkey.toString('hex')
99
+ const cblock = scriptTaproot.witness?.[scriptTaproot.witness.length - 1].toString('hex')
100
+
101
+ return {
102
+ script,
103
+ tapleaf,
104
+ tpubkey,
105
+ cblock,
106
+ revealAddress,
107
+ scriptTaproot,
108
+ outputScript,
109
+ }
110
+ }
111
+
112
+ async function createRevealTx({ commitTxData, commitTxResult, toAddress, privateKey, amount }) {
113
+ assert(commitTxData, `commitTxData is required`)
114
+ assert(commitTxResult, `commitTxResult is required`)
115
+ assert(toAddress, `toAddress is required`)
116
+ assert(privateKey instanceof Buffer, `privateKey must be a Buffer`)
117
+ assert(typeof amount === 'number', `amount must be a number`)
118
+
119
+ const { cblock, scriptTaproot, outputScript } = commitTxData
120
+
121
+ const tapLeafScript = {
122
+ leafVersion: scriptTaproot.redeemVersion, // 192 0xc0
123
+ script: outputScript,
124
+ controlBlock: Buffer.from(cblock, 'hex'),
125
+ }
126
+
127
+ ECPair = ECPairFactory(ecc)
128
+ const keypair = ECPair.fromPrivateKey(privateKey, { network })
129
+ const psbt = new bitcoinjsLib.Psbt({ network })
130
+ psbt.addInput({
131
+ hash: commitTxResult.txId,
132
+ index: commitTxResult.sendUtxoIndex,
133
+ witnessUtxo: { value: commitTxResult.sendAmount, script: scriptTaproot.output },
134
+ tapLeafScript: [tapLeafScript],
135
+ sequence: getTxSequence(false),
136
+ })
137
+
138
+ psbt.addOutput({
139
+ value: amount, // generally 1000 for nfts, 549 for brc20
140
+ address: toAddress,
141
+ })
142
+
143
+ await psbt.signInputAsync(0, toAsyncSigner({ keyPair: keypair, ecc }))
144
+
145
+ const signature = psbt.data.inputs[0].tapScriptSig[0].signature.toString('hex')
146
+
147
+ // We have to construct our witness script in a custom finalizer
148
+ const customFinalizer = (_inputIndex: number, input: any) => {
149
+ const witness = [input.tapScriptSig[0].signature]
150
+ .concat(outputScript)
151
+ .concat(tapLeafScript.controlBlock)
152
+
153
+ return {
154
+ finalScriptWitness: witnessStackToScriptWitness(witness),
155
+ }
156
+ }
157
+
158
+ psbt.finalizeInput(0, customFinalizer)
159
+
160
+ const tx = psbt.extractTransaction()
161
+
162
+ const rawTx = tx.toBuffer().toString('hex')
163
+ const txId = tx.getId()
164
+
165
+ const virtualSize = tx.virtualSize()
166
+
167
+ return {
168
+ txId,
169
+ rawTx,
170
+ inscriptionId: `${txId}i0`,
171
+ signature,
172
+ virtualSize,
173
+ }
174
+ }
175
+
176
+ const broadcastInscription = async ({
177
+ asset,
178
+ walletAccount,
179
+ receiverWalletAccount,
180
+ receiverAddress,
181
+ assetClientInterface,
182
+ inscription,
183
+ privateKey = randomBytes(32),
184
+ customFee,
185
+ }) => {
186
+ assert(asset, 'asset is required')
187
+ assert(walletAccount, 'walletAccount is required')
188
+ assert(assetClientInterface, 'assetClientInterface is required')
189
+ assert(inscription, 'inscription is required')
190
+
191
+ const assetName = asset.name
192
+
193
+ const toAddress =
194
+ 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
+
205
+ const postage = inscription.postage
206
+
207
+ const publicKey = secp256k1.pointFromScalar(privateKey, false)
208
+ const commitTxData = createCommitTxData({ publicKey, inscription })
209
+
210
+ // simulate to get size
211
+ const { virtualSize: txSize } = await createRevealTx({
212
+ commitTxData,
213
+ amount: postage,
214
+ commitTxResult: {
215
+ txId: randomBytes(32).toString('hex'),
216
+ sendUtxoIndex: 0,
217
+ sendAmount: 100000,
218
+ },
219
+ toAddress,
220
+ privateKey,
221
+ })
222
+
223
+ const feeData = await assetClientInterface.getFeeConfig({ assetName })
224
+
225
+ const feePerKB = customFee || feeData.feePerKB
226
+
227
+ const minersFee = Math.ceil((feePerKB.toBaseNumber() * txSize) / 1000)
228
+
229
+ const commitAmount = minersFee + postage
230
+
231
+ const commitTxResult = await asset.api.sendTx(
232
+ {
233
+ asset,
234
+ walletAccount,
235
+ address: commitTxData.revealAddress,
236
+ amount: asset.currency.baseUnit(commitAmount),
237
+ options: { isRbfAllowed: false, customFee },
238
+ },
239
+ { assetClientInterface }
240
+ )
241
+
242
+ const revealTx = await createRevealTx({
243
+ commitTxData,
244
+ amount: postage,
245
+ commitTxResult,
246
+ toAddress,
247
+ privateKey,
248
+ })
249
+
250
+ await asset.api.broadcastTx(revealTx.rawTx)
251
+ return { ...revealTx, ...commitTxData }
252
+ }
253
+
254
+ return {
255
+ createTextInscription,
256
+ createBrc20Inscription,
257
+ createCommitTxData,
258
+ createRevealTx,
259
+ broadcastInscription,
260
+ }
261
+ }
@@ -59,7 +59,7 @@ export const nftsApiFactory = ({ ordinalChainIndex, asset }) => {
59
59
  nfts.filter((nft) => !utxosOutputs.includes(nft.output.toLowerCase()))
60
60
  )
61
61
  }
62
- return filteredNfts
62
+ return filteredNfts.filter((nft) => !nft.isBrc20)
63
63
  },
64
64
  }
65
65
  }
@@ -1,3 +1,10 @@
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
+ export const DEFAULT_ORDINAL_POSTAGE = 10000
7
+
1
8
  // What's the taproot chain index to use as the default ordinal address (as in purpose 86, m/2/0).
2
9
  // Note that it's recommended for exodus wallets to not use 0 as it can hold regular btc (as in purpose 86, m/0/0).
3
10
  // If a user syncs an ordinal Wallet (BE) with a non-ordinal Wallet (old Desktop), the non-ordinal wallet may burn ordinals as regular BTC