@onekeyfe/cardano-coin-selection-asmjs 1.1.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.
Files changed (79) hide show
  1. package/CHANGELOG.MD +25 -0
  2. package/README.md +183 -0
  3. package/lib/cjs/constants/index.d.ts +40 -0
  4. package/lib/cjs/constants/index.js +69 -0
  5. package/lib/cjs/index.d.ts +6 -0
  6. package/lib/cjs/index.js +101 -0
  7. package/lib/cjs/methods/largestFirst.d.ts +2 -0
  8. package/lib/cjs/methods/largestFirst.js +201 -0
  9. package/lib/cjs/methods/randomImprove.d.ts +2 -0
  10. package/lib/cjs/methods/randomImprove.js +187 -0
  11. package/lib/cjs/types/trezor.d.ts +45 -0
  12. package/lib/cjs/types/trezor.js +8 -0
  13. package/lib/cjs/types/types.d.ts +116 -0
  14. package/lib/cjs/types/types.js +17 -0
  15. package/lib/cjs/utils/common.d.ts +46 -0
  16. package/lib/cjs/utils/common.js +514 -0
  17. package/lib/cjs/utils/errors.d.ts +8 -0
  18. package/lib/cjs/utils/errors.js +13 -0
  19. package/lib/cjs/utils/logger.d.ts +5 -0
  20. package/lib/cjs/utils/logger.js +27 -0
  21. package/lib/cjs/utils/onekey/dapp.d.ts +14 -0
  22. package/lib/cjs/utils/onekey/dapp.js +247 -0
  23. package/lib/cjs/utils/onekey/error.d.ts +28 -0
  24. package/lib/cjs/utils/onekey/error.js +25 -0
  25. package/lib/cjs/utils/onekey/index.d.ts +48 -0
  26. package/lib/cjs/utils/onekey/index.js +15 -0
  27. package/lib/cjs/utils/onekey/signTx.d.ts +26 -0
  28. package/lib/cjs/utils/onekey/signTx.js +296 -0
  29. package/lib/cjs/utils/onekey/transaction.d.ts +5 -0
  30. package/lib/cjs/utils/onekey/transaction.js +49 -0
  31. package/lib/cjs/utils/onekey/txToOneKey.d.ts +67 -0
  32. package/lib/cjs/utils/onekey/txToOneKey.js +504 -0
  33. package/lib/cjs/utils/onekey/types.d.ts +79 -0
  34. package/lib/cjs/utils/onekey/types.js +16 -0
  35. package/lib/cjs/utils/trezor/index.d.ts +3 -0
  36. package/lib/cjs/utils/trezor/index.js +9 -0
  37. package/lib/cjs/utils/trezor/sign.d.ts +5 -0
  38. package/lib/cjs/utils/trezor/sign.js +69 -0
  39. package/lib/cjs/utils/trezor/transformations.d.ts +17 -0
  40. package/lib/cjs/utils/trezor/transformations.js +66 -0
  41. package/lib/esm/constants/index.d.ts +40 -0
  42. package/lib/esm/constants/index.js +43 -0
  43. package/lib/esm/index.d.ts +6 -0
  44. package/lib/esm/index.js +73 -0
  45. package/lib/esm/methods/largestFirst.d.ts +2 -0
  46. package/lib/esm/methods/largestFirst.js +174 -0
  47. package/lib/esm/methods/randomImprove.d.ts +2 -0
  48. package/lib/esm/methods/randomImprove.js +160 -0
  49. package/lib/esm/types/trezor.d.ts +45 -0
  50. package/lib/esm/types/trezor.js +5 -0
  51. package/lib/esm/types/types.d.ts +116 -0
  52. package/lib/esm/types/types.js +14 -0
  53. package/lib/esm/utils/common.d.ts +46 -0
  54. package/lib/esm/utils/common.js +460 -0
  55. package/lib/esm/utils/errors.d.ts +8 -0
  56. package/lib/esm/utils/errors.js +9 -0
  57. package/lib/esm/utils/logger.d.ts +5 -0
  58. package/lib/esm/utils/logger.js +23 -0
  59. package/lib/esm/utils/onekey/dapp.d.ts +14 -0
  60. package/lib/esm/utils/onekey/dapp.js +216 -0
  61. package/lib/esm/utils/onekey/error.d.ts +28 -0
  62. package/lib/esm/utils/onekey/error.js +22 -0
  63. package/lib/esm/utils/onekey/index.d.ts +48 -0
  64. package/lib/esm/utils/onekey/index.js +11 -0
  65. package/lib/esm/utils/onekey/signTx.d.ts +26 -0
  66. package/lib/esm/utils/onekey/signTx.js +266 -0
  67. package/lib/esm/utils/onekey/transaction.d.ts +5 -0
  68. package/lib/esm/utils/onekey/transaction.js +42 -0
  69. package/lib/esm/utils/onekey/txToOneKey.d.ts +67 -0
  70. package/lib/esm/utils/onekey/txToOneKey.js +477 -0
  71. package/lib/esm/utils/onekey/types.d.ts +79 -0
  72. package/lib/esm/utils/onekey/types.js +15 -0
  73. package/lib/esm/utils/trezor/index.d.ts +3 -0
  74. package/lib/esm/utils/trezor/index.js +3 -0
  75. package/lib/esm/utils/trezor/sign.d.ts +5 -0
  76. package/lib/esm/utils/trezor/sign.js +42 -0
  77. package/lib/esm/utils/trezor/transformations.d.ts +17 -0
  78. package/lib/esm/utils/trezor/transformations.js +60 -0
  79. package/package.json +61 -0
@@ -0,0 +1,216 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
2
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
3
+ import * as CardanoMessage from '@emurgo/cardano-message-signing-asmjs/cardano_message_signing';
4
+ import BigNumber from 'bignumber.js';
5
+ import { getUtxos as getRawUtxos, requestAccountKey } from './signTx';
6
+ import { DataSignError } from './error';
7
+ const getBalance = async (balances) => {
8
+ const value = await assetsToValue(balances);
9
+ return Buffer.from(value.to_bytes(), 'hex').toString('hex');
10
+ };
11
+ export const assetsToValue = async (assets) => {
12
+ const multiAsset = CardanoWasm.MultiAsset.new();
13
+ const lovelace = assets.find(asset => asset.unit === 'lovelace');
14
+ const policies = [
15
+ ...new Set(assets
16
+ .filter(asset => asset.unit !== 'lovelace')
17
+ .map(asset => asset.unit.slice(0, 56))),
18
+ ];
19
+ policies.forEach(policy => {
20
+ const policyAssets = assets.filter(asset => asset.unit.slice(0, 56) === policy);
21
+ const assetsValue = CardanoWasm.Assets.new();
22
+ policyAssets.forEach(asset => {
23
+ assetsValue.insert(CardanoWasm.AssetName.new(Buffer.from(asset.unit.slice(56), 'hex')), CardanoWasm.BigNum.from_str(asset.quantity));
24
+ });
25
+ multiAsset.insert(CardanoWasm.ScriptHash.from_bytes(Buffer.from(policy, 'hex')), assetsValue);
26
+ });
27
+ const value = CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(lovelace ? lovelace.quantity : '0'));
28
+ if (assets.length > 1 || !lovelace)
29
+ value.set_multiasset(multiAsset);
30
+ return value;
31
+ };
32
+ const getAddresses = async (addresses) => {
33
+ return addresses.map(address => {
34
+ const addr = Buffer.from(CardanoWasm.Address.from_bech32(address).to_bytes(), 'hex').toString('hex');
35
+ return addr;
36
+ });
37
+ };
38
+ const getUtxos = async (address, utxos, amount) => {
39
+ let converted = await getRawUtxos(address, utxos);
40
+ // filter utxos
41
+ if (amount) {
42
+ let filterVaule;
43
+ try {
44
+ filterVaule = CardanoWasm.Value.from_bytes(Buffer.from(amount, 'hex'));
45
+ }
46
+ catch (e) {
47
+ throw new Error('Invalid Request');
48
+ }
49
+ converted = converted === null || converted === void 0 ? void 0 : converted.filter(unspent => !unspent.output().amount().compare(filterVaule) ||
50
+ unspent.output().amount().compare(filterVaule) !== -1);
51
+ }
52
+ if (amount && Array.isArray(converted) && converted.length <= 0) {
53
+ return null;
54
+ }
55
+ return converted === null || converted === void 0 ? void 0 : converted.map(utxo => Buffer.from(utxo.to_bytes(), 'hex').toString('hex'));
56
+ };
57
+ const convertCborTxToEncodeTx = async (txHex, utxos, addresses, changeAddress) => {
58
+ var _a, _b;
59
+ const tx = CardanoWasm.Transaction.from_bytes(Buffer.from(txHex, 'hex'));
60
+ const body = tx.body();
61
+ // Fee
62
+ const fee = body.fee().to_str();
63
+ const totalFeeInNative = new BigNumber(fee).shiftedBy(-1 * 6).toFixed();
64
+ // inputs txs
65
+ const encodeInputs = [];
66
+ const inputs = [];
67
+ const inputsLen = body.inputs().len();
68
+ for (let i = 0; i < inputsLen; i++) {
69
+ const input = body.inputs().get(i);
70
+ const txHash = Buffer.from(input.transaction_id().to_bytes(), 'utf8').toString('hex');
71
+ const index = input.index();
72
+ inputs.push({ tx_hash: txHash, tx_index: index });
73
+ const utxo = utxos.find(utxo => utxo.tx_hash === txHash && +utxo.tx_index === +index);
74
+ encodeInputs.push(utxo);
75
+ }
76
+ // outputs txs
77
+ const outputs = [];
78
+ const outputsLen = body.outputs().len();
79
+ for (let i = 0; i < outputsLen; i++) {
80
+ const output = body.outputs().get(i);
81
+ const address = output.address().to_bech32();
82
+ const amount = output.amount().coin().to_str();
83
+ // get the asset from output
84
+ const assetsArray = [];
85
+ const multiasset = output.amount().multiasset();
86
+ if (multiasset) {
87
+ const keys = multiasset.keys(); // policy Ids of thee multiasset
88
+ const N = keys.len();
89
+ // (`${N} Multiassets in the UTXO`)
90
+ for (let i = 0; i < N; i++) {
91
+ const policyId = keys.get(i);
92
+ const policyIdHex = Buffer.from(policyId.to_bytes(), 'utf8').toString('hex');
93
+ const assets = multiasset.get(policyId);
94
+ if (assets) {
95
+ const assetNames = assets.keys();
96
+ const K = assetNames.len();
97
+ for (let j = 0; j < K; j++) {
98
+ const assetName = assetNames.get(j);
99
+ const assetNameHex = Buffer.from(assetName.name(), 'utf8').toString('hex');
100
+ const multiassetAmt = multiasset.get_asset(policyId, assetName);
101
+ assetsArray.push({
102
+ unit: `${policyIdHex}${assetNameHex}`,
103
+ quantity: multiassetAmt.to_str(),
104
+ });
105
+ }
106
+ }
107
+ }
108
+ }
109
+ // isChange: outputs length > 0 && address === changeAddress.address
110
+ const isChange = i > 0 && address === changeAddress.address;
111
+ outputs.push({
112
+ amount: amount,
113
+ address: address,
114
+ assets: assetsArray,
115
+ isChange,
116
+ });
117
+ }
118
+ const totalSpent = BigNumber.sum(...outputs.map(o => o.amount)).toFixed();
119
+ const token = (_b = (_a = outputs
120
+ .filter(o => !addresses.includes(o.address))
121
+ .find(o => o.assets.length > 0)) === null || _a === void 0 ? void 0 : _a.assets) === null || _b === void 0 ? void 0 : _b[0].unit;
122
+ const encodedTx = {
123
+ inputs: encodeInputs.map(input => (Object.assign(Object.assign({}, input), { txHash: input.tx_hash, outputIndex: input.tx_index }))),
124
+ outputs,
125
+ fee,
126
+ totalSpent,
127
+ totalFeeInNative,
128
+ transferInfo: {
129
+ from: encodeInputs[0].address,
130
+ to: outputs[0].address,
131
+ amount: totalSpent,
132
+ token,
133
+ },
134
+ tx: {
135
+ body: body.to_hex(),
136
+ hash: Buffer.from(CardanoWasm.hash_transaction(body).to_bytes(), 'utf8').toString('hex'),
137
+ size: 0,
138
+ rawTxHex: txHex,
139
+ },
140
+ signOnly: true,
141
+ };
142
+ console.log('Cardano DApp EncodedTx: ', encodedTx);
143
+ return encodedTx;
144
+ };
145
+ const signData = async (address, payload, xprv, accountIndex) => {
146
+ const keyHash = await extractKeyHash(address);
147
+ if (!keyHash) {
148
+ throw DataSignError.InvalidFormat;
149
+ }
150
+ const prefix = keyHash.startsWith('addr_vkh') ? 'addr_vkh' : 'stake_vkh';
151
+ const { paymentKey, stakeKey } = await requestAccountKey(xprv, accountIndex);
152
+ const accountKey = prefix === 'addr_vkh' ? paymentKey : stakeKey;
153
+ const publicKey = accountKey.to_public();
154
+ if (keyHash !== publicKey.hash().to_bech32(prefix))
155
+ throw DataSignError.ProofGeneration;
156
+ const protectedHeaders = CardanoMessage.HeaderMap.new();
157
+ protectedHeaders.set_algorithm_id(CardanoMessage.Label.from_algorithm_id(CardanoMessage.AlgorithmId.EdDSA));
158
+ // protectedHeaders.set_key_id(publicKey.as_bytes()); // Removed to adhere to CIP-30
159
+ protectedHeaders.set_header(CardanoMessage.Label.new_text('address'), CardanoMessage.CBORValue.new_bytes(Buffer.from(address, 'hex')));
160
+ const protectedSerialized = CardanoMessage.ProtectedHeaderMap.new(protectedHeaders);
161
+ const unprotectedHeaders = CardanoMessage.HeaderMap.new();
162
+ const headers = CardanoMessage.Headers.new(protectedSerialized, unprotectedHeaders);
163
+ const builder = CardanoMessage.COSESign1Builder.new(headers, Buffer.from(payload, 'hex'), false);
164
+ const toSign = builder.make_data_to_sign().to_bytes();
165
+ const signedSigStruc = accountKey.sign(toSign).to_bytes();
166
+ const coseSign1 = builder.build(signedSigStruc);
167
+ stakeKey.free();
168
+ paymentKey.free();
169
+ const key = CardanoMessage.COSEKey.new(CardanoMessage.Label.from_key_type(CardanoMessage.KeyType.OKP));
170
+ key.set_algorithm_id(CardanoMessage.Label.from_algorithm_id(CardanoMessage.AlgorithmId.EdDSA));
171
+ key.set_header(CardanoMessage.Label.new_int(CardanoMessage.Int.new_negative(CardanoMessage.BigNum.from_str('1'))), CardanoMessage.CBORValue.new_int(CardanoMessage.Int.new_i32(6))); // crv (-1) set to Ed25519 (6)
172
+ key.set_header(CardanoMessage.Label.new_int(CardanoMessage.Int.new_negative(CardanoMessage.BigNum.from_str('2'))), CardanoMessage.CBORValue.new_bytes(publicKey.as_bytes())); // x (-2) set to public key
173
+ return {
174
+ signature: Buffer.from(coseSign1.to_bytes()).toString('hex'),
175
+ key: Buffer.from(key.to_bytes()).toString('hex'),
176
+ };
177
+ };
178
+ export const extractKeyHash = async (address) => {
179
+ var _a;
180
+ try {
181
+ const addr = CardanoWasm.BaseAddress.from_address(CardanoWasm.Address.from_bytes(Buffer.from(address, 'hex')));
182
+ return (_a = addr.payment_cred()) === null || _a === void 0 ? void 0 : _a.to_keyhash().to_bech32('addr_vkh');
183
+ }
184
+ catch (e) {
185
+ // ignore
186
+ }
187
+ try {
188
+ const addr = CardanoWasm.EnterpriseAddress.from_address(CardanoWasm.Address.from_bytes(Buffer.from(address, 'hex')));
189
+ return addr.payment_cred().to_keyhash().to_bech32('addr_vkh');
190
+ }
191
+ catch (e) {
192
+ // ignore
193
+ }
194
+ try {
195
+ const addr = CardanoWasm.PointerAddress.from_address(CardanoWasm.Address.from_bytes(Buffer.from(address, 'hex')));
196
+ return addr.payment_cred().to_keyhash().to_bech32('addr_vkh');
197
+ }
198
+ catch (e) {
199
+ // ignore
200
+ }
201
+ try {
202
+ const addr = CardanoWasm.RewardAddress.from_address(CardanoWasm.Address.from_bytes(Buffer.from(address, 'hex')));
203
+ return addr.payment_cred().to_keyhash().to_bech32('stake_vkh');
204
+ }
205
+ catch (e) {
206
+ // ignore
207
+ }
208
+ throw DataSignError.AddressNotPK;
209
+ };
210
+ export const dAppUtils = {
211
+ getBalance,
212
+ getAddresses,
213
+ getUtxos,
214
+ convertCborTxToEncodeTx,
215
+ signData,
216
+ };
@@ -0,0 +1,28 @@
1
+ export declare const TxSignError: {
2
+ ProofGeneration: {
3
+ code: number;
4
+ info: string;
5
+ };
6
+ UserDeclined: {
7
+ code: number;
8
+ info: string;
9
+ };
10
+ };
11
+ export declare const DataSignError: {
12
+ ProofGeneration: {
13
+ code: number;
14
+ info: string;
15
+ };
16
+ AddressNotPK: {
17
+ code: number;
18
+ info: string;
19
+ };
20
+ UserDeclined: {
21
+ code: number;
22
+ info: string;
23
+ };
24
+ InvalidFormat: {
25
+ code: number;
26
+ info: string;
27
+ };
28
+ };
@@ -0,0 +1,22 @@
1
+ export const TxSignError = {
2
+ ProofGeneration: {
3
+ code: 1,
4
+ info: 'User has accepted the transaction sign, but the wallet was unable to sign the transaction (e.g. not having some of the private keys).',
5
+ },
6
+ UserDeclined: { code: 2, info: 'User declined to sign the transaction.' },
7
+ };
8
+ export const DataSignError = {
9
+ ProofGeneration: {
10
+ code: 1,
11
+ info: 'Wallet could not sign the data (e.g. does not have the secret key associated with the address).',
12
+ },
13
+ AddressNotPK: {
14
+ code: 2,
15
+ info: 'Address was not a P2PK address or Reward address and thus had no SK associated with it.',
16
+ },
17
+ UserDeclined: { code: 3, info: 'User declined to sign the data.' },
18
+ InvalidFormat: {
19
+ code: 4,
20
+ info: 'If a wallet enforces data format requirements, this error signifies that the data did not conform to valid formats.',
21
+ },
22
+ };
@@ -0,0 +1,48 @@
1
+ import { dAppUtils } from './dapp';
2
+ declare const onekeyUtils: {
3
+ composeTxPlan: (transferInfo: import("./types").ITransferInfo, accountXpub: string, utxos: import("./types").IAdaUTXO[], changeAddress: string, outputs: import("./types").IOutput[], options?: {
4
+ debug: boolean;
5
+ } | undefined) => Promise<import("../../types/types").PrecomposedTransaction>;
6
+ signTransaction: (txBodyHex: string, address: string, accountIndex: number, utxos: import("./types").IAdaUTXO[], xprv: string, signOnly: boolean, partialSign?: boolean | undefined) => Promise<{
7
+ signedTx: string;
8
+ txid: string;
9
+ }>;
10
+ signTx: (keys: {
11
+ accountKey: import("@emurgo/cardano-serialization-lib-asmjs").Bip32PrivateKey;
12
+ paymentKey: import("@emurgo/cardano-serialization-lib-asmjs").PrivateKey;
13
+ stakeKey: import("@emurgo/cardano-serialization-lib-asmjs").PrivateKey;
14
+ }, tx: string, keyHashes: string[], partialSign?: boolean) => Promise<import("@emurgo/cardano-serialization-lib-asmjs").TransactionWitnessSet>;
15
+ txToOneKey: (rawTx: string, network: number, initKeys: {
16
+ payment: {
17
+ hash: string | null;
18
+ path: string | null;
19
+ };
20
+ stake: {
21
+ hash: string | null;
22
+ path: string | null;
23
+ };
24
+ }, xpub: string, changeAddress: import("./types").IChangeAddress) => Promise<{
25
+ signingMode: import("./txToOneKey").CardanoTxSigningMode.ORDINARY_TRANSACTION | import("./txToOneKey").CardanoTxSigningMode.POOL_REGISTRATION_AS_OWNER | import("./txToOneKey").CardanoTxSigningMode.PLUTUS_TRANSACTION;
26
+ outputs: never[];
27
+ fee: string;
28
+ ttl: string | null;
29
+ validityIntervalStart: any;
30
+ certificates: [] | null;
31
+ withdrawals: null;
32
+ auxiliaryData: {
33
+ hash: string;
34
+ } | null;
35
+ mint: null;
36
+ scriptDataHash: string | null;
37
+ collateralInputs: null;
38
+ requiredSigners: null;
39
+ protocolMagic: number;
40
+ networkId: number;
41
+ includeNetworkId: boolean;
42
+ additionalWitnessRequests: null;
43
+ collateralReturn: null;
44
+ totalCollateral: string | null;
45
+ referenceInputs: null;
46
+ }>;
47
+ };
48
+ export { onekeyUtils, dAppUtils };
@@ -0,0 +1,11 @@
1
+ import { composeTxPlan } from './transaction';
2
+ import { signTransaction, signTx } from './signTx';
3
+ import { dAppUtils } from './dapp';
4
+ import { txToOneKey } from './txToOneKey';
5
+ const onekeyUtils = {
6
+ composeTxPlan,
7
+ signTransaction,
8
+ signTx,
9
+ txToOneKey,
10
+ };
11
+ export { onekeyUtils, dAppUtils };
@@ -0,0 +1,26 @@
1
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
+ import { IAdaUTXO } from './types';
3
+ declare type SignKeys = {
4
+ accountKey: CardanoWasm.Bip32PrivateKey;
5
+ paymentKey: CardanoWasm.PrivateKey;
6
+ stakeKey: CardanoWasm.PrivateKey;
7
+ };
8
+ export declare const signTransaction: (txBodyHex: string, address: string, accountIndex: number, utxos: IAdaUTXO[], xprv: string, signOnly: boolean, partialSign?: boolean) => Promise<{
9
+ signedTx: string;
10
+ txid: string;
11
+ }>;
12
+ /**
13
+ *
14
+ * @param {string} tx - cbor hex string
15
+ * @param {Array<string>} keyHashes
16
+ * @param {string} password
17
+ * @returns {string} witness set as hex string
18
+ */
19
+ export declare const signTx: (keys: SignKeys, tx: string, keyHashes: string[], partialSign?: boolean) => Promise<CardanoWasm.TransactionWitnessSet>;
20
+ export declare const getUtxos: (address: string, utxos: IAdaUTXO[]) => Promise<CardanoWasm.TransactionUnspentOutput[] | null>;
21
+ export declare const requestAccountKey: (xprv: string, accountIndex: number) => Promise<{
22
+ accountKey: any;
23
+ paymentKey: any;
24
+ stakeKey: any;
25
+ }>;
26
+ export {};
@@ -0,0 +1,266 @@
1
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
+ import { TxSignError } from './error';
3
+ export const signTransaction = async (txBodyHex, address, accountIndex, utxos, xprv, signOnly, partialSign) => {
4
+ const { paymentKey, stakeKey, accountKey } = await requestAccountKey(xprv, accountIndex);
5
+ const serializedUtxos = await getUtxos(address, utxos);
6
+ if (!serializedUtxos || serializedUtxos === null) {
7
+ throw new Error('no utxos');
8
+ }
9
+ const transactionWitnessSet = CardanoWasm.TransactionWitnessSet.new();
10
+ const rawTx = CardanoWasm.Transaction.new(CardanoWasm.TransactionBody.from_hex(txBodyHex), CardanoWasm.TransactionWitnessSet.from_bytes(transactionWitnessSet.to_bytes()));
11
+ const keyHashes = await getKeyHashes(rawTx, serializedUtxos, { paymentAddr: address });
12
+ const witnessSet = await signTx({ paymentKey, stakeKey, accountKey }, Buffer.from(rawTx.to_bytes(), 'utf8').toString('hex'), keyHashes.key, partialSign);
13
+ if (signOnly) {
14
+ return {
15
+ signedTx: Buffer.from(witnessSet.to_bytes(), 'utf8').toString('hex'),
16
+ txid: '',
17
+ };
18
+ }
19
+ const transaction = CardanoWasm.Transaction.new(rawTx.body(), witnessSet, rawTx.auxiliary_data());
20
+ const signedTx = Buffer.from(transaction.to_bytes(), 'hex').toString('hex');
21
+ const hash = CardanoWasm.hash_transaction(transaction.body()).to_hex();
22
+ return {
23
+ signedTx,
24
+ txid: hash,
25
+ };
26
+ };
27
+ /**
28
+ *
29
+ * @param {string} tx - cbor hex string
30
+ * @param {Array<string>} keyHashes
31
+ * @param {string} password
32
+ * @returns {string} witness set as hex string
33
+ */
34
+ export const signTx = async (keys, tx, keyHashes, partialSign = false) => {
35
+ const { paymentKey, stakeKey } = keys;
36
+ const paymentKeyHash = Buffer.from(paymentKey === null || paymentKey === void 0 ? void 0 : paymentKey.to_public().hash().to_bytes(), 'hex').toString('hex');
37
+ const stakeKeyHash = Buffer.from(stakeKey.to_public().hash().to_bytes(), 'hex').toString('hex');
38
+ const rawTx = CardanoWasm.Transaction.from_bytes(Buffer.from(tx, 'hex'));
39
+ const txWitnessSet = CardanoWasm.TransactionWitnessSet.new();
40
+ const vkeyWitnesses = CardanoWasm.Vkeywitnesses.new();
41
+ const txHash = CardanoWasm.hash_transaction(rawTx.body());
42
+ keyHashes.forEach(keyHash => {
43
+ let signingKey;
44
+ if (keyHash === paymentKeyHash)
45
+ signingKey = paymentKey;
46
+ else if (keyHash === stakeKeyHash)
47
+ signingKey = stakeKey;
48
+ else if (!partialSign)
49
+ throw TxSignError.ProofGeneration;
50
+ else
51
+ return;
52
+ const vkey = CardanoWasm.make_vkey_witness(txHash, signingKey);
53
+ vkeyWitnesses.add(vkey);
54
+ });
55
+ stakeKey.free();
56
+ // stakeKey = null;
57
+ paymentKey.free();
58
+ // paymentKey = null;
59
+ txWitnessSet.set_vkeys(vkeyWitnesses);
60
+ return txWitnessSet;
61
+ };
62
+ const getKeyHashes = async (tx, utxos, account) => {
63
+ var _a, _b, _c, _d;
64
+ let requiredKeyHashes = [];
65
+ const baseAddr = CardanoWasm.BaseAddress.from_address(CardanoWasm.Address.from_bech32(account.paymentAddr));
66
+ if (!baseAddr)
67
+ return { key: [], keyKind: [] };
68
+ const paymentKeyHash = Buffer.from((_b = (_a = baseAddr.payment_cred().to_keyhash()) === null || _a === void 0 ? void 0 : _a.to_bytes()) !== null && _b !== void 0 ? _b : '').toString('hex');
69
+ const stakeKeyHash = Buffer.from((_d = (_c = baseAddr.stake_cred().to_keyhash()) === null || _c === void 0 ? void 0 : _c.to_bytes()) !== null && _d !== void 0 ? _d : '').toString('hex');
70
+ //get key hashes from inputs
71
+ const inputs = tx.body().inputs();
72
+ for (let i = 0; i < inputs.len(); i++) {
73
+ const input = inputs.get(i);
74
+ const txHash = Buffer.from(input.transaction_id().to_bytes()).toString('hex');
75
+ const index = input.index();
76
+ if (utxos.some(utxo => Buffer.from(utxo.input().transaction_id().to_bytes()).toString('hex') === txHash && utxo.input().index() === index)) {
77
+ requiredKeyHashes.push(paymentKeyHash);
78
+ }
79
+ else {
80
+ requiredKeyHashes.push('<not_owned_key_hash>');
81
+ }
82
+ }
83
+ //get key hashes from certificates
84
+ const txBody = tx.body();
85
+ const keyHashFromCert = txBody => {
86
+ for (let i = 0; i < txBody.certs().len(); i++) {
87
+ const cert = txBody.certs().get(i);
88
+ if (cert.kind() === 0) {
89
+ const credential = cert.as_stake_registration().stake_credential();
90
+ if (credential.kind() === 0) {
91
+ // stake registration doesn't required key hash
92
+ }
93
+ }
94
+ else if (cert.kind() === 1) {
95
+ const credential = cert.as_stake_deregistration().stake_credential();
96
+ if (credential.kind() === 0) {
97
+ const keyHash = Buffer.from(credential.to_keyhash().to_bytes()).toString('hex');
98
+ requiredKeyHashes.push(keyHash);
99
+ }
100
+ }
101
+ else if (cert.kind() === 2) {
102
+ const credential = cert.as_stake_delegation().stake_credential();
103
+ if (credential.kind() === 0) {
104
+ const keyHash = Buffer.from(credential.to_keyhash().to_bytes()).toString('hex');
105
+ requiredKeyHashes.push(keyHash);
106
+ }
107
+ }
108
+ else if (cert.kind() === 3) {
109
+ const owners = cert.as_pool_registration().pool_params().pool_owners();
110
+ for (let i = 0; i < owners.len(); i++) {
111
+ const keyHash = Buffer.from(owners.get(i).to_bytes()).toString('hex');
112
+ requiredKeyHashes.push(keyHash);
113
+ }
114
+ }
115
+ else if (cert.kind() === 4) {
116
+ const operator = cert.as_pool_retirement().pool_keyhash().to_hex();
117
+ requiredKeyHashes.push(operator);
118
+ }
119
+ else if (cert.kind() === 6) {
120
+ const instant_reward = cert
121
+ .as_move_instantaneous_rewards_cert()
122
+ .move_instantaneous_reward()
123
+ .as_to_stake_creds()
124
+ .keys();
125
+ for (let i = 0; i < instant_reward.len(); i++) {
126
+ const credential = instant_reward.get(i);
127
+ if (credential.kind() === 0) {
128
+ const keyHash = Buffer.from(credential.to_keyhash().to_bytes()).toString('hex');
129
+ requiredKeyHashes.push(keyHash);
130
+ }
131
+ }
132
+ }
133
+ }
134
+ };
135
+ if (txBody.certs())
136
+ keyHashFromCert(txBody);
137
+ // key hashes from withdrawals
138
+ const withdrawals = txBody.withdrawals();
139
+ const keyHashFromWithdrawal = withdrawals => {
140
+ const rewardAddresses = withdrawals.keys();
141
+ for (let i = 0; i < rewardAddresses.len(); i++) {
142
+ const credential = rewardAddresses.get(i).payment_cred();
143
+ if (credential.kind() === 0) {
144
+ requiredKeyHashes.push(credential.to_keyhash().to_hex());
145
+ }
146
+ }
147
+ };
148
+ if (withdrawals)
149
+ keyHashFromWithdrawal(withdrawals);
150
+ //get key hashes from scripts
151
+ const scripts = tx.witness_set().native_scripts();
152
+ const keyHashFromScript = scripts => {
153
+ for (let i = 0; i < scripts.len(); i++) {
154
+ const script = scripts.get(i);
155
+ if (script.kind() === 0) {
156
+ const keyHash = Buffer.from(script.as_script_pubkey().addr_keyhash().to_bytes()).toString('hex');
157
+ requiredKeyHashes.push(keyHash);
158
+ }
159
+ if (script.kind() === 1) {
160
+ return keyHashFromScript(script.as_script_all().native_scripts());
161
+ }
162
+ if (script.kind() === 2) {
163
+ return keyHashFromScript(script.as_script_any().native_scripts());
164
+ }
165
+ if (script.kind() === 3) {
166
+ return keyHashFromScript(script.as_script_n_of_k().native_scripts());
167
+ }
168
+ }
169
+ };
170
+ if (scripts)
171
+ keyHashFromScript(scripts);
172
+ //get keyHashes from required signers
173
+ const requiredSigners = tx.body().required_signers();
174
+ if (requiredSigners) {
175
+ for (let i = 0; i < requiredSigners.len(); i++) {
176
+ requiredKeyHashes.push(Buffer.from(requiredSigners.get(i).to_bytes()).toString('hex'));
177
+ }
178
+ }
179
+ //get keyHashes from collateral
180
+ const collateral = txBody.collateral();
181
+ if (collateral) {
182
+ // TODO: Collateral KeyHashed
183
+ // for (let i = 0; i < collateral.len(); i++) {
184
+ // const c = collateral.get(i);
185
+ // const utxo = await getSpecificUtxo(
186
+ // Buffer.from(c.transaction_id().to_bytes()).toString('hex'),
187
+ // c.index(),
188
+ // );
189
+ // if (utxo) {
190
+ // const address = CardanoWasm.Address.from_bech32(utxo.address);
191
+ // requiredKeyHashes.push(await getPaymentKeyHash(address));
192
+ // }
193
+ // }
194
+ }
195
+ const keyKind = [];
196
+ requiredKeyHashes = [...new Set(requiredKeyHashes)];
197
+ if (requiredKeyHashes.includes(paymentKeyHash))
198
+ keyKind.push('payment');
199
+ if (requiredKeyHashes.includes(stakeKeyHash))
200
+ keyKind.push('stake');
201
+ return {
202
+ key: requiredKeyHashes,
203
+ keyKind,
204
+ };
205
+ };
206
+ export const getUtxos = async (address, utxos) => {
207
+ const paymentAddr = getPaymentHexAddress(address);
208
+ const converted = utxos.map(utxo => utxoFromJson(utxo, paymentAddr));
209
+ if (converted.length <= 0) {
210
+ return null;
211
+ }
212
+ return Promise.resolve(converted);
213
+ };
214
+ const getPaymentHexAddress = (address) => {
215
+ const paymentAddr = Buffer.from(CardanoWasm.Address.from_bech32(address).to_bytes(), 'hex').toString('hex');
216
+ return paymentAddr;
217
+ };
218
+ /**
219
+ *
220
+ * @param {JSON} output
221
+ * @param {BaseAddress} address
222
+ * @returns
223
+ */
224
+ const utxoFromJson = (output, address) => CardanoWasm.TransactionUnspentOutput.new(CardanoWasm.TransactionInput.new(CardanoWasm.TransactionHash.from_bytes(Buffer.from(output.tx_hash, 'hex')), Number(output.output_index)), CardanoWasm.TransactionOutput.new(CardanoWasm.Address.from_bytes(Buffer.from(address, 'hex')), assetsToValue(output.amount)));
225
+ const assetsToValue = (assets) => {
226
+ const multiAsset = CardanoWasm.MultiAsset.new();
227
+ const lovelace = assets.find(asset => asset.unit === 'lovelace');
228
+ const policies = [
229
+ ...new Set(assets
230
+ .filter(asset => asset.unit !== 'lovelace')
231
+ .map(asset => asset.unit.slice(0, 56))),
232
+ ];
233
+ policies.forEach(policy => {
234
+ const policyAssets = assets.filter(asset => asset.unit.slice(0, 56) === policy);
235
+ const assetsValue = CardanoWasm.Assets.new();
236
+ policyAssets.forEach(asset => {
237
+ assetsValue.insert(CardanoWasm.AssetName.new(Buffer.from(asset.unit.slice(56), 'hex')), CardanoWasm.BigNum.from_str(asset.quantity));
238
+ });
239
+ multiAsset.insert(CardanoWasm.ScriptHash.from_bytes(Buffer.from(policy, 'hex')), assetsValue);
240
+ });
241
+ const value = CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(lovelace ? lovelace.quantity : '0'));
242
+ if (assets.length > 1 || !lovelace) {
243
+ value.set_multiasset(multiAsset);
244
+ }
245
+ return value;
246
+ };
247
+ const harden = (num) => {
248
+ return 0x80000000 + num;
249
+ };
250
+ export const requestAccountKey = async (xprv, accountIndex) => {
251
+ let accountKey;
252
+ try {
253
+ accountKey = CardanoWasm.Bip32PrivateKey.from_bech32(xprv)
254
+ .derive(harden(1852)) // purpose
255
+ .derive(harden(1815)) // coin type;
256
+ .derive(harden(parseInt(`${accountIndex}`)));
257
+ }
258
+ catch (e) {
259
+ throw new Error('Wrong private key');
260
+ }
261
+ return {
262
+ accountKey,
263
+ paymentKey: accountKey.derive(0).derive(0).to_raw_key(),
264
+ stakeKey: accountKey.derive(2).derive(0).to_raw_key(),
265
+ };
266
+ };
@@ -0,0 +1,5 @@
1
+ import { PrecomposedTransaction } from '../../types/types';
2
+ import { ITransferInfo, IAdaUTXO, IOutput } from './types';
3
+ export declare const composeTxPlan: (transferInfo: ITransferInfo, accountXpub: string, utxos: IAdaUTXO[], changeAddress: string, outputs: IOutput[], options?: {
4
+ debug: boolean;
5
+ }) => Promise<PrecomposedTransaction>;
@@ -0,0 +1,42 @@
1
+ import BigNumber from 'bignumber.js';
2
+ import { coinSelection } from '../../index';
3
+ import { getLogger } from '../logger';
4
+ export const composeTxPlan = (transferInfo, accountXpub, utxos, changeAddress, outputs, options) => {
5
+ var _a;
6
+ const logger = getLogger(!!(options === null || options === void 0 ? void 0 : options.debug));
7
+ const transformUtxos = utxos.map(utxo => {
8
+ var _a;
9
+ return (Object.assign(Object.assign({}, utxo), { txHash: utxo.tx_hash, outputIndex: utxo.output_index, address: (_a = utxo.address) !== null && _a !== void 0 ? _a : transferInfo.from }));
10
+ });
11
+ try {
12
+ const txPlan = coinSelection({
13
+ utxos: transformUtxos,
14
+ outputs: outputs,
15
+ changeAddress,
16
+ certificates: [],
17
+ withdrawals: [],
18
+ accountPubKey: accountXpub,
19
+ }, {
20
+ debug: (_a = options === null || options === void 0 ? void 0 : options.debug) !== null && _a !== void 0 ? _a : false,
21
+ });
22
+ return Promise.resolve(txPlan);
23
+ }
24
+ catch (err) {
25
+ if ((err === null || err === void 0 ? void 0 : err.code) === 'UTXO_BALANCE_INSUFFICIENT') {
26
+ logger.debug('UTxO balance insufficient');
27
+ if (outputs.length === 1) {
28
+ const fixedOutput = [...outputs];
29
+ const amountBN = new BigNumber(outputs[0].amount);
30
+ const oneLovelace = new BigNumber('100000');
31
+ if (amountBN.gte(oneLovelace)) {
32
+ fixedOutput[0].amount = amountBN.minus(oneLovelace).toFixed();
33
+ return composeTxPlan(transferInfo, accountXpub, utxos, changeAddress, fixedOutput);
34
+ }
35
+ }
36
+ throw err;
37
+ }
38
+ else {
39
+ throw err;
40
+ }
41
+ }
42
+ };