@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.
- package/CHANGELOG.MD +25 -0
- package/README.md +183 -0
- package/lib/cjs/constants/index.d.ts +40 -0
- package/lib/cjs/constants/index.js +69 -0
- package/lib/cjs/index.d.ts +6 -0
- package/lib/cjs/index.js +101 -0
- package/lib/cjs/methods/largestFirst.d.ts +2 -0
- package/lib/cjs/methods/largestFirst.js +201 -0
- package/lib/cjs/methods/randomImprove.d.ts +2 -0
- package/lib/cjs/methods/randomImprove.js +187 -0
- package/lib/cjs/types/trezor.d.ts +45 -0
- package/lib/cjs/types/trezor.js +8 -0
- package/lib/cjs/types/types.d.ts +116 -0
- package/lib/cjs/types/types.js +17 -0
- package/lib/cjs/utils/common.d.ts +46 -0
- package/lib/cjs/utils/common.js +514 -0
- package/lib/cjs/utils/errors.d.ts +8 -0
- package/lib/cjs/utils/errors.js +13 -0
- package/lib/cjs/utils/logger.d.ts +5 -0
- package/lib/cjs/utils/logger.js +27 -0
- package/lib/cjs/utils/onekey/dapp.d.ts +14 -0
- package/lib/cjs/utils/onekey/dapp.js +247 -0
- package/lib/cjs/utils/onekey/error.d.ts +28 -0
- package/lib/cjs/utils/onekey/error.js +25 -0
- package/lib/cjs/utils/onekey/index.d.ts +48 -0
- package/lib/cjs/utils/onekey/index.js +15 -0
- package/lib/cjs/utils/onekey/signTx.d.ts +26 -0
- package/lib/cjs/utils/onekey/signTx.js +296 -0
- package/lib/cjs/utils/onekey/transaction.d.ts +5 -0
- package/lib/cjs/utils/onekey/transaction.js +49 -0
- package/lib/cjs/utils/onekey/txToOneKey.d.ts +67 -0
- package/lib/cjs/utils/onekey/txToOneKey.js +504 -0
- package/lib/cjs/utils/onekey/types.d.ts +79 -0
- package/lib/cjs/utils/onekey/types.js +16 -0
- package/lib/cjs/utils/trezor/index.d.ts +3 -0
- package/lib/cjs/utils/trezor/index.js +9 -0
- package/lib/cjs/utils/trezor/sign.d.ts +5 -0
- package/lib/cjs/utils/trezor/sign.js +69 -0
- package/lib/cjs/utils/trezor/transformations.d.ts +17 -0
- package/lib/cjs/utils/trezor/transformations.js +66 -0
- package/lib/esm/constants/index.d.ts +40 -0
- package/lib/esm/constants/index.js +43 -0
- package/lib/esm/index.d.ts +6 -0
- package/lib/esm/index.js +73 -0
- package/lib/esm/methods/largestFirst.d.ts +2 -0
- package/lib/esm/methods/largestFirst.js +174 -0
- package/lib/esm/methods/randomImprove.d.ts +2 -0
- package/lib/esm/methods/randomImprove.js +160 -0
- package/lib/esm/types/trezor.d.ts +45 -0
- package/lib/esm/types/trezor.js +5 -0
- package/lib/esm/types/types.d.ts +116 -0
- package/lib/esm/types/types.js +14 -0
- package/lib/esm/utils/common.d.ts +46 -0
- package/lib/esm/utils/common.js +460 -0
- package/lib/esm/utils/errors.d.ts +8 -0
- package/lib/esm/utils/errors.js +9 -0
- package/lib/esm/utils/logger.d.ts +5 -0
- package/lib/esm/utils/logger.js +23 -0
- package/lib/esm/utils/onekey/dapp.d.ts +14 -0
- package/lib/esm/utils/onekey/dapp.js +216 -0
- package/lib/esm/utils/onekey/error.d.ts +28 -0
- package/lib/esm/utils/onekey/error.js +22 -0
- package/lib/esm/utils/onekey/index.d.ts +48 -0
- package/lib/esm/utils/onekey/index.js +11 -0
- package/lib/esm/utils/onekey/signTx.d.ts +26 -0
- package/lib/esm/utils/onekey/signTx.js +266 -0
- package/lib/esm/utils/onekey/transaction.d.ts +5 -0
- package/lib/esm/utils/onekey/transaction.js +42 -0
- package/lib/esm/utils/onekey/txToOneKey.d.ts +67 -0
- package/lib/esm/utils/onekey/txToOneKey.js +477 -0
- package/lib/esm/utils/onekey/types.d.ts +79 -0
- package/lib/esm/utils/onekey/types.js +15 -0
- package/lib/esm/utils/trezor/index.d.ts +3 -0
- package/lib/esm/utils/trezor/index.js +3 -0
- package/lib/esm/utils/trezor/sign.d.ts +5 -0
- package/lib/esm/utils/trezor/sign.js +42 -0
- package/lib/esm/utils/trezor/transformations.d.ts +17 -0
- package/lib/esm/utils/trezor/transformations.js +60 -0
- package/package.json +61 -0
package/CHANGELOG.MD
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## Unreleased
|
|
9
|
+
|
|
10
|
+
## [2.1.0] - 2022-11-22
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- occasionally too low fee while using `setMax` on token output
|
|
15
|
+
- order of inputs returned in txPlan did not always match the order of inputs in constructed transaction CBOR
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- Upgraded deps, cardano-serialization-lib to babbage-compatible release (v11)
|
|
20
|
+
|
|
21
|
+
## [2.0.0] - 2022-02-14
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
|
|
25
|
+
- Initial release
|
package/README.md
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# coin-selection
|
|
2
|
+
|
|
3
|
+
Minimal implementation of Cardano coin selection algorithms (see [CIP-2](https://cips.cardano.org/cips/cip2/)) developed solely for OneKeyHQ.
|
|
4
|
+
Under the hood it leverages Cardano Serialization Lib via WASM module.
|
|
5
|
+
|
|
6
|
+
## Features
|
|
7
|
+
|
|
8
|
+
- Final tx plan: Compose transaction plan for given inputs (shelley utxos only), certificates (support for stake (de)registration and delegation), withdrawals,...
|
|
9
|
+
- Draft tx plan: Return basic information about potential transaction (such as a size and fee) even for incomplete inputs (without an recipient address or an amount)
|
|
10
|
+
- Set max: Calculate the max amount of an asset that is possible to include in a transaction output
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
const txPlan = coinSelection(
|
|
16
|
+
txParams: {
|
|
17
|
+
utxos: Utxo[];
|
|
18
|
+
outputs: UserOutput[];
|
|
19
|
+
changeAddress: string;
|
|
20
|
+
certificates: Certificate[];
|
|
21
|
+
withdrawals: Withdrawal[];
|
|
22
|
+
accountPubKey: string;
|
|
23
|
+
ttl?: number;
|
|
24
|
+
},
|
|
25
|
+
options: {
|
|
26
|
+
feeParams?: { a: string };
|
|
27
|
+
debug?: boolean;
|
|
28
|
+
forceLargestFirstSelection?: boolean;
|
|
29
|
+
}
|
|
30
|
+
);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### `coinSelection(txParams, options)`
|
|
34
|
+
|
|
35
|
+
#### `txParams`
|
|
36
|
+
|
|
37
|
+
- `utxos`: Array of account's utxo
|
|
38
|
+
- `outputs`: Requested outputs provided by an user
|
|
39
|
+
- `changeAddress`: An address where the change will be sent
|
|
40
|
+
- `certificates`: Stake registration and/or delegation certificates (stake pool registration is not supported)
|
|
41
|
+
- `withdrawals`: Withdrawal requests
|
|
42
|
+
- `accountPubKey`: Account public key
|
|
43
|
+
- `ttl`: Time-to-live for the transaction
|
|
44
|
+
|
|
45
|
+
#### `Options`
|
|
46
|
+
|
|
47
|
+
- `forceLargestFirstSelection`: Always use largest-first algorithm
|
|
48
|
+
- `debug`: print debug information about coin-selection (selected utxos, outputs including change output,...)
|
|
49
|
+
|
|
50
|
+
## Example
|
|
51
|
+
|
|
52
|
+
### Final tx plan
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
|
|
56
|
+
export const utxo1 = {
|
|
57
|
+
address:
|
|
58
|
+
'addr1q860vxljhadqxnrrsr2j6yxnwpdkyquq74lmghx502aj0r28d2kd47hsre5v9urjyu8s0ryk38dxzw0t5jesncw4v90sp0878u',
|
|
59
|
+
txHash: '3c388acb799a37a4f1cc99bec7626637b0b80626b9ef7c7a687282cab701178d',
|
|
60
|
+
outputIndex: 0,
|
|
61
|
+
amount: [
|
|
62
|
+
{
|
|
63
|
+
quantity: '5000000',
|
|
64
|
+
unit: 'lovelace',
|
|
65
|
+
},
|
|
66
|
+
],
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export const utxo2 = {
|
|
70
|
+
address:
|
|
71
|
+
'addr1q860vxljhadqxnrrsr2j6yxnwpdkyquq74lmghx502aj0r28d2kd47hsre5v9urjyu8s0ryk38dxzw0t5jesncw4v90sp0878u',
|
|
72
|
+
txHash: '9e63fddf20cb7b5472e2c9a1bb4bbe3112b8f2b22e45bc441206bcddde5c58a0',
|
|
73
|
+
outputIndex: 1,
|
|
74
|
+
amount: [
|
|
75
|
+
{
|
|
76
|
+
quantity: '5000000',
|
|
77
|
+
unit: 'lovelace',
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
quantity: '1000',
|
|
81
|
+
unit: '02477d7c23b4c2834b0be8ca8578dde47af0cc82a964688f6fc95a7a47524943',
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const txPlan = coinSelection(
|
|
87
|
+
txParams: {
|
|
88
|
+
utxos: Utxo[];
|
|
89
|
+
outputs: [
|
|
90
|
+
{
|
|
91
|
+
address:
|
|
92
|
+
'addr1qya0nkzrf04gmcpu66vdt7sudwptnyg5df6475y7jhtt2wc44vzmgrfy6wwf69xlaszdslksw8evveyykw4c82eavq7sx29tlc',
|
|
93
|
+
amount: '1000000',
|
|
94
|
+
assets: [],
|
|
95
|
+
setMax: false,
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
address:
|
|
99
|
+
'addr1qya0nkzrf04gmcpu66vdt7sudwptnyg5df6475y7jhtt2wc44vzmgrfy6wwf69xlaszdslksw8evveyykw4c82eavq7sx29tlc',
|
|
100
|
+
amount: undefined,
|
|
101
|
+
assets: [],
|
|
102
|
+
setMax: true,
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
changeAddress: `addr1q8u2f05rprqjhygz22m06mhy4xrnqvqqpyuzhmxqfxnwvxz8d2kd47hsre5v9urjyu8s0ryk38dxzw0t5jesncw4v90s22tk0f`,
|
|
106
|
+
certificates: [],
|
|
107
|
+
withdrawals: [],
|
|
108
|
+
accountPubKey:
|
|
109
|
+
'ec8fdf616242f430855ad7477acda53395eb30c295f5a7ef038712578877375b5a2f00353c9c5cc88c7ff18e71dc08724d90fc238213b789c0b02438e336be07',
|
|
110
|
+
},
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
// txPlan
|
|
114
|
+
// {
|
|
115
|
+
// max: '7480901',
|
|
116
|
+
// totalSpent: '8655202',
|
|
117
|
+
// fee: '174301',
|
|
118
|
+
// inputs: [utxo1, utxo2],
|
|
119
|
+
// outputs: [
|
|
120
|
+
// {
|
|
121
|
+
// address:
|
|
122
|
+
// 'addr1qya0nkzrf04gmcpu66vdt7sudwptnyg5df6475y7jhtt2wc44vzmgrfy6wwf69xlaszdslksw8evveyykw4c82eavq7sx29tlc',
|
|
123
|
+
// amount: '1000000',
|
|
124
|
+
// assets: [],
|
|
125
|
+
// setMax: false,
|
|
126
|
+
// },
|
|
127
|
+
// {
|
|
128
|
+
// address:
|
|
129
|
+
// 'addr1qya0nkzrf04gmcpu66vdt7sudwptnyg5df6475y7jhtt2wc44vzmgrfy6wwf69xlaszdslksw8evveyykw4c82eavq7sx29tlc',
|
|
130
|
+
// amount: '7480901',
|
|
131
|
+
// assets: [],
|
|
132
|
+
// setMax: true,
|
|
133
|
+
// },
|
|
134
|
+
// {
|
|
135
|
+
// isChange: true,
|
|
136
|
+
// address: changeAddress,
|
|
137
|
+
// amount: '1344798',
|
|
138
|
+
// assets: [
|
|
139
|
+
// {
|
|
140
|
+
// quantity: '1000',
|
|
141
|
+
// unit: '02477d7c23b4c2834b0be8ca8578dde47af0cc82a964688f6fc95a7a47524943',
|
|
142
|
+
// },
|
|
143
|
+
// ],
|
|
144
|
+
// },
|
|
145
|
+
// ],
|
|
146
|
+
// },
|
|
147
|
+
;
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Draft tx plan
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
|
|
154
|
+
const txPlan = coinSelection(
|
|
155
|
+
{
|
|
156
|
+
utxos: [utxo1];
|
|
157
|
+
outputs: [
|
|
158
|
+
{
|
|
159
|
+
address: undefined, // address not filled
|
|
160
|
+
amount: '2000000',
|
|
161
|
+
assets: [],
|
|
162
|
+
setMax: false,
|
|
163
|
+
},
|
|
164
|
+
],
|
|
165
|
+
changeAddress: `addr1q8u2f05rprqjhygz22m06mhy4xrnqvqqpyuzhmxqfxnwvxz8d2kd47hsre5v9urjyu8s0ryk38dxzw0t5jesncw4v90s22tk0f`,
|
|
166
|
+
certificates: [],
|
|
167
|
+
withdrawals: [],
|
|
168
|
+
accountPubKey:
|
|
169
|
+
'ec8fdf616242f430855ad7477acda53395eb30c295f5a7ef038712578877375b5a2f00353c9c5cc88c7ff18e71dc08724d90fc238213b789c0b02438e336be07',
|
|
170
|
+
},
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
// txPlan:
|
|
174
|
+
// {
|
|
175
|
+
// totalSpent: '2168053',
|
|
176
|
+
// fee: '168053',
|
|
177
|
+
// },
|
|
178
|
+
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Notes
|
|
182
|
+
|
|
183
|
+
- If there are certificates present or the transaction includes an output with `setMax: true` then largest-first algorithm will be used instead of random-improve.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
|
|
2
|
+
export declare const CertificateType: {
|
|
3
|
+
readonly STAKE_REGISTRATION: 0;
|
|
4
|
+
readonly STAKE_DEREGISTRATION: 1;
|
|
5
|
+
readonly STAKE_DELEGATION: 2;
|
|
6
|
+
readonly STAKE_POOL_REGISTRATION: 3;
|
|
7
|
+
};
|
|
8
|
+
export declare const ERROR: {
|
|
9
|
+
readonly UTXO_BALANCE_INSUFFICIENT: {
|
|
10
|
+
readonly code: "UTXO_BALANCE_INSUFFICIENT";
|
|
11
|
+
readonly message: "UTxO balance insufficient";
|
|
12
|
+
};
|
|
13
|
+
readonly UTXO_VALUE_TOO_SMALL: {
|
|
14
|
+
readonly code: "UTXO_VALUE_TOO_SMALL";
|
|
15
|
+
readonly message: "UTxO value too small";
|
|
16
|
+
};
|
|
17
|
+
readonly UNSUPPORTED_CERTIFICATE_TYPE: {
|
|
18
|
+
readonly code: "UNSUPPORTED_CERTIFICATE_TYPE";
|
|
19
|
+
readonly message: "Unsupported certificate type";
|
|
20
|
+
};
|
|
21
|
+
readonly UTXO_NOT_FRAGMENTED_ENOUGH: {
|
|
22
|
+
readonly code: "UTXO_NOT_FRAGMENTED_ENOUGH";
|
|
23
|
+
readonly message: "UTxO Not fragmented enough.";
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
export declare const CARDANO_PARAMS: {
|
|
27
|
+
readonly PROTOCOL_MAGICS: {
|
|
28
|
+
readonly mainnet: number;
|
|
29
|
+
readonly testnet: number;
|
|
30
|
+
};
|
|
31
|
+
readonly NETWORK_IDS: {
|
|
32
|
+
readonly mainnet: number;
|
|
33
|
+
readonly testnet: number;
|
|
34
|
+
};
|
|
35
|
+
readonly COINS_PER_UTXO_BYTE: "4310";
|
|
36
|
+
readonly MAX_TX_SIZE: 16384;
|
|
37
|
+
readonly MAX_VALUE_SIZE: 5000;
|
|
38
|
+
};
|
|
39
|
+
export declare const MAX_TOKENS_PER_OUTPUT = 50;
|
|
40
|
+
export declare const DATA_COST_PER_UTXO_BYTE: CardanoWasm.DataCost;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.DATA_COST_PER_UTXO_BYTE = exports.MAX_TOKENS_PER_OUTPUT = exports.CARDANO_PARAMS = exports.ERROR = exports.CertificateType = void 0;
|
|
27
|
+
const CardanoWasm = __importStar(require("@emurgo/cardano-serialization-lib-asmjs"));
|
|
28
|
+
exports.CertificateType = {
|
|
29
|
+
STAKE_REGISTRATION: 0,
|
|
30
|
+
STAKE_DEREGISTRATION: 1,
|
|
31
|
+
STAKE_DELEGATION: 2,
|
|
32
|
+
STAKE_POOL_REGISTRATION: 3,
|
|
33
|
+
};
|
|
34
|
+
exports.ERROR = {
|
|
35
|
+
UTXO_BALANCE_INSUFFICIENT: {
|
|
36
|
+
code: 'UTXO_BALANCE_INSUFFICIENT',
|
|
37
|
+
message: 'UTxO balance insufficient',
|
|
38
|
+
},
|
|
39
|
+
UTXO_VALUE_TOO_SMALL: {
|
|
40
|
+
code: 'UTXO_VALUE_TOO_SMALL',
|
|
41
|
+
message: 'UTxO value too small',
|
|
42
|
+
},
|
|
43
|
+
UNSUPPORTED_CERTIFICATE_TYPE: {
|
|
44
|
+
code: 'UNSUPPORTED_CERTIFICATE_TYPE',
|
|
45
|
+
message: 'Unsupported certificate type',
|
|
46
|
+
},
|
|
47
|
+
UTXO_NOT_FRAGMENTED_ENOUGH: {
|
|
48
|
+
code: 'UTXO_NOT_FRAGMENTED_ENOUGH',
|
|
49
|
+
message: 'UTxO Not fragmented enough.',
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
exports.CARDANO_PARAMS = {
|
|
53
|
+
PROTOCOL_MAGICS: {
|
|
54
|
+
mainnet: CardanoWasm.NetworkInfo.mainnet().protocol_magic(),
|
|
55
|
+
testnet: CardanoWasm.NetworkInfo.testnet().protocol_magic(),
|
|
56
|
+
},
|
|
57
|
+
NETWORK_IDS: {
|
|
58
|
+
mainnet: CardanoWasm.NetworkInfo.mainnet().network_id(),
|
|
59
|
+
testnet: CardanoWasm.NetworkInfo.testnet().network_id(),
|
|
60
|
+
},
|
|
61
|
+
COINS_PER_UTXO_BYTE: '4310',
|
|
62
|
+
MAX_TX_SIZE: 16384,
|
|
63
|
+
MAX_VALUE_SIZE: 5000,
|
|
64
|
+
};
|
|
65
|
+
// https://github.com/vacuumlabs/adalite/blob/d8ba3bb1ff439ae8e02abd99163435a989d97961/app/frontend/wallet/shelley/transaction/constants.ts
|
|
66
|
+
// policyId is 28 bytes, assetName max 32 bytes, together with quantity makes
|
|
67
|
+
// max token size about 70 bytes, max output size is 4000 => 4000 / 70 ~ 50
|
|
68
|
+
exports.MAX_TOKENS_PER_OUTPUT = 50;
|
|
69
|
+
exports.DATA_COST_PER_UTXO_BYTE = CardanoWasm.DataCost.new_coins_per_byte(CardanoWasm.BigNum.from_str(exports.CARDANO_PARAMS.COINS_PER_UTXO_BYTE));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { CoinSelectionParams, Options, PrecomposedTransaction } from './types/types';
|
|
2
|
+
export declare const coinSelection: (params: CoinSelectionParams, options?: Options) => PrecomposedTransaction;
|
|
3
|
+
export * as types from './types/types';
|
|
4
|
+
export * as trezorUtils from './utils/trezor';
|
|
5
|
+
export { onekeyUtils, dAppUtils } from './utils/onekey';
|
|
6
|
+
export { CoinSelectionError } from './utils/errors';
|
package/lib/cjs/index.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.CoinSelectionError = exports.dAppUtils = exports.onekeyUtils = exports.trezorUtils = exports.types = exports.coinSelection = void 0;
|
|
27
|
+
const constants_1 = require("./constants");
|
|
28
|
+
const largestFirst_1 = require("./methods/largestFirst");
|
|
29
|
+
const randomImprove_1 = require("./methods/randomImprove");
|
|
30
|
+
const errors_1 = require("./utils/errors");
|
|
31
|
+
const logger_1 = require("./utils/logger");
|
|
32
|
+
const common_1 = require("./utils/common");
|
|
33
|
+
const coinSelection = (params, options) => {
|
|
34
|
+
const logger = (0, logger_1.getLogger)(!!(options === null || options === void 0 ? void 0 : options.debug));
|
|
35
|
+
logger.debug('Args:', {
|
|
36
|
+
params,
|
|
37
|
+
options,
|
|
38
|
+
});
|
|
39
|
+
if (params.utxos.length === 0) {
|
|
40
|
+
logger.debug('Empty Utxo set');
|
|
41
|
+
throw new errors_1.CoinSelectionError(constants_1.ERROR.UTXO_BALANCE_INSUFFICIENT);
|
|
42
|
+
}
|
|
43
|
+
const t1 = new Date().getTime();
|
|
44
|
+
let res;
|
|
45
|
+
if (params.outputs.find(o => o.setMax) ||
|
|
46
|
+
params.certificates.length > 0 ||
|
|
47
|
+
params.withdrawals.length > 0 ||
|
|
48
|
+
(options === null || options === void 0 ? void 0 : options.forceLargestFirstSelection)) {
|
|
49
|
+
logger.debug('Running largest-first alg');
|
|
50
|
+
res = (0, largestFirst_1.largestFirst)(params, options);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
logger.debug('Running random-improve alg');
|
|
54
|
+
try {
|
|
55
|
+
res = (0, randomImprove_1.randomImprove)(params, options);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (error instanceof errors_1.CoinSelectionError &&
|
|
59
|
+
error.code === 'UTXO_NOT_FRAGMENTED_ENOUGH') {
|
|
60
|
+
logger.debug(`random-improve failed with ${error.code}. Retrying with largest-first alg.`);
|
|
61
|
+
res = (0, largestFirst_1.largestFirst)(params, options);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const t2 = new Date().getTime();
|
|
69
|
+
logger.debug(`Duration: ${(t2 - t1) / 1000} seconds`);
|
|
70
|
+
const incompleteOutputs = res.outputs.find(o => !o.address ||
|
|
71
|
+
!o.amount ||
|
|
72
|
+
// assets set with quantity = 0
|
|
73
|
+
(o.assets.length > 0 &&
|
|
74
|
+
o.assets.find(a => !a.quantity ||
|
|
75
|
+
(0, common_1.bigNumFromStr)(a.quantity).compare((0, common_1.bigNumFromStr)('0')) === 0)));
|
|
76
|
+
if (incompleteOutputs) {
|
|
77
|
+
const selection = {
|
|
78
|
+
type: 'nonfinal',
|
|
79
|
+
fee: res.fee,
|
|
80
|
+
totalSpent: res.totalSpent,
|
|
81
|
+
deposit: res.deposit,
|
|
82
|
+
withdrawal: res.withdrawal,
|
|
83
|
+
max: res.max,
|
|
84
|
+
};
|
|
85
|
+
logger.debug('Coin selection for a draft transaction:', selection);
|
|
86
|
+
return selection;
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
const selection = Object.assign(Object.assign({ type: 'final' }, res), { outputs: res.outputs });
|
|
90
|
+
logger.debug('Coin selection for a final transaction:', selection);
|
|
91
|
+
return selection;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
exports.coinSelection = coinSelection;
|
|
95
|
+
exports.types = __importStar(require("./types/types"));
|
|
96
|
+
exports.trezorUtils = __importStar(require("./utils/trezor"));
|
|
97
|
+
var onekey_1 = require("./utils/onekey");
|
|
98
|
+
Object.defineProperty(exports, "onekeyUtils", { enumerable: true, get: function () { return onekey_1.onekeyUtils; } });
|
|
99
|
+
Object.defineProperty(exports, "dAppUtils", { enumerable: true, get: function () { return onekey_1.dAppUtils; } });
|
|
100
|
+
var errors_2 = require("./utils/errors");
|
|
101
|
+
Object.defineProperty(exports, "CoinSelectionError", { enumerable: true, get: function () { return errors_2.CoinSelectionError; } });
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.largestFirst = void 0;
|
|
27
|
+
const constants_1 = require("../constants");
|
|
28
|
+
const CardanoWasm = __importStar(require("@emurgo/cardano-serialization-lib-asmjs"));
|
|
29
|
+
const common_1 = require("../utils/common");
|
|
30
|
+
const errors_1 = require("../utils/errors");
|
|
31
|
+
const largestFirst = (params, options) => {
|
|
32
|
+
var _a;
|
|
33
|
+
const { utxos, outputs, changeAddress, certificates, withdrawals, accountPubKey, ttl, } = params;
|
|
34
|
+
const txBuilder = (0, common_1.getTxBuilder)((_a = options === null || options === void 0 ? void 0 : options.feeParams) === null || _a === void 0 ? void 0 : _a.a);
|
|
35
|
+
if (ttl) {
|
|
36
|
+
txBuilder.set_ttl(ttl);
|
|
37
|
+
}
|
|
38
|
+
const usedUtxos = [];
|
|
39
|
+
let sortedUtxos = (0, common_1.sortUtxos)(utxos);
|
|
40
|
+
const accountKey = CardanoWasm.Bip32PublicKey.from_bytes(Buffer.from(accountPubKey, 'hex'));
|
|
41
|
+
// add withdrawals and certs to correctly set a fee
|
|
42
|
+
const preparedCertificates = (0, common_1.prepareCertificates)(certificates, accountKey);
|
|
43
|
+
const preparedWithdrawals = (0, common_1.prepareWithdrawals)(withdrawals);
|
|
44
|
+
if (preparedCertificates.len() > 0) {
|
|
45
|
+
txBuilder.set_certs(preparedCertificates);
|
|
46
|
+
}
|
|
47
|
+
if (preparedWithdrawals.len() > 0) {
|
|
48
|
+
txBuilder.set_withdrawals(preparedWithdrawals);
|
|
49
|
+
}
|
|
50
|
+
// TODO: negative value in case of deregistration (-2000000), but we still need enough utxos to cover fee which can't be (is that right?) paid from returned deposit
|
|
51
|
+
const deposit = (0, common_1.calculateRequiredDeposit)(certificates);
|
|
52
|
+
const totalWithdrawal = withdrawals.reduce((acc, withdrawal) => acc.checked_add((0, common_1.bigNumFromStr)(withdrawal.amount)), (0, common_1.bigNumFromStr)('0'));
|
|
53
|
+
// calc initial fee
|
|
54
|
+
let totalFeesAmount = txBuilder.min_fee();
|
|
55
|
+
let utxosTotalAmount = totalWithdrawal;
|
|
56
|
+
if (deposit < 0) {
|
|
57
|
+
// stake deregistration, 2 ADA returned
|
|
58
|
+
utxosTotalAmount = utxosTotalAmount.checked_add((0, common_1.bigNumFromStr)(Math.abs(deposit).toString()));
|
|
59
|
+
}
|
|
60
|
+
const preparedOutputs = (0, common_1.setMinUtxoValueForOutputs)(txBuilder, outputs, changeAddress);
|
|
61
|
+
const addUtxoToSelection = (utxo) => {
|
|
62
|
+
const { input, address, amount } = (0, common_1.buildTxInput)(utxo);
|
|
63
|
+
const fee = txBuilder.fee_for_input(address, input, amount);
|
|
64
|
+
txBuilder.add_input(address, input, amount);
|
|
65
|
+
usedUtxos.push(utxo);
|
|
66
|
+
totalFeesAmount = totalFeesAmount.checked_add(fee);
|
|
67
|
+
utxosTotalAmount = utxosTotalAmount.checked_add((0, common_1.bigNumFromStr)((0, common_1.getAssetAmount)(utxo)));
|
|
68
|
+
};
|
|
69
|
+
// set initial utxos set for setMax functionality
|
|
70
|
+
const maxOutputIndex = outputs.findIndex(o => !!o.setMax);
|
|
71
|
+
const maxOutput = preparedOutputs[maxOutputIndex];
|
|
72
|
+
const { used, remaining } = (0, common_1.getInitialUtxoSet)(sortedUtxos, maxOutput);
|
|
73
|
+
sortedUtxos = remaining;
|
|
74
|
+
used.forEach(utxo => addUtxoToSelection(utxo));
|
|
75
|
+
// add cost of external outputs to total fee amount
|
|
76
|
+
totalFeesAmount = totalFeesAmount.checked_add((0, common_1.calculateUserOutputsFee)(txBuilder, preparedOutputs, changeAddress));
|
|
77
|
+
let totalUserOutputsAmount = (0, common_1.getUserOutputQuantityWithDeposit)(preparedOutputs, deposit);
|
|
78
|
+
let changeOutput = null;
|
|
79
|
+
let sufficientUtxos = false;
|
|
80
|
+
let forceAnotherRound = false;
|
|
81
|
+
while (!sufficientUtxos) {
|
|
82
|
+
if (maxOutput) {
|
|
83
|
+
// reset previously computed maxOutput in order to correctly calculate a potential change output
|
|
84
|
+
preparedOutputs[maxOutputIndex] = (0, common_1.setMinUtxoValueForOutputs)(txBuilder, [maxOutput], changeAddress)[0];
|
|
85
|
+
}
|
|
86
|
+
// Calculate change output
|
|
87
|
+
let singleChangeOutput = (0, common_1.prepareChangeOutput)(txBuilder, usedUtxos, preparedOutputs, changeAddress, utxosTotalAmount, (0, common_1.getUserOutputQuantityWithDeposit)(preparedOutputs, deposit), totalFeesAmount);
|
|
88
|
+
if (maxOutput) {
|
|
89
|
+
// set amount for a max output from a changeOutput calculated above
|
|
90
|
+
const { maxOutput: newMaxOutput } = (0, common_1.setMaxOutput)(maxOutput, singleChangeOutput);
|
|
91
|
+
// change output may be completely removed if all ADA are consumed by max output
|
|
92
|
+
preparedOutputs[maxOutputIndex] = newMaxOutput;
|
|
93
|
+
// recalculate total user outputs amount
|
|
94
|
+
totalUserOutputsAmount = (0, common_1.getUserOutputQuantityWithDeposit)(preparedOutputs, deposit);
|
|
95
|
+
// recalculate fees for outputs as cost for max output may be larger than before
|
|
96
|
+
totalFeesAmount = txBuilder
|
|
97
|
+
.min_fee()
|
|
98
|
+
.checked_add((0, common_1.calculateUserOutputsFee)(txBuilder, preparedOutputs, changeAddress));
|
|
99
|
+
// recalculate change after setting amount to max output
|
|
100
|
+
singleChangeOutput = (0, common_1.prepareChangeOutput)(txBuilder, usedUtxos, preparedOutputs, changeAddress, utxosTotalAmount, (0, common_1.getUserOutputQuantityWithDeposit)(preparedOutputs, deposit), totalFeesAmount);
|
|
101
|
+
}
|
|
102
|
+
const changeOutputs = singleChangeOutput
|
|
103
|
+
? (0, common_1.splitChangeOutput)(txBuilder, singleChangeOutput, changeAddress, options === null || options === void 0 ? void 0 : options._maxTokensPerOutput)
|
|
104
|
+
: [];
|
|
105
|
+
let requiredAmount = totalFeesAmount.checked_add(totalUserOutputsAmount);
|
|
106
|
+
changeOutputs.forEach(changeOutput => {
|
|
107
|
+
// we need to cover amounts and fees for change outputs
|
|
108
|
+
requiredAmount = requiredAmount
|
|
109
|
+
.checked_add(changeOutput.output.amount().coin())
|
|
110
|
+
.checked_add(changeOutput.outputFee);
|
|
111
|
+
});
|
|
112
|
+
// List of tokens for which we don't have enough utxos
|
|
113
|
+
const unsatisfiedAssets = (0, common_1.getUnsatisfiedAssets)(usedUtxos, preparedOutputs);
|
|
114
|
+
if (utxosTotalAmount.compare(requiredAmount) >= 0 &&
|
|
115
|
+
unsatisfiedAssets.length === 0 &&
|
|
116
|
+
usedUtxos.length > 0 && // TODO: force at least 1 utxo, otherwise withdrawal tx is composed without utxo if rewards > tx cost
|
|
117
|
+
!forceAnotherRound) {
|
|
118
|
+
// we are done. we have enough utxos to cover fees + minUtxoValue for each output. now we can add the cost of the change output to total fees
|
|
119
|
+
if (changeOutputs.length > 0) {
|
|
120
|
+
changeOutputs.forEach(changeOutput => {
|
|
121
|
+
totalFeesAmount = totalFeesAmount.checked_add(changeOutput.outputFee);
|
|
122
|
+
});
|
|
123
|
+
// set change output
|
|
124
|
+
changeOutput = changeOutputs.map(change => ({
|
|
125
|
+
isChange: true,
|
|
126
|
+
amount: change.output.amount().coin().to_str(),
|
|
127
|
+
address: changeAddress,
|
|
128
|
+
assets: (0, common_1.multiAssetToArray)(change.output.amount().multiasset()),
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
if (sortedUtxos.length > 0) {
|
|
133
|
+
// In current iteration we don't have enough utxo to meet min utxo value for an output,
|
|
134
|
+
// but some utxos are still available, force adding another one in order to create a change output
|
|
135
|
+
forceAnotherRound = true;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
// Change output would be inefficient., we can burn its value + fee we would pay for it
|
|
139
|
+
const unspendableChangeAmount = utxosTotalAmount.clamped_sub(totalFeesAmount.checked_add(totalUserOutputsAmount));
|
|
140
|
+
totalFeesAmount = totalFeesAmount.checked_add(unspendableChangeAmount);
|
|
141
|
+
}
|
|
142
|
+
sufficientUtxos = true;
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
if (unsatisfiedAssets.length > 0) {
|
|
146
|
+
// TODO: https://github.com/Emurgo/cardano-serialization-lib/pull/264
|
|
147
|
+
sortedUtxos = (0, common_1.sortUtxos)(sortedUtxos, unsatisfiedAssets[0]);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
sortedUtxos = (0, common_1.sortUtxos)(sortedUtxos);
|
|
151
|
+
}
|
|
152
|
+
const utxo = sortedUtxos.shift();
|
|
153
|
+
if (!utxo)
|
|
154
|
+
break;
|
|
155
|
+
addUtxoToSelection(utxo);
|
|
156
|
+
forceAnotherRound = false;
|
|
157
|
+
}
|
|
158
|
+
// END LOOP
|
|
159
|
+
}
|
|
160
|
+
if (!sufficientUtxos) {
|
|
161
|
+
throw new errors_1.CoinSelectionError(constants_1.ERROR.UTXO_BALANCE_INSUFFICIENT);
|
|
162
|
+
}
|
|
163
|
+
preparedOutputs.forEach(output => {
|
|
164
|
+
const txOutput = (0, common_1.buildTxOutput)(output, changeAddress);
|
|
165
|
+
txBuilder.add_output(txOutput);
|
|
166
|
+
});
|
|
167
|
+
const finalOutputs = JSON.parse(JSON.stringify(preparedOutputs));
|
|
168
|
+
if (changeOutput) {
|
|
169
|
+
changeOutput.forEach(change => {
|
|
170
|
+
finalOutputs.push(change);
|
|
171
|
+
txBuilder.add_output((0, common_1.buildTxOutput)(change, changeAddress));
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
txBuilder.set_fee(totalFeesAmount);
|
|
175
|
+
const txBody = txBuilder.build();
|
|
176
|
+
const txHash = Buffer.from(CardanoWasm.hash_transaction(txBody).to_bytes()).toString('hex');
|
|
177
|
+
const txBodyHex = Buffer.from(txBody.to_bytes()).toString('hex');
|
|
178
|
+
const totalSpent = totalUserOutputsAmount.checked_add(totalFeesAmount);
|
|
179
|
+
// Set max property with the value of an output which has setMax=true
|
|
180
|
+
let max;
|
|
181
|
+
if (maxOutput) {
|
|
182
|
+
max =
|
|
183
|
+
maxOutput.assets.length > 0
|
|
184
|
+
? maxOutput.assets[0].quantity
|
|
185
|
+
: maxOutput.amount;
|
|
186
|
+
}
|
|
187
|
+
// reorder inputs to match order within tx
|
|
188
|
+
const orderedInputs = (0, common_1.orderInputs)(usedUtxos, txBody);
|
|
189
|
+
return {
|
|
190
|
+
tx: { body: txBodyHex, hash: txHash, size: txBuilder.full_size() },
|
|
191
|
+
inputs: orderedInputs,
|
|
192
|
+
outputs: finalOutputs,
|
|
193
|
+
fee: totalFeesAmount.to_str(),
|
|
194
|
+
totalSpent: totalSpent.to_str(),
|
|
195
|
+
deposit: deposit.toString(),
|
|
196
|
+
withdrawal: totalWithdrawal.to_str(),
|
|
197
|
+
ttl,
|
|
198
|
+
max,
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
exports.largestFirst = largestFirst;
|