@bitpay-labs/crypto-wallet-core 11.11.4 → 11.11.6

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 (91) hide show
  1. package/package.json +9 -3
  2. package/ts_build/src/constants/index.d.ts +18 -1
  3. package/ts_build/src/constants/index.d.ts.map +1 -1
  4. package/ts_build/src/constants/tokens.d.ts +14 -2
  5. package/ts_build/src/constants/tokens.d.ts.map +1 -1
  6. package/ts_build/src/constants/tokens.js +8 -2
  7. package/ts_build/src/constants/tokens.js.map +1 -1
  8. package/ts_build/src/constants/units.d.ts +11 -0
  9. package/ts_build/src/constants/units.d.ts.map +1 -1
  10. package/ts_build/src/constants/units.js +11 -0
  11. package/ts_build/src/constants/units.js.map +1 -1
  12. package/ts_build/src/transactions/index.d.ts +1 -1
  13. package/ts_build/src/transactions/index.d.ts.map +1 -1
  14. package/ts_build/src/transactions/index.js.map +1 -1
  15. package/ts_build/src/types/derivation.d.ts +1 -0
  16. package/ts_build/src/types/derivation.d.ts.map +1 -1
  17. package/.mocharc.json +0 -6
  18. package/LICENSE +0 -21
  19. package/mcr.config.js +0 -17
  20. package/src/constants/address.ts +0 -7
  21. package/src/constants/algorithms.ts +0 -9
  22. package/src/constants/arc.ts +0 -4
  23. package/src/constants/chains.ts +0 -68
  24. package/src/constants/feeMinimums.ts +0 -23
  25. package/src/constants/index.ts +0 -40
  26. package/src/constants/tokens.ts +0 -227
  27. package/src/constants/units.ts +0 -300
  28. package/src/derivation/arb/index.ts +0 -3
  29. package/src/derivation/base/index.ts +0 -3
  30. package/src/derivation/bch/index.ts +0 -11
  31. package/src/derivation/btc/index.ts +0 -68
  32. package/src/derivation/doge/index.ts +0 -6
  33. package/src/derivation/eth/index.ts +0 -86
  34. package/src/derivation/index.ts +0 -140
  35. package/src/derivation/ltc/index.ts +0 -6
  36. package/src/derivation/matic/index.ts +0 -3
  37. package/src/derivation/op/index.ts +0 -3
  38. package/src/derivation/paths.ts +0 -45
  39. package/src/derivation/sol/index.ts +0 -81
  40. package/src/derivation/xrp/index.ts +0 -63
  41. package/src/index.ts +0 -48
  42. package/src/message/btc.ts +0 -28
  43. package/src/message/eth.ts +0 -47
  44. package/src/message/index.ts +0 -71
  45. package/src/message/sol.ts +0 -3
  46. package/src/message/xrp.ts +0 -4
  47. package/src/transactions/arb/index.ts +0 -14
  48. package/src/transactions/base/index.ts +0 -13
  49. package/src/transactions/bch/index.ts +0 -25
  50. package/src/transactions/btc/index.ts +0 -316
  51. package/src/transactions/doge/index.ts +0 -31
  52. package/src/transactions/erc20/abi.ts +0 -418
  53. package/src/transactions/erc20/index.ts +0 -57
  54. package/src/transactions/eth/index.ts +0 -192
  55. package/src/transactions/eth-multisig/abi.ts +0 -724
  56. package/src/transactions/eth-multisig/index.ts +0 -172
  57. package/src/transactions/index.ts +0 -85
  58. package/src/transactions/ltc/index.ts +0 -31
  59. package/src/transactions/matic/index.ts +0 -14
  60. package/src/transactions/matic-multisig/index.ts +0 -172
  61. package/src/transactions/op/index.ts +0 -14
  62. package/src/transactions/sol/index.ts +0 -306
  63. package/src/transactions/spl/index.ts +0 -192
  64. package/src/transactions/xrp/index.ts +0 -167
  65. package/src/types/derivation.ts +0 -34
  66. package/src/types/index.ts +0 -3
  67. package/src/types/message.ts +0 -15
  68. package/src/types/utils.ts +0 -1
  69. package/src/types/validation.ts +0 -4
  70. package/src/utils/bigint.ts +0 -238
  71. package/src/utils/index.ts +0 -188
  72. package/src/validation/arb/index.ts +0 -8
  73. package/src/validation/arc/index.ts +0 -8
  74. package/src/validation/base/index.ts +0 -8
  75. package/src/validation/bch/index.ts +0 -17
  76. package/src/validation/btc/index.ts +0 -17
  77. package/src/validation/doge/index.ts +0 -16
  78. package/src/validation/eth/index.ts +0 -29
  79. package/src/validation/index.ts +0 -45
  80. package/src/validation/ltc/index.ts +0 -16
  81. package/src/validation/matic/index.ts +0 -8
  82. package/src/validation/op/index.ts +0 -8
  83. package/src/validation/sol/index.ts +0 -34
  84. package/src/validation/xrp/index.ts +0 -50
  85. package/test/address.test.ts +0 -190
  86. package/test/bigint.test.ts +0 -373
  87. package/test/deriver.test.ts +0 -126
  88. package/test/transactions.test.ts +0 -2103
  89. package/test/utils.test.ts +0 -446
  90. package/test/validation.test.ts +0 -282
  91. package/tsconfig.json +0 -29
@@ -1,306 +0,0 @@
1
- import * as SolKit from '@solana/kit';
2
- import * as SolComputeBudget from '@solana-program/compute-budget';
3
- import * as SolComputeMemo from '@solana-program/memo';
4
- import * as SolSystem from '@solana-program/system';
5
- import * as SolToken from '@solana-program/token';
6
- import type { Key } from '../../types/derivation';
7
-
8
-
9
- export class SOLTxProvider {
10
-
11
- MAX_TRANSFERS = 12;
12
- MINIMUM_PRIORITY_FEE = 1000;
13
-
14
- create(params: {
15
- recipients: Array<{ address: string; amount: string; addressKeyPair?: SolKit.KeyPairSigner }>;
16
- from: string;
17
- fee?: number;
18
- feeRate: number;
19
- txType?: 'legacy' | '0'; // legacy, version 0
20
- category?: 'transfer' | 'createAccount'; // transfer, create account
21
- nonce?: string; // nonce is represented as a transaction id
22
- nonceAddress?: string;
23
- blockHash?: string;
24
- blockHeight?: number;
25
- priorityFee?: number;
26
- computeUnits?: number;
27
- memo?: string;
28
- txInstructions?: Array<SolKit.BaseTransactionMessage['instructions'][number]>;
29
- // account creation fields
30
- fromKeyPair?: any;
31
- space?: number; // amount of space to reserve a new account in bytes
32
- mint?: string; // mint address for createATA
33
- ataAddress?: any; // ATA address for createATA
34
- }) {
35
- const { recipients, from, nonce, nonceAddress, category, space, blockHash, blockHeight, priorityFee, txInstructions, computeUnits, fromKeyPair, memo } = params;
36
- const fromAddress = SolKit.address(from);
37
- const txType: SolKit.TransactionVersion = ['0', 0].includes(params?.txType) ? 0 : 'legacy';
38
- let lifetimeConstrainedTx;
39
- switch (category?.toLowerCase()) {
40
- case 'transfer':
41
- default:
42
- if (recipients.length > this.MAX_TRANSFERS) {
43
- throw new Error('Too many recipients');
44
- }
45
- const transactionMessage = SolKit.pipe(
46
- SolKit.createTransactionMessage({ version: txType }),
47
- tx => SolKit.setTransactionMessageFeePayer(fromAddress, tx),
48
- );
49
-
50
- if (nonce) {
51
- const nonceAccountAddress = SolKit.address(nonceAddress);
52
- const nonceAuthorityAddress = fromAddress;
53
- lifetimeConstrainedTx = SolKit.setTransactionMessageLifetimeUsingDurableNonce({
54
- nonce: nonce as SolKit.Nonce,
55
- nonceAccountAddress,
56
- nonceAuthorityAddress
57
- }, transactionMessage);
58
- } else {
59
- const recentBlockhash = {
60
- blockhash: blockHash as SolKit.Blockhash,
61
- lastValidBlockHeight: BigInt(blockHeight)
62
- };
63
- lifetimeConstrainedTx = SolKit.setTransactionMessageLifetimeUsingBlockhash(
64
- recentBlockhash,
65
- transactionMessage,
66
- );
67
- }
68
- const transferInstructions = txInstructions || [];
69
- if (!transferInstructions.length) {
70
- for (const recipient of recipients) {
71
- const { address: recipientAddress, amount: recipientAmount } = recipient;
72
- transferInstructions.push(SolSystem.getTransferSolInstruction({
73
- amount: BigInt(recipientAmount),
74
- destination: SolKit.address(recipientAddress),
75
- source: {
76
- address: fromAddress,
77
- signTransactions: async () => []
78
- } as SolKit.TransactionPartialSigner
79
- }));
80
- }
81
- }
82
- if (priorityFee) {
83
- const maxPriorityFee = Math.max(this.MINIMUM_PRIORITY_FEE, priorityFee);
84
- transferInstructions.push(SolComputeBudget.getSetComputeUnitPriceInstruction({ microLamports: maxPriorityFee }));
85
- }
86
- if (computeUnits) {
87
- transferInstructions.push(SolComputeBudget.getSetComputeUnitLimitInstruction({ units: computeUnits }));
88
- }
89
- if (memo) {
90
- const memoInstruction = SolComputeMemo.getAddMemoInstruction({
91
- memo
92
- });
93
- transferInstructions.push(memoInstruction);
94
- }
95
- const transferTxMessage = SolKit.appendTransactionMessageInstructions(transferInstructions, lifetimeConstrainedTx);
96
- const compiledTx = SolKit.compileTransaction(transferTxMessage);
97
- return SolKit.getBase64EncodedWireTransaction(compiledTx);
98
- case 'createaccount':
99
- const { amount, addressKeyPair } = recipients[0];
100
- const _space = space || 200;
101
- const _amount = Number(amount);
102
-
103
- if (!addressKeyPair) {
104
- throw new Error('New address keypair is required to create an account.');
105
- }
106
- const recentBlockhash = {
107
- blockhash: blockHash as SolKit.Blockhash,
108
- lastValidBlockHeight: BigInt(blockHeight)
109
- };
110
- const createAccountInstructions = [];
111
- createAccountInstructions.push(SolSystem.getCreateAccountInstruction({
112
- payer: fromKeyPair,
113
- newAccount: addressKeyPair,
114
- lamports: _amount,
115
- space: _space,
116
- programAddress: SolSystem.SYSTEM_PROGRAM_ADDRESS
117
- }));
118
- const txMessage = SolKit.pipe(
119
- SolKit.createTransactionMessage({ version: txType }),
120
- (tx) => SolKit.setTransactionMessageFeePayerSigner(fromKeyPair, tx),
121
- );
122
- lifetimeConstrainedTx = SolKit.setTransactionMessageLifetimeUsingBlockhash(
123
- recentBlockhash,
124
- txMessage,
125
- );
126
- if (priorityFee) {
127
- const maxPriorityFee = Math.max(this.MINIMUM_PRIORITY_FEE, priorityFee);
128
- createAccountInstructions.push(SolComputeBudget.getSetComputeUnitPriceInstruction({ microLamports: maxPriorityFee }));
129
- }
130
- if (computeUnits) {
131
- createAccountInstructions.push(SolComputeBudget.getSetComputeUnitLimitInstruction({ units: computeUnits }));
132
- }
133
- const completeMessage = SolKit.appendTransactionMessageInstructions(
134
- createAccountInstructions,
135
- lifetimeConstrainedTx
136
- );
137
- const compiled = SolKit.compileTransaction(completeMessage);
138
- return SolKit.getBase64EncodedWireTransaction(compiled);
139
- case 'createata':
140
- const { mint, ataAddress } = params;
141
- const createAssociatedTokenIdempotentInstruction = SolToken.getCreateAssociatedTokenIdempotentInstruction({
142
- payer: fromKeyPair,
143
- owner: fromAddress,
144
- mint: SolKit.address(mint),
145
- ata: ataAddress
146
- });
147
- const ataTxMessage = SolKit.pipe(
148
- SolKit.createTransactionMessage({ version: 0 }),
149
- (tx) => SolKit.setTransactionMessageFeePayerSigner(fromKeyPair, tx),
150
- (tx) => SolKit.setTransactionMessageLifetimeUsingBlockhash({ blockhash: blockHash as SolKit.Blockhash, lastValidBlockHeight: BigInt(blockHeight) }, tx),
151
- (tx) => SolKit.appendTransactionMessageInstructions(
152
- [createAssociatedTokenIdempotentInstruction],
153
- tx
154
- )
155
- );
156
- const compiledAtaTx = SolKit.compileTransaction(ataTxMessage);
157
- return SolKit.getBase64EncodedWireTransaction(compiledAtaTx);
158
- }
159
- }
160
-
161
- decodeRawTransaction({ rawTx, decodeTransactionMessage = true }) {
162
- if (typeof rawTx !== 'string') {
163
- throw new Error(`Raw transaction expected to be a string. Found ${typeof rawTx} instead.`);
164
- }
165
- const uint8ArrayTx = SolKit.getBase64Encoder().encode(rawTx);
166
- const decodedTx: any = SolKit.getTransactionDecoder().decode(uint8ArrayTx);
167
-
168
- // decoding and decompiling the transaction message allows extraction of key data such as lifetimeConstraint
169
- // certain advance transactions such as dex swaps, lookup table txs, may need additional data to perform decompilation and will throw errors if not provided
170
- if (decodeTransactionMessage) {
171
- const decompiledTransactionMessage = this.decodeTransactionMessage(decodedTx?.messageBytes);
172
- decodedTx.lifetimeConstraint = decompiledTransactionMessage.lifetimeConstraint;
173
- }
174
- return decodedTx;
175
- }
176
-
177
- decodeTransactionMessage(bytes) {
178
- // TODO support lookup tables
179
- const compiledTransactionMessage = SolKit.getCompiledTransactionMessageDecoder().decode(bytes);
180
- return SolKit.decompileTransactionMessage(compiledTransactionMessage);
181
- }
182
-
183
- /**
184
- * Reads the fields BWS may mutate between proposal creation and publish out of a raw tx, to bind
185
- * txp.prePublishRaw to the proposal. For Solana that is the recent blockhash (refreshOnPublish), which is
186
- * the compiled message's `lifetimeToken`. We decode only the compiled message (never decompile) so this
187
- * stays safe for txs using Address Lookup Tables -- decompilation would need the on-chain table accounts,
188
- * which a client-side lib cannot fetch. lastValidBlockHeight is not on the wire and does not affect
189
- * serialization, so it is intentionally not recovered.
190
- */
191
- getMutableFields(rawTx: string): { blockHash?: string } {
192
- const decoded: any = this.decodeRawTransaction({ rawTx, decodeTransactionMessage: false });
193
- const compiled: any = SolKit.getCompiledTransactionMessageDecoder().decode(decoded.messageBytes);
194
- return { blockHash: compiled?.lifetimeToken };
195
- }
196
-
197
- async sign(params: { tx: string; key: Key }): Promise<string> {
198
- const { tx, key } = params;
199
- const decodedTx = this.decodeRawTransaction({ rawTx: tx, decodeTransactionMessage: false });
200
- const privKeyBytes = SolKit.getBase58Encoder().encode(key.privKey);
201
- const keypair = await SolKit.createKeyPairFromPrivateKeyBytes(privKeyBytes);
202
- const signedTransaciton = await SolKit.signTransaction([keypair], decodedTx);
203
- return SolKit.getBase64EncodedWireTransaction(signedTransaciton);
204
- }
205
-
206
- async signPartially(params) {
207
- const { tx, key } = params;
208
- const decodedTx = this.decodeRawTransaction({ rawTx: tx, decodeTransactionMessage: false });
209
- const privKeyBytes = SolKit.getBase58Encoder().encode(key.privKey);
210
- const keypair = await SolKit.createKeyPairFromPrivateKeyBytes(privKeyBytes);
211
- const signedTransaciton = await SolKit.partiallySignTransaction([keypair], decodedTx);
212
- return SolKit.getBase64EncodedWireTransaction(signedTransaciton);
213
- }
214
-
215
- async signMessage(params) {
216
- const { key, messageBytes } = params;
217
- const privKeyBytes = SolKit.getBase58Encoder().encode(key.privKey);
218
- const keypair = await SolKit.createKeyPairFromPrivateKeyBytes(privKeyBytes);
219
- const signedBytes = await SolKit.signBytes(keypair.privateKey, messageBytes);
220
- return SolKit.getBase58Decoder().decode(signedBytes);
221
- }
222
-
223
- async getSignature(params: { tx: string; keys: Array<Key> }) {
224
- const { tx, keys } = params;
225
- const key = keys[0];
226
- const signedTx = await this.sign({ tx, key });
227
- const decodedTx = this.decodeRawTransaction({ rawTx: signedTx, decodeTransactionMessage: false });
228
- const sigEncoding = decodedTx.signatures[key.address];
229
- return SolKit.getBase58Decoder().decode(sigEncoding);
230
- }
231
-
232
- applySignature(params: { tx: string; signature: string }): string {
233
- const { tx, signature } = params;
234
- const signatures = [SolKit.getBase58Encoder().encode(signature)];
235
- const transaction = SolKit.getBase64Encoder().encode(tx);
236
- const transformWithNewSignatures = (_tx) => {
237
- const { messageBytes } = _tx;
238
- const signerAddressesDecoder = SolKit.getTupleDecoder([
239
- // read transaction version
240
- SolKit.getTransactionVersionDecoder(),
241
- // read first byte of header, `numSignerAccounts`
242
- // padRight to skip the next 2 bytes, `numReadOnlySignedAccounts` and `numReadOnlyUnsignedAccounts` which we don't need
243
- SolKit.padRightDecoder(SolKit.getU8Decoder(), 2),
244
- // read static addresses
245
- SolKit.getArrayDecoder(SolKit.getAddressDecoder(), { size: SolKit.getShortU16Decoder() })
246
- ]);
247
- const [, numRequiredSignatures, staticAddresses] = signerAddressesDecoder.decode(messageBytes);
248
- const signerAddresses = staticAddresses.slice(0, numRequiredSignatures);
249
- if (signerAddresses.length !== signatures.length) {
250
- throw new Error(`The transaction message expected the transaction to have ${signerAddresses.length} signatures, got ${signatures.length}.`);
251
- }
252
- const signaturesMap = {};
253
- for (let index = 0; index < signerAddresses.length; index++) {
254
- const address = signerAddresses[index];
255
- const signatureForAddress = signatures[index];
256
-
257
- if (signatureForAddress.every((b) => b === 0)) {
258
- signaturesMap[address] = null;
259
- } else {
260
- signaturesMap[address] = signatureForAddress;
261
- }
262
- }
263
- return {
264
- messageBytes,
265
- signatures: Object.freeze(signaturesMap)
266
- };
267
- };
268
- const decoderTransform = SolKit.transformDecoder(
269
- SolKit.getStructDecoder([
270
- ['signatures', SolKit.getArrayDecoder(SolKit.fixDecoderSize(SolKit.getBytesDecoder(), 64), { size: SolKit.getShortU16Decoder() })],
271
- ['messageBytes', SolKit.getBytesDecoder()]
272
- ]),
273
- transformWithNewSignatures
274
- );
275
- const signedTx = decoderTransform.decode(transaction);
276
- return SolKit.getBase64EncodedWireTransaction(signedTx);
277
- }
278
-
279
- getHash(params: { tx: string }): string {
280
- const { tx } = params;
281
- const decodedTx = this.decodeRawTransaction({ rawTx: tx, decodeTransactionMessage: false });
282
- const pubKeys = Object.keys(decodedTx.signatures);
283
- let signature;
284
-
285
- if (pubKeys.length == 1) {
286
- signature = decodedTx.signatures[pubKeys[0]];
287
- } else if (pubKeys.length > 1) {
288
- try {
289
- const compiledTransactionMessage = SolKit.getCompiledTransactionMessageDecoder().decode(decodedTx.messageBytes);
290
- const feePayerAddress = compiledTransactionMessage.staticAccounts[0];
291
- signature = decodedTx.signatures[feePayerAddress];
292
- } catch (err) {
293
- throw new Error('unable to get fee payer signature %o', err.stack || err.message || err);
294
- }
295
- }
296
- if (!signature) {
297
- throw new Error('tx is unsigned by fee payer');
298
- }
299
-
300
- return SolKit.getBase58Decoder().decode(signature);
301
- }
302
-
303
- getSighash(_params: { tx: string }): string {
304
- return null; // TODO
305
- }
306
- }
@@ -1,192 +0,0 @@
1
- import * as SolKit from '@solana/kit';
2
- import * as SolToken from '@solana-program/token';
3
- import { SOLTxProvider } from '../sol';
4
-
5
- export class SPLTxProvider extends SOLTxProvider {
6
-
7
- create(params: CreateParams) {
8
- // Reuse exposed TransactionProxy API (Create)
9
- // @ts-expect-error - so public api is minimally changed
10
- if (params.category === 'recoverNestedAssociatedToken') {
11
- return SPLTxProvider.createRecoverNestedAssociatedTokenTransaction(params as unknown as CreateRecoverNestedAssociatedTokenParams);
12
- }
13
- // @ts-expect-error - so public api is minimally changed
14
- if (params.category === 'closeTokenAccount') {
15
- return SPLTxProvider.createCloseTokenAccountTransaction(params as unknown as CreateCloseTokenAccountParams);
16
- }
17
-
18
- const { recipients, from, fromAta, tokenAddress, decimals, instructions = [] } = params;
19
- // Start with custom instructions
20
- const allInstructions = [...instructions];
21
- if (recipients.length > 0 && !instructions?.length) {
22
- // Add SPL token transfer instructions for each recipient
23
- for (const recipient of recipients) {
24
- const { address: recipientAddress, amount: recipientAmount } = recipient;
25
- allInstructions.push(SolToken.getTransferCheckedInstruction({
26
- source: SolKit.address(fromAta), // ATA address
27
- authority: SolKit.address(from),
28
- mint: SolKit.address(tokenAddress),
29
- destination: SolKit.address(recipientAddress), // ATA address
30
- amount: BigInt(recipientAmount),
31
- decimals: Number(decimals)
32
- }));
33
- }
34
- }
35
-
36
- return super.create({ ...params, txInstructions: allInstructions });
37
- }
38
-
39
- static createAtokenInstructions(instructionType: InstructionType, params: any) {
40
- try {
41
- switch (instructionType) {
42
- case 'createAssociatedToken':
43
- return SolToken.getCreateAssociatedTokenInstruction(params);
44
- case 'createAssociatedTokenIdempotent':
45
- return SolToken.getCreateAssociatedTokenIdempotentInstruction(params);
46
- case 'recoverNestedAssociatedToken':
47
- return SolToken.getRecoverNestedAssociatedTokenInstruction(params);
48
- default:
49
- throw new Error(`Unsupported AToken instruction type: ${instructionType}`);
50
- }
51
- } catch (error) {
52
- throw new Error(`Failed to create AToken instruction: ${error.message}`);
53
- }
54
- }
55
-
56
- static createRecoverNestedAssociatedTokenTransaction(params: CreateRecoverNestedAssociatedTokenParams) {
57
- const {
58
- fromKeyPair,
59
- blockHash,
60
- blockHeight,
61
- nestedAssociatedAccountAddress,
62
- nestedTokenMintAddress,
63
- destinationAssociatedAccountAddress,
64
- ownerAssociatedAccountAddress,
65
- ownerTokenMintAddress
66
- } = params;
67
- // Validate
68
- if (!SolKit.isKeyPairSigner(fromKeyPair)) {
69
- throw new Error('fromKeyPair required to implement KeyPairSigner');
70
- }
71
- if (!(blockHash && blockHeight)) {
72
- throw new Error('blockHash and blockHeight required');
73
- }
74
-
75
- const instruction = SolToken.getRecoverNestedAssociatedTokenInstruction({
76
- nestedAssociatedAccountAddress: SolKit.address(nestedAssociatedAccountAddress),
77
- nestedTokenMintAddress: SolKit.address(nestedTokenMintAddress),
78
- destinationAssociatedAccountAddress: SolKit.address(destinationAssociatedAccountAddress),
79
- ownerAssociatedAccountAddress: SolKit.address(ownerAssociatedAccountAddress),
80
- ownerTokenMintAddress: SolKit.address(ownerTokenMintAddress),
81
- walletAddress: params.fromKeyPair
82
- });
83
-
84
- const recentBlockhash = {
85
- blockhash: blockHash as SolKit.Blockhash,
86
- lastValidBlockHeight: BigInt(blockHeight)
87
- };
88
-
89
- // Create transaction
90
- const transactionMessage = SolKit.pipe(
91
- SolKit.createTransactionMessage({ version: 'legacy' }),
92
- (tx) => SolKit.setTransactionMessageFeePayer(fromKeyPair.address, tx),
93
- (tx) => SolKit.setTransactionMessageLifetimeUsingBlockhash(recentBlockhash, tx),
94
- (tx) => SolKit.appendTransactionMessageInstructions(
95
- [instruction], tx
96
- )
97
- );
98
-
99
- const compiledTx = SolKit.compileTransaction(transactionMessage);
100
- return SolKit.getBase64EncodedWireTransaction(compiledTx);
101
- }
102
-
103
- static createCloseTokenAccountTransaction(params: CreateCloseTokenAccountParams) {
104
- const {
105
- fromKeyPair,
106
- blockHash,
107
- blockHeight,
108
- ataAddressToClose,
109
- solRentReturnAddress,
110
- ataAddressToCloseOwnerSolAddress
111
- } = params;
112
- // Validate
113
- if (!SolKit.isKeyPairSigner(fromKeyPair)) {
114
- throw new Error('fromKeyPair required to implement KeyPairSigner');
115
- }
116
- if (!(blockHash && blockHeight)) {
117
- throw new Error('blockHash and blockHeight required');
118
- }
119
-
120
- const instruction = SolToken.getCloseAccountInstruction({
121
- account: SolKit.address(ataAddressToClose),
122
- destination: SolKit.address(solRentReturnAddress),
123
- owner: SolKit.address(ataAddressToCloseOwnerSolAddress)
124
- });
125
-
126
- const recentBlockhash = {
127
- blockhash: blockHash as SolKit.Blockhash,
128
- lastValidBlockHeight: BigInt(blockHeight)
129
- };
130
-
131
- // Create transaction
132
- const transactionMessage = SolKit.pipe(
133
- SolKit.createTransactionMessage({ version: 'legacy' }),
134
- (tx) => SolKit.setTransactionMessageFeePayer(fromKeyPair.address, tx),
135
- (tx) => SolKit.setTransactionMessageLifetimeUsingBlockhash(recentBlockhash, tx),
136
- (tx) => SolKit.appendTransactionMessageInstructions(
137
- [instruction], tx
138
- )
139
- );
140
-
141
- const compiledTx = SolKit.compileTransaction(transactionMessage);
142
- return SolKit.getBase64EncodedWireTransaction(compiledTx);
143
- }
144
- }
145
-
146
- interface CreateParams {
147
- recipients: Array<{ address: string; amount: string; addressKeyPair?: SolKit.KeyPairSigner }>;
148
- from: string;
149
- fee?: number;
150
- feeRate: number;
151
- txType?: 'legacy' | '0'; // legacy, version 0
152
- category?: 'transfer' | 'createAccount';
153
- nonce?: string; // nonce is represented as a transaction id
154
- nonceAddress?: string;
155
- blockHash?: string;
156
- blockHeight?: number;
157
- priorityFee?: number;
158
- computeUnits?: number;
159
- memo?: string;
160
- // account creation fields
161
- fromKeyPair?: SolKit.KeyPairSigner;
162
- space?: number; // amount of space to reserve a new account in bytes
163
- instructions?: Array<SolKit.BaseTransactionMessage['instructions'][number]>;
164
- // SPL token transfer fields (required for token transfers)
165
- tokenAddress: string; // mint address
166
- fromAta?: string;
167
- decimals?: number | string;
168
- }
169
-
170
- interface CreateRecoverNestedAssociatedTokenParams {
171
- category: 'recoverNestedAssociatedToken';
172
- blockHash: string;
173
- blockHeight: number;
174
- fromKeyPair: SolKit.KeyPairSigner;
175
- nestedAssociatedAccountAddress: string;
176
- nestedTokenMintAddress: string;
177
- destinationAssociatedAccountAddress: string;
178
- ownerAssociatedAccountAddress: string;
179
- ownerTokenMintAddress: string;
180
- }
181
-
182
- interface CreateCloseTokenAccountParams {
183
- category: 'closeTokenAccount';
184
- blockHash: string;
185
- blockHeight: number;
186
- fromKeyPair: SolKit.KeyPairSigner;
187
- ataAddressToClose: string;
188
- solRentReturnAddress: string;
189
- ataAddressToCloseOwnerSolAddress: string;
190
- }
191
-
192
- type InstructionType = 'createAssociatedToken' | 'createAssociatedTokenIdempotent' | 'recoverNestedAssociatedToken';
@@ -1,167 +0,0 @@
1
- import { createHash } from 'crypto';
2
- import * as RBC from 'ripple-binary-codec';
3
- import * as binary from 'ripple-binary-codec/dist/binary';
4
- import { HashPrefix } from 'ripple-binary-codec/dist/hash-prefixes';
5
- import * as xrpl from 'xrpl';
6
- import * as Utils from '../../utils';
7
- import { BTCTxProvider } from '../btc';
8
- import type { Key } from '../../types/derivation';
9
-
10
- export class XRPTxProvider {
11
- create(params: {
12
- recipients: Array<{ address: string; amount: string; tag?: number }>;
13
- tag?: number;
14
- from: string;
15
- invoiceID?: string;
16
- fee: number;
17
- feeRate: number;
18
- nonce: number;
19
- txType?: string;
20
- flags?: number | string;
21
- }) {
22
- const {
23
- recipients,
24
- tag,
25
- from,
26
- invoiceID,
27
- fee,
28
- nonce,
29
- // `params.type` is an old param to fallback to.
30
- // Changed to txType to re-use similar property name from other chains (e.g. EVM)
31
- txType = params['type'],
32
- flags,
33
- } = params;
34
-
35
- switch (txType?.toLowerCase()) {
36
- case 'payment':
37
- default:
38
- const { address, amount } = recipients[0];
39
- const _tag = recipients[0]?.tag || tag;
40
- const paymentTx: xrpl.Payment = {
41
- TransactionType: 'Payment',
42
- Account: from,
43
- Destination: address,
44
- Amount: amount.toString(),
45
- Fee: fee.toString(),
46
- Sequence: nonce,
47
- Flags: 2147483648 // tfFullyCanonicalSig - DEPRECATED but still here for backward compatibility
48
- };
49
- if (flags != null) {
50
- paymentTx.Flags = this.transformFlags<xrpl.PaymentFlagsInterface>(flags, 'payment');
51
- xrpl.setTransactionFlagsToNumber(paymentTx);
52
- }
53
- if (invoiceID) {
54
- paymentTx.InvoiceID = invoiceID;
55
- }
56
- if (_tag) {
57
- paymentTx.DestinationTag = _tag;
58
- }
59
- return xrpl.encode(paymentTx);
60
- case 'accountset':
61
- const accountSetTx: xrpl.AccountSet = {
62
- TransactionType: 'AccountSet',
63
- Account: from,
64
- Flags: this.transformFlags<xrpl.AccountSetFlagsInterface>(flags, 'accountset'),
65
- Fee: fee.toString(),
66
- Sequence: nonce
67
- };
68
- xrpl.setTransactionFlagsToNumber(accountSetTx);
69
- return xrpl.encode(accountSetTx);
70
- case 'accountdelete':
71
- const accountDeleteTx: xrpl.AccountDelete = {
72
- TransactionType: 'AccountDelete',
73
- Account: from,
74
- Destination: recipients[0].address,
75
- DestinationTag: recipients[0].tag,
76
- Fee: fee.toString(),
77
- Sequence: nonce
78
- };
79
- return xrpl.encode(accountDeleteTx);
80
- }
81
- }
82
-
83
- getSignatureObject(params: { tx: string; key: Key }) {
84
- const { tx, key } = params;
85
- const txJSON = (xrpl.decode(tx) as unknown) as xrpl.Payment;
86
- const signedTx = new xrpl.Wallet(key.pubKey.toUpperCase(), key.privKey.toUpperCase()).sign(txJSON);
87
- return { signedTransaction: signedTx.tx_blob, hash: signedTx.hash };
88
- }
89
-
90
- getSignature(params: { tx: string; key: Key }): string {
91
- const { signedTransaction } = this.getSignatureObject(params);
92
- const decoded = (xrpl.decode(signedTransaction) as any) as xrpl.Transaction;
93
- return decoded.TxnSignature;
94
- }
95
-
96
- getHash(params: { tx: string }): string {
97
- const { tx } = params;
98
- const prefix = HashPrefix.transactionID.toString('hex').toUpperCase();
99
- return this.sha512Half(prefix + tx);
100
- }
101
-
102
- /**
103
- * Reads the fields BWS may mutate between proposal creation and publish out of a raw tx, to bind
104
- * txp.prePublishRaw to the proposal. For XRP that is only the account sequence/nonce (deferred-nonce).
105
- */
106
- getMutableFields(rawTx: string): { nonce?: number } {
107
- const txJSON = (xrpl.decode(rawTx) as any);
108
- return { nonce: txJSON?.Sequence != null ? Number(txJSON.Sequence) : undefined };
109
- }
110
-
111
- applySignature(params: { tx: string; signature: string; pubKey: string }): string {
112
- const { tx, signature, pubKey } = params;
113
- const txJSON = (xrpl.decode(tx) as any) as xrpl.Transaction;
114
- txJSON.TxnSignature = signature;
115
- txJSON.SigningPubKey = pubKey;
116
- const signedTx = xrpl.encode(txJSON);
117
- return signedTx;
118
- }
119
-
120
- sign(params: { tx: string; key: Key }): string {
121
- const { tx, key } = params;
122
- const signature = this.getSignature({ tx, key });
123
- return this.applySignature({ tx, signature, pubKey: key.pubKey });
124
- }
125
-
126
- sha512Half(hex: string): string {
127
- return createHash('sha512')
128
- .update(Buffer.from(hex, 'hex'))
129
- .digest('hex')
130
- .toUpperCase()
131
- .slice(0, 64);
132
- }
133
-
134
- transformSignatureObject(params: { obj: any }) {
135
- const { obj } = params;
136
- return new BTCTxProvider().transformSignatureObject({ obj });
137
- }
138
-
139
- getSighash(params: { tx: string; pubKey: string }) {
140
- const { tx, pubKey } = params;
141
- const decoded = RBC.decode(tx);
142
- decoded.SigningPubKey = pubKey;
143
- const encoded = binary.serializeObject(decoded, {
144
- prefix: HashPrefix.transactionSig,
145
- signingFieldsOnly: true
146
- }).toString('hex');
147
- return this.sha512Half(encoded);
148
- }
149
-
150
- private transformFlags<T extends xrpl.PaymentFlagsInterface>(flags: string | number, txType: 'payment'): T | number
151
- private transformFlags<T extends xrpl.AccountSetFlagsInterface>(flags: string | number, txType: 'accountset'): T | number
152
- private transformFlags<T extends xrpl.PaymentFlagsInterface | xrpl.AccountSetFlagsInterface>(flags: string | number, txType: 'payment' | 'accountset'): T | number {
153
- if (flags == null) {
154
- throw new Error('No XRP flag(s) provided');
155
- }
156
- if (typeof flags === 'number') {
157
- // Pass through numbers since they may be combined flags
158
- return flags;
159
- }
160
- const flagEnum = txType === 'payment' ? xrpl.PaymentFlags : xrpl.AccountSetTfFlags;
161
- return flags.split(',').reduce((acc, flag) => {
162
- const flagValue = Utils.normalizeXrpFlag(flag.trim(), flagEnum);
163
- acc[flagValue] = true;
164
- return acc;
165
- }, {} as T);
166
- }
167
- }