@onekeyfe/cardano-coin-selection-asmjs 1.1.0 → 1.1.2

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 (47) hide show
  1. package/CHANGELOG.MD +22 -0
  2. package/lib/cjs/constants/index.d.ts +7 -2
  3. package/lib/cjs/constants/index.js +7 -2
  4. package/lib/cjs/methods/largestFirst.js +7 -4
  5. package/lib/cjs/methods/randomImprove.d.ts +1 -1
  6. package/lib/cjs/methods/randomImprove.js +4 -2
  7. package/lib/cjs/types/trezor.d.ts +4 -4
  8. package/lib/cjs/types/trezor.js +1 -1
  9. package/lib/cjs/types/types.d.ts +27 -6
  10. package/lib/cjs/types/types.js +9 -2
  11. package/lib/cjs/utils/common.d.ts +4 -4
  12. package/lib/cjs/utils/common.js +35 -9
  13. package/lib/cjs/utils/errors.d.ts +2 -2
  14. package/lib/cjs/utils/onekey/dapp.js +3 -1
  15. package/lib/cjs/utils/onekey/index.d.ts +2 -2
  16. package/lib/cjs/utils/onekey/signTx.d.ts +1 -1
  17. package/lib/cjs/utils/onekey/signTx.js +4 -2
  18. package/lib/cjs/utils/onekey/txToOneKey.d.ts +2 -2
  19. package/lib/cjs/utils/onekey/txToOneKey.js +22 -13
  20. package/lib/cjs/utils/onekey/types.d.ts +9 -9
  21. package/lib/cjs/utils/trezor/index.d.ts +2 -2
  22. package/lib/cjs/utils/trezor/index.js +2 -1
  23. package/lib/cjs/utils/trezor/transformations.d.ts +5 -1
  24. package/lib/cjs/utils/trezor/transformations.js +50 -1
  25. package/lib/esm/constants/index.d.ts +7 -2
  26. package/lib/esm/constants/index.js +7 -2
  27. package/lib/esm/methods/largestFirst.js +7 -4
  28. package/lib/esm/methods/randomImprove.d.ts +1 -1
  29. package/lib/esm/methods/randomImprove.js +4 -2
  30. package/lib/esm/types/trezor.d.ts +4 -4
  31. package/lib/esm/types/types.d.ts +27 -6
  32. package/lib/esm/types/types.js +7 -0
  33. package/lib/esm/utils/common.d.ts +4 -4
  34. package/lib/esm/utils/common.js +35 -9
  35. package/lib/esm/utils/errors.d.ts +2 -2
  36. package/lib/esm/utils/onekey/dapp.js +3 -1
  37. package/lib/esm/utils/onekey/index.d.ts +2 -2
  38. package/lib/esm/utils/onekey/signTx.d.ts +1 -1
  39. package/lib/esm/utils/onekey/signTx.js +4 -2
  40. package/lib/esm/utils/onekey/txToOneKey.d.ts +2 -2
  41. package/lib/esm/utils/onekey/txToOneKey.js +18 -9
  42. package/lib/esm/utils/onekey/types.d.ts +9 -9
  43. package/lib/esm/utils/trezor/index.d.ts +2 -2
  44. package/lib/esm/utils/trezor/index.js +2 -2
  45. package/lib/esm/utils/trezor/transformations.d.ts +5 -1
  46. package/lib/esm/utils/trezor/transformations.js +25 -0
  47. package/package.json +20 -16
@@ -1,3 +1,3 @@
1
- import { transformToTokenBundle, transformToTrezorInputs, transformToTrezorOutputs } from './transformations';
1
+ import { transformToTokenBundle, transformToTrezorInputs, transformToTrezorOutputs, drepIdToHex } from './transformations';
2
2
  import { signTransaction } from './sign';
3
- export { transformToTokenBundle, transformToTrezorInputs, transformToTrezorOutputs, signTransaction, };
3
+ export { transformToTokenBundle, transformToTrezorInputs, transformToTrezorOutputs, signTransaction, drepIdToHex, };
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.signTransaction = exports.transformToTrezorOutputs = exports.transformToTrezorInputs = exports.transformToTokenBundle = void 0;
3
+ exports.drepIdToHex = exports.signTransaction = exports.transformToTrezorOutputs = exports.transformToTrezorInputs = exports.transformToTokenBundle = void 0;
4
4
  const transformations_1 = require("./transformations");
5
5
  Object.defineProperty(exports, "transformToTokenBundle", { enumerable: true, get: function () { return transformations_1.transformToTokenBundle; } });
6
6
  Object.defineProperty(exports, "transformToTrezorInputs", { enumerable: true, get: function () { return transformations_1.transformToTrezorInputs; } });
7
7
  Object.defineProperty(exports, "transformToTrezorOutputs", { enumerable: true, get: function () { return transformations_1.transformToTrezorOutputs; } });
8
+ Object.defineProperty(exports, "drepIdToHex", { enumerable: true, get: function () { return transformations_1.drepIdToHex; } });
8
9
  const sign_1 = require("./sign");
9
10
  Object.defineProperty(exports, "signTransaction", { enumerable: true, get: function () { return sign_1.signTransaction; } });
@@ -1,5 +1,5 @@
1
1
  import { CardanoAddressParameters, CardanoInput, CardanoOutput } from '../../types/trezor';
2
- import { Asset, FinalOutput, Utxo } from '../../types/types';
2
+ import { Asset, CardanoDRepType, FinalOutput, Utxo } from '../../types/types';
3
3
  interface AssetInPolicy {
4
4
  assetNameBytes: string;
5
5
  amount: string;
@@ -14,4 +14,8 @@ export declare const transformToTrezorInputs: (utxos: Utxo[], trezorUtxos: {
14
14
  path: string;
15
15
  }[]) => CardanoInput[];
16
16
  export declare const transformToTrezorOutputs: (outputs: FinalOutput[], changeAddressParameters: CardanoAddressParameters) => CardanoOutput[];
17
+ export declare const drepIdToHex: (drepId: string) => {
18
+ type: CardanoDRepType.KEY_HASH | CardanoDRepType.SCRIPT_HASH;
19
+ hex: string;
20
+ };
17
21
  export {};
@@ -1,6 +1,31 @@
1
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
+ };
2
25
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.transformToTrezorOutputs = exports.transformToTrezorInputs = exports.transformToTokenBundle = void 0;
26
+ exports.drepIdToHex = exports.transformToTrezorOutputs = exports.transformToTrezorInputs = exports.transformToTokenBundle = void 0;
27
+ const CardanoWasm = __importStar(require("@emurgo/cardano-serialization-lib-asmjs"));
28
+ const types_1 = require("../../types/types");
4
29
  const common_1 = require("../common");
5
30
  const transformToTokenBundle = (assets) => {
6
31
  // prepare token bundle used in trezor output
@@ -64,3 +89,27 @@ const transformToTrezorOutputs = (outputs, changeAddressParameters) => {
64
89
  });
65
90
  };
66
91
  exports.transformToTrezorOutputs = transformToTrezorOutputs;
92
+ const drepIdToHex = (drepId) => {
93
+ var _a, _b;
94
+ const drep = CardanoWasm.DRep.from_bech32(drepId);
95
+ const kind = drep.kind();
96
+ let drepHex;
97
+ switch (kind) {
98
+ case types_1.CardanoDRepType.KEY_HASH:
99
+ drepHex = (_a = drep.to_key_hash()) === null || _a === void 0 ? void 0 : _a.to_hex();
100
+ break;
101
+ case types_1.CardanoDRepType.SCRIPT_HASH:
102
+ drepHex = (_b = drep.to_script_hash()) === null || _b === void 0 ? void 0 : _b.to_hex();
103
+ break;
104
+ }
105
+ if (!drepHex) {
106
+ throw Error('Invalid drepId');
107
+ }
108
+ const drepData = {
109
+ type: kind,
110
+ hex: drepHex,
111
+ };
112
+ drep.free();
113
+ return drepData;
114
+ };
115
+ exports.drepIdToHex = drepIdToHex;
@@ -4,6 +4,9 @@ export declare const CertificateType: {
4
4
  readonly STAKE_DEREGISTRATION: 1;
5
5
  readonly STAKE_DELEGATION: 2;
6
6
  readonly STAKE_POOL_REGISTRATION: 3;
7
+ readonly STAKE_REGISTRATION_CONWAY: 7;
8
+ readonly STAKE_DEREGISTRATION_CONWAY: 8;
9
+ readonly VOTE_DELEGATION: 9;
7
10
  };
8
11
  export declare const ERROR: {
9
12
  readonly UTXO_BALANCE_INSUFFICIENT: {
@@ -26,11 +29,13 @@ export declare const ERROR: {
26
29
  export declare const CARDANO_PARAMS: {
27
30
  readonly PROTOCOL_MAGICS: {
28
31
  readonly mainnet: number;
29
- readonly testnet: number;
32
+ readonly testnet_preprod: number;
33
+ readonly testnet_preview: number;
30
34
  };
31
35
  readonly NETWORK_IDS: {
32
36
  readonly mainnet: number;
33
- readonly testnet: number;
37
+ readonly testnet_preprod: number;
38
+ readonly testnet_preview: number;
34
39
  };
35
40
  readonly COINS_PER_UTXO_BYTE: "4310";
36
41
  readonly MAX_TX_SIZE: 16384;
@@ -4,6 +4,9 @@ export const CertificateType = {
4
4
  STAKE_DEREGISTRATION: 1,
5
5
  STAKE_DELEGATION: 2,
6
6
  STAKE_POOL_REGISTRATION: 3,
7
+ STAKE_REGISTRATION_CONWAY: 7,
8
+ STAKE_DEREGISTRATION_CONWAY: 8,
9
+ VOTE_DELEGATION: 9,
7
10
  };
8
11
  export const ERROR = {
9
12
  UTXO_BALANCE_INSUFFICIENT: {
@@ -26,11 +29,13 @@ export const ERROR = {
26
29
  export const CARDANO_PARAMS = {
27
30
  PROTOCOL_MAGICS: {
28
31
  mainnet: CardanoWasm.NetworkInfo.mainnet().protocol_magic(),
29
- testnet: CardanoWasm.NetworkInfo.testnet().protocol_magic(),
32
+ testnet_preprod: CardanoWasm.NetworkInfo.testnet_preprod().protocol_magic(),
33
+ testnet_preview: CardanoWasm.NetworkInfo.testnet_preview().protocol_magic(),
30
34
  },
31
35
  NETWORK_IDS: {
32
36
  mainnet: CardanoWasm.NetworkInfo.mainnet().network_id(),
33
- testnet: CardanoWasm.NetworkInfo.testnet().network_id(),
37
+ testnet_preprod: CardanoWasm.NetworkInfo.testnet_preprod().network_id(),
38
+ testnet_preview: CardanoWasm.NetworkInfo.testnet_preview().network_id(),
34
39
  },
35
40
  COINS_PER_UTXO_BYTE: '4310',
36
41
  MAX_TX_SIZE: 16384,
@@ -35,7 +35,7 @@ export const largestFirst = (params, options) => {
35
35
  const addUtxoToSelection = (utxo) => {
36
36
  const { input, address, amount } = buildTxInput(utxo);
37
37
  const fee = txBuilder.fee_for_input(address, input, amount);
38
- txBuilder.add_input(address, input, amount);
38
+ txBuilder.add_regular_input(address, input, amount);
39
39
  usedUtxos.push(utxo);
40
40
  totalFeesAmount = totalFeesAmount.checked_add(fee);
41
41
  utxosTotalAmount = utxosTotalAmount.checked_add(bigNumFromStr(getAssetAmount(utxo)));
@@ -54,14 +54,15 @@ export const largestFirst = (params, options) => {
54
54
  let forceAnotherRound = false;
55
55
  while (!sufficientUtxos) {
56
56
  if (maxOutput) {
57
- // reset previously computed maxOutput in order to correctly calculate a potential change output
57
+ // Reset previously computed maxOutput in order to correctly calculate a potential change output
58
+ // when new utxo is added to the set
58
59
  preparedOutputs[maxOutputIndex] = setMinUtxoValueForOutputs(txBuilder, [maxOutput], changeAddress)[0];
59
60
  }
60
61
  // Calculate change output
61
62
  let singleChangeOutput = prepareChangeOutput(txBuilder, usedUtxos, preparedOutputs, changeAddress, utxosTotalAmount, getUserOutputQuantityWithDeposit(preparedOutputs, deposit), totalFeesAmount);
62
63
  if (maxOutput) {
63
64
  // set amount for a max output from a changeOutput calculated above
64
- const { maxOutput: newMaxOutput } = setMaxOutput(maxOutput, singleChangeOutput);
65
+ const { maxOutput: newMaxOutput } = setMaxOutput(txBuilder, maxOutput, singleChangeOutput);
65
66
  // change output may be completely removed if all ADA are consumed by max output
66
67
  preparedOutputs[maxOutputIndex] = newMaxOutput;
67
68
  // recalculate total user outputs amount
@@ -147,7 +148,9 @@ export const largestFirst = (params, options) => {
147
148
  }
148
149
  txBuilder.set_fee(totalFeesAmount);
149
150
  const txBody = txBuilder.build();
150
- const txHash = Buffer.from(CardanoWasm.hash_transaction(txBody).to_bytes()).toString('hex');
151
+ const txHash = CardanoWasm.FixedTransaction.new_from_body_bytes(txBody.to_bytes())
152
+ .transaction_hash()
153
+ .to_hex();
151
154
  const txBodyHex = Buffer.from(txBody.to_bytes()).toString('hex');
152
155
  const totalSpent = totalUserOutputsAmount.checked_add(totalFeesAmount);
153
156
  // Set max property with the value of an output which has setMax=true
@@ -1,2 +1,2 @@
1
1
  import { CoinSelectionParams, CoinSelectionResult, Options } from '../types/types';
2
- export declare const randomImprove: (params: Pick<CoinSelectionParams, 'utxos' | 'outputs' | 'changeAddress' | 'ttl'>, options?: Options) => CoinSelectionResult;
2
+ export declare const randomImprove: (params: Pick<CoinSelectionParams, "utxos" | "outputs" | "changeAddress" | "ttl">, options?: Options) => CoinSelectionResult;
@@ -56,7 +56,7 @@ const selection = (utxos, outputs, txBuilder, dummyAddress) => {
56
56
  if (improvesSelection(utxoSelected, utxo, getOutputQuantity(preparedOutputs, asset), asset)) {
57
57
  utxoSelected.push(utxo);
58
58
  const { input, address, amount } = buildTxInput(utxo);
59
- txBuilder.add_input(address, input, amount);
59
+ txBuilder.add_regular_input(address, input, amount);
60
60
  utxoRemaining.splice(utxoRemaining.indexOf(utxo), 1);
61
61
  }
62
62
  else {
@@ -143,7 +143,9 @@ export const randomImprove = (params, options) => {
143
143
  const totalSpent = totalUserOutputsAmount.checked_add(fee);
144
144
  txBuilder.set_fee(fee);
145
145
  const txBody = txBuilder.build();
146
- const txHash = Buffer.from(CardanoWasm.hash_transaction(txBody).to_bytes()).toString('hex');
146
+ const txHash = CardanoWasm.FixedTransaction.new_from_body_bytes(txBody.to_bytes())
147
+ .transaction_hash()
148
+ .to_hex();
147
149
  const txBodyHex = Buffer.from(txBody.to_bytes()).toString('hex');
148
150
  // reorder inputs to match order within tx
149
151
  const orderedInputs = orderInputs(utxoSelected, txBody);
@@ -4,11 +4,11 @@ export interface CardanoInput {
4
4
  prev_hash: string;
5
5
  prev_index: number;
6
6
  }
7
- export declare type CardanoToken = {
7
+ export type CardanoToken = {
8
8
  assetNameBytes: string;
9
9
  amount: string;
10
10
  };
11
- export declare type CardanoAssetGroup = {
11
+ export type CardanoAssetGroup = {
12
12
  policyId: string;
13
13
  tokenAmounts: CardanoToken[];
14
14
  };
@@ -24,7 +24,7 @@ export interface CardanoAddressParameters {
24
24
  stakingKeyHash?: string;
25
25
  certificatePointer?: CardanoCertificatePointer;
26
26
  }
27
- export declare type CardanoOutput = {
27
+ export type CardanoOutput = {
28
28
  addressParameters: CardanoAddressParameters;
29
29
  amount: string;
30
30
  tokenBundle?: CardanoAssetGroup[];
@@ -37,7 +37,7 @@ export declare enum CardanoTxWitnessType {
37
37
  BYRON_WITNESS = 0,
38
38
  SHELLEY_WITNESS = 1
39
39
  }
40
- export declare type CardanoSignedTxWitness = {
40
+ export type CardanoSignedTxWitness = {
41
41
  type: CardanoTxWitnessType;
42
42
  pubKey: string;
43
43
  signature: string;
@@ -36,9 +36,9 @@ export interface ChangeOutput extends BaseOutput {
36
36
  address: string;
37
37
  isChange: true;
38
38
  }
39
- export declare type FinalOutput = ExternalOutput | ChangeOutput;
40
- export declare type UserOutput = ExternalOutput | ExternalOutputIncomplete;
41
- export declare type Output = FinalOutput | ExternalOutputIncomplete;
39
+ export type FinalOutput = ExternalOutput | ChangeOutput;
40
+ export type UserOutput = ExternalOutput | ExternalOutputIncomplete;
41
+ export type Output = FinalOutput | ExternalOutputIncomplete;
42
42
  export interface OutputCost {
43
43
  output: CardanoWasm.TransactionOutput;
44
44
  outputFee: BigNum;
@@ -57,6 +57,23 @@ export declare enum CardanoAddressType {
57
57
  REWARD = 14,
58
58
  REWARD_SCRIPT = 15
59
59
  }
60
+ export declare enum CardanoDRepType {
61
+ KEY_HASH = 0,
62
+ SCRIPT_HASH = 1,
63
+ ABSTAIN = 2,
64
+ NO_CONFIDENCE = 3
65
+ }
66
+ export type DRep = {
67
+ type: CardanoDRepType.KEY_HASH;
68
+ keyHash: string;
69
+ } | {
70
+ type: CardanoDRepType.SCRIPT_HASH;
71
+ scriptHash: string;
72
+ } | {
73
+ type: CardanoDRepType.ABSTAIN | CardanoDRepType.NO_CONFIDENCE;
74
+ keyHash?: never;
75
+ scriptHash?: never;
76
+ };
60
77
  export interface CoinSelectionResult {
61
78
  tx: {
62
79
  body: string;
@@ -72,7 +89,7 @@ export interface CoinSelectionResult {
72
89
  ttl?: number;
73
90
  max?: string;
74
91
  }
75
- export declare type PrecomposedTransaction = ({
92
+ export type PrecomposedTransaction = ({
76
93
  type: 'final';
77
94
  outputs: FinalOutput[];
78
95
  } & Omit<CoinSelectionResult, 'outputs'>) | ({
@@ -82,7 +99,7 @@ export interface Withdrawal {
82
99
  stakeAddress: string;
83
100
  amount: string;
84
101
  }
85
- export declare type CertificateTypeType = typeof CertificateType;
102
+ export type CertificateTypeType = typeof CertificateType;
86
103
  export interface CertificateStakeRegistration {
87
104
  type: CertificateTypeType['STAKE_REGISTRATION'] | CertificateTypeType['STAKE_DEREGISTRATION'];
88
105
  stakingKeyHash?: string;
@@ -96,7 +113,11 @@ export interface CertificateStakePoolRegistration {
96
113
  type: CertificateTypeType['STAKE_POOL_REGISTRATION'];
97
114
  pool_parameters: Record<string, unknown>;
98
115
  }
99
- export declare type Certificate = CertificateStakeRegistration | CertificateStakeDelegation | CertificateStakePoolRegistration;
116
+ export interface CertificateVoteDelegation {
117
+ type: CertificateTypeType['VOTE_DELEGATION'];
118
+ dRep: DRep;
119
+ }
120
+ export type Certificate = CertificateStakeRegistration | CertificateStakeDelegation | CertificateStakePoolRegistration | CertificateVoteDelegation;
100
121
  export interface Options {
101
122
  feeParams?: {
102
123
  a: string;
@@ -12,3 +12,10 @@ export var CardanoAddressType;
12
12
  CardanoAddressType[CardanoAddressType["REWARD"] = 14] = "REWARD";
13
13
  CardanoAddressType[CardanoAddressType["REWARD_SCRIPT"] = 15] = "REWARD_SCRIPT";
14
14
  })(CardanoAddressType || (CardanoAddressType = {}));
15
+ export var CardanoDRepType;
16
+ (function (CardanoDRepType) {
17
+ CardanoDRepType[CardanoDRepType["KEY_HASH"] = 0] = "KEY_HASH";
18
+ CardanoDRepType[CardanoDRepType["SCRIPT_HASH"] = 1] = "SCRIPT_HASH";
19
+ CardanoDRepType[CardanoDRepType["ABSTAIN"] = 2] = "ABSTAIN";
20
+ CardanoDRepType[CardanoDRepType["NO_CONFIDENCE"] = 3] = "NO_CONFIDENCE";
21
+ })(CardanoDRepType || (CardanoDRepType = {}));
@@ -2,15 +2,15 @@ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
2
  import { CARDANO_PARAMS } from '../constants';
3
3
  import { Certificate, Output, Utxo, Withdrawal, OutputCost, UserOutput, Asset } from '../types/types';
4
4
  export declare const bigNumFromStr: (num: string) => CardanoWasm.BigNum;
5
- export declare const getProtocolMagic: (tesnet?: boolean) => (typeof CARDANO_PARAMS.PROTOCOL_MAGICS)['mainnet'] | (typeof CARDANO_PARAMS.PROTOCOL_MAGICS)['testnet'];
6
- export declare const getNetworkId: (testnet?: boolean) => (typeof CARDANO_PARAMS.NETWORK_IDS)['mainnet'] | (typeof CARDANO_PARAMS.NETWORK_IDS)['testnet'];
5
+ export declare const getProtocolMagic: (tesnet?: boolean) => (typeof CARDANO_PARAMS.PROTOCOL_MAGICS)["mainnet"] | (typeof CARDANO_PARAMS.PROTOCOL_MAGICS)["testnet_preview"] | (typeof CARDANO_PARAMS.PROTOCOL_MAGICS)["testnet_preprod"];
6
+ export declare const getNetworkId: (testnet?: boolean) => (typeof CARDANO_PARAMS.NETWORK_IDS)["mainnet"] | (typeof CARDANO_PARAMS.NETWORK_IDS)["testnet_preprod"] | (typeof CARDANO_PARAMS.NETWORK_IDS)["testnet_preview"];
7
7
  export declare const parseAsset: (hex: string) => {
8
8
  policyId: string;
9
9
  assetNameInHex: string;
10
10
  };
11
11
  export declare const buildMultiAsset: (assets: Asset[]) => CardanoWasm.MultiAsset;
12
12
  export declare const multiAssetToArray: (multiAsset: CardanoWasm.MultiAsset | undefined) => Asset[];
13
- export declare const getAssetAmount: (obj: Pick<Utxo, 'amount'>, asset?: string) => string;
13
+ export declare const getAssetAmount: (obj: Pick<Utxo, "amount">, asset?: string) => string;
14
14
  export declare const getUtxoQuantity: (utxos: Utxo[], asset?: string) => CardanoWasm.BigNum;
15
15
  export declare const getOutputQuantity: (outputs: Output[], asset?: string) => CardanoWasm.BigNum;
16
16
  export declare const sortUtxos: (utxos: Utxo[], asset?: string) => Utxo[];
@@ -33,7 +33,7 @@ export declare const getInitialUtxoSet: (utxos: Utxo[], maxOutput: UserOutput |
33
33
  used: Utxo[];
34
34
  remaining: Utxo[];
35
35
  };
36
- export declare const setMaxOutput: (maxOutput: UserOutput, changeOutput: OutputCost | null) => {
36
+ export declare const setMaxOutput: (txBuilder: CardanoWasm.TransactionBuilder, maxOutput: UserOutput, changeOutput: OutputCost | null) => {
37
37
  maxOutput: UserOutput;
38
38
  };
39
39
  export declare const getUserOutputQuantityWithDeposit: (outputs: UserOutput[], deposit: number, asset?: string) => CardanoWasm.BigNum;
@@ -1,12 +1,13 @@
1
1
  import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
2
  import { CARDANO_PARAMS, CertificateType, DATA_COST_PER_UTXO_BYTE, ERROR, MAX_TOKENS_PER_OUTPUT, } from '../constants';
3
+ import { CardanoDRepType, } from '../types/types';
3
4
  import { CoinSelectionError } from './errors';
4
5
  export const bigNumFromStr = (num) => CardanoWasm.BigNum.from_str(num);
5
6
  export const getProtocolMagic = (tesnet) => tesnet
6
- ? CARDANO_PARAMS.PROTOCOL_MAGICS.testnet
7
+ ? CARDANO_PARAMS.PROTOCOL_MAGICS.testnet_preview
7
8
  : CARDANO_PARAMS.PROTOCOL_MAGICS.mainnet;
8
9
  export const getNetworkId = (testnet) => testnet
9
- ? CARDANO_PARAMS.NETWORK_IDS.testnet
10
+ ? CARDANO_PARAMS.NETWORK_IDS.testnet_preview
10
11
  : CARDANO_PARAMS.NETWORK_IDS.mainnet;
11
12
  export const parseAsset = (hex) => {
12
13
  const policyIdSize = 56;
@@ -141,7 +142,7 @@ export const prepareCertificates = (certificates, accountKey) => {
141
142
  if (certificates.length === 0)
142
143
  return preparedCertificates;
143
144
  const stakeKey = accountKey.derive(2).derive(0);
144
- const stakeCred = CardanoWasm.StakeCredential.from_keyhash(stakeKey.to_raw_key().hash());
145
+ const stakeCred = CardanoWasm.Credential.from_keyhash(stakeKey.to_raw_key().hash());
145
146
  certificates.forEach(cert => {
146
147
  if (cert.type === CertificateType.STAKE_REGISTRATION) {
147
148
  preparedCertificates.add(CardanoWasm.Certificate.new_stake_registration(CardanoWasm.StakeRegistration.new(stakeCred)));
@@ -152,6 +153,26 @@ export const prepareCertificates = (certificates, accountKey) => {
152
153
  else if (cert.type === CertificateType.STAKE_DEREGISTRATION) {
153
154
  preparedCertificates.add(CardanoWasm.Certificate.new_stake_deregistration(CardanoWasm.StakeDeregistration.new(stakeCred)));
154
155
  }
156
+ else if (cert.type === CertificateType.VOTE_DELEGATION) {
157
+ let targetDRep;
158
+ switch (cert.dRep.type) {
159
+ case CardanoDRepType.ABSTAIN:
160
+ targetDRep = CardanoWasm.DRep.new_always_abstain();
161
+ break;
162
+ case CardanoDRepType.NO_CONFIDENCE:
163
+ targetDRep = CardanoWasm.DRep.new_always_no_confidence();
164
+ break;
165
+ case CardanoDRepType.KEY_HASH:
166
+ targetDRep = CardanoWasm.DRep.new_key_hash(CardanoWasm.Ed25519KeyHash.from_hex(cert.dRep.keyHash));
167
+ break;
168
+ case CardanoDRepType.SCRIPT_HASH:
169
+ targetDRep = CardanoWasm.DRep.new_script_hash(CardanoWasm.ScriptHash.from_hex(cert.dRep.scriptHash));
170
+ break;
171
+ }
172
+ if (targetDRep) {
173
+ preparedCertificates.add(CardanoWasm.Certificate.new_vote_delegation(CardanoWasm.VoteDelegation.new(stakeCred, targetDRep)));
174
+ }
175
+ }
155
176
  else {
156
177
  throw new CoinSelectionError(ERROR.UNSUPPORTED_CERTIFICATE_TYPE);
157
178
  }
@@ -161,6 +182,7 @@ export const prepareCertificates = (certificates, accountKey) => {
161
182
  export const calculateRequiredDeposit = (certificates) => {
162
183
  const CertificateDeposit = {
163
184
  [CertificateType.STAKE_DELEGATION]: 0,
185
+ [CertificateType.VOTE_DELEGATION]: 0,
164
186
  [CertificateType.STAKE_POOL_REGISTRATION]: 500000000,
165
187
  [CertificateType.STAKE_REGISTRATION]: 2000000,
166
188
  [CertificateType.STAKE_DEREGISTRATION]: -2000000,
@@ -372,18 +394,22 @@ export const getInitialUtxoSet = (utxos, maxOutput) => {
372
394
  remaining,
373
395
  };
374
396
  };
375
- export const setMaxOutput = (maxOutput, changeOutput) => {
376
- var _a, _b, _c, _d;
397
+ export const setMaxOutput = (txBuilder, maxOutput, changeOutput) => {
398
+ var _a, _b, _c, _d, _e;
377
399
  const maxOutputAsset = (_b = (_a = maxOutput.assets[0]) === null || _a === void 0 ? void 0 : _a.unit) !== null && _b !== void 0 ? _b : 'lovelace';
378
400
  let newMaxAmount = bigNumFromStr('0');
379
401
  const changeOutputAssets = multiAssetToArray(changeOutput === null || changeOutput === void 0 ? void 0 : changeOutput.output.amount().multiasset());
380
402
  if (maxOutputAsset === 'lovelace') {
381
403
  // set maxOutput for ADA
382
404
  if (changeOutput) {
405
+ // Calculate the cost of previous dummy set-max output
406
+ const previousMaxOutputCost = getOutputCost(txBuilder, maxOutput, (_c = maxOutput.address) !== null && _c !== void 0 ? _c : changeOutput.output.address().to_bech32());
383
407
  newMaxAmount = changeOutput.output.amount().coin();
384
408
  if (changeOutputAssets.length === 0) {
385
- // we don't need the change output anymore
386
- newMaxAmount = newMaxAmount.checked_add(changeOutput.outputFee);
409
+ // Add a fee that was previously consumed by the dummy max output.
410
+ // Cost calculated for the change output will be greater (due to larger coin amount
411
+ // than in dummy output - which is 0) than the cost of the dummy set-max output.
412
+ newMaxAmount = newMaxAmount.checked_add(previousMaxOutputCost.outputFee);
387
413
  changeOutput = null;
388
414
  }
389
415
  else {
@@ -402,7 +428,7 @@ export const setMaxOutput = (maxOutput, changeOutput) => {
402
428
  // set maxOutput for token
403
429
  if (changeOutput) {
404
430
  // max amount of the asset in output is equal to its quantity in change output
405
- newMaxAmount = bigNumFromStr((_d = (_c = changeOutputAssets.find(a => a.unit === maxOutputAsset)) === null || _c === void 0 ? void 0 : _c.quantity) !== null && _d !== void 0 ? _d : '0');
431
+ newMaxAmount = bigNumFromStr((_e = (_d = changeOutputAssets.find(a => a.unit === maxOutputAsset)) === null || _d === void 0 ? void 0 : _d.quantity) !== null && _e !== void 0 ? _e : '0');
406
432
  maxOutput.assets[0].quantity = newMaxAmount.to_str(); // TODO: set 0 if no change?
407
433
  const txOutput = CardanoWasm.TransactionOutput.new(changeOutput.output.address(),
408
434
  // new_from_assets does not automatically include required ADA
@@ -433,7 +459,7 @@ export const getRandomUtxo = (txBuilder, utxoRemaining, utxoSelected) => {
433
459
  addUtxo: () => {
434
460
  utxoSelected.push(utxo);
435
461
  const { input, address, amount } = buildTxInput(utxo);
436
- txBuilder.add_input(address, input, amount);
462
+ txBuilder.add_regular_input(address, input, amount);
437
463
  utxoRemaining.splice(utxoRemaining.indexOf(utxo), 1);
438
464
  },
439
465
  };
@@ -1,6 +1,6 @@
1
1
  import { ERROR } from '../constants';
2
- declare type ErrorTypeKeys = keyof typeof ERROR;
3
- declare type ErrorObjectType = typeof ERROR[ErrorTypeKeys];
2
+ type ErrorTypeKeys = keyof typeof ERROR;
3
+ type ErrorObjectType = typeof ERROR[ErrorTypeKeys];
4
4
  export declare class CoinSelectionError extends Error {
5
5
  code: ErrorObjectType['code'];
6
6
  constructor(errorObject: ErrorObjectType);
@@ -133,7 +133,9 @@ const convertCborTxToEncodeTx = async (txHex, utxos, addresses, changeAddress) =
133
133
  },
134
134
  tx: {
135
135
  body: body.to_hex(),
136
- hash: Buffer.from(CardanoWasm.hash_transaction(body).to_bytes(), 'utf8').toString('hex'),
136
+ hash: CardanoWasm.FixedTransaction.new_from_body_bytes(body.to_bytes())
137
+ .transaction_hash()
138
+ .to_hex(),
137
139
  size: 0,
138
140
  rawTxHex: txHex,
139
141
  },
@@ -2,8 +2,8 @@ import { dAppUtils } from './dapp';
2
2
  declare const onekeyUtils: {
3
3
  composeTxPlan: (transferInfo: import("./types").ITransferInfo, accountXpub: string, utxos: import("./types").IAdaUTXO[], changeAddress: string, outputs: import("./types").IOutput[], options?: {
4
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<{
5
+ }) => Promise<import("../../types/types").PrecomposedTransaction>;
6
+ signTransaction: (txBodyHex: string, address: string, accountIndex: number, utxos: import("./types").IAdaUTXO[], xprv: string, signOnly: boolean, partialSign?: boolean) => Promise<{
7
7
  signedTx: string;
8
8
  txid: string;
9
9
  }>;
@@ -1,6 +1,6 @@
1
1
  import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
2
  import { IAdaUTXO } from './types';
3
- declare type SignKeys = {
3
+ type SignKeys = {
4
4
  accountKey: CardanoWasm.Bip32PrivateKey;
5
5
  paymentKey: CardanoWasm.PrivateKey;
6
6
  stakeKey: CardanoWasm.PrivateKey;
@@ -18,7 +18,9 @@ export const signTransaction = async (txBodyHex, address, accountIndex, utxos, x
18
18
  }
19
19
  const transaction = CardanoWasm.Transaction.new(rawTx.body(), witnessSet, rawTx.auxiliary_data());
20
20
  const signedTx = Buffer.from(transaction.to_bytes(), 'hex').toString('hex');
21
- const hash = CardanoWasm.hash_transaction(transaction.body()).to_hex();
21
+ const hash = CardanoWasm.FixedTransaction.new_from_body_bytes(transaction.body().to_bytes())
22
+ .transaction_hash()
23
+ .to_hex();
22
24
  return {
23
25
  signedTx,
24
26
  txid: hash,
@@ -38,7 +40,7 @@ export const signTx = async (keys, tx, keyHashes, partialSign = false) => {
38
40
  const rawTx = CardanoWasm.Transaction.from_bytes(Buffer.from(tx, 'hex'));
39
41
  const txWitnessSet = CardanoWasm.TransactionWitnessSet.new();
40
42
  const vkeyWitnesses = CardanoWasm.Vkeywitnesses.new();
41
- const txHash = CardanoWasm.hash_transaction(rawTx.body());
43
+ const txHash = CardanoWasm.FixedTransaction.new_from_body_bytes(rawTx.body().to_bytes()).transaction_hash();
42
44
  keyHashes.forEach(keyHash => {
43
45
  let signingKey;
44
46
  if (keyHash === paymentKeyHash)
@@ -29,11 +29,11 @@ export declare enum CardanoPoolRelayType {
29
29
  SINGLE_HOST_NAME = 1,
30
30
  MULTIPLE_HOST_NAME = 2
31
31
  }
32
- declare type Key = {
32
+ type Key = {
33
33
  hash: string | null;
34
34
  path: string | null;
35
35
  };
36
- declare type Keys = {
36
+ type Keys = {
37
37
  payment: Key;
38
38
  stake: Key;
39
39
  };
@@ -46,7 +46,6 @@ const generateKeys = (keys, xpub) => {
46
46
  };
47
47
  };
48
48
  const outputsToOneKey = (outputs, changeAddress) => {
49
- var _a, _b;
50
49
  const onekeyOutputs = [];
51
50
  for (let i = 0; i < outputs.len(); i++) {
52
51
  const output = outputs.get(i);
@@ -121,15 +120,15 @@ const outputsToOneKey = (outputs, changeAddress) => {
121
120
  : {
122
121
  address: outputAddressHuman,
123
122
  };
124
- const datumHash = (!output.has_plutus_data() ||
125
- (output.has_plutus_data() && ((_a = output.plutus_data()) === null || _a === void 0 ? void 0 : _a.kind()) === 0)) &&
126
- output.has_data_hash()
123
+ // https://github.com/dcSpark/cardano-multiplatform-lib/blob/c6a6d110065e98ed50640c7380d12748856608cf/chain/rust/src/transaction/mod.rs#L87
124
+ // https://github.com/dcSpark/cardano-multiplatform-lib/blob/c6a6d110065e98ed50640c7380d12748856608cf/chain/rust/src/transaction/mod.rs#L117-L136
125
+ // data_hash : kind = 0
126
+ // plutus_data : kind = 1
127
+ const datumHash = output.has_data_hash()
127
128
  ? output.data_hash().to_hex()
128
129
  : null;
129
- const inlineDatum = output.has_data_hash() &&
130
- output.has_plutus_data() &&
131
- ((_b = output.plutus_data()) === null || _b === void 0 ? void 0 : _b.kind()) === 1
132
- ? output.data_hash().to_hex()
130
+ const inlineDatum = output.has_plutus_data()
131
+ ? output.plutus_data().to_hex()
133
132
  : null;
134
133
  // const datumHash =
135
134
  // output.datum() && output.datum().kind() === 0
@@ -143,7 +142,11 @@ const outputsToOneKey = (outputs, changeAddress) => {
143
142
  ? Buffer.from(output.script_ref().get().to_bytes()).toString('hex')
144
143
  : null;
145
144
  const outputRes = Object.assign({ amount: output.amount().coin().to_str(), tokenBundle,
146
- datumHash, format: inlineDatum || referenceScript ? 1 : 0, inlineDatum,
145
+ datumHash,
146
+ // https://github.com/input-output-hk/nami/commit/a5f5a9357da81307bff9bc77ef2476f1746c134a#diff-1c7110974e24c349d96acac1989fe76c94b0031ab0f5a114e10823e5d74549deR421-R423
147
+ format: Buffer.from(output.to_bytes()).toString('hex').startsWith('a')
148
+ ? 1
149
+ : 0, inlineDatum,
147
150
  referenceScript }, destination);
148
151
  if (!tokenBundle)
149
152
  delete outputRes.tokenBundle;
@@ -401,6 +404,12 @@ export const txToOneKey = async (rawTx, network, initKeys, xpub, changeAddress)
401
404
  keyPath: keys.payment.path,
402
405
  });
403
406
  }
407
+ else if (signer === keys.stake.hash) {
408
+ // https://github.com/input-output-hk/nami/commit/a5f5a9357da81307bff9bc77ef2476f1746c134a#diff-1c7110974e24c349d96acac1989fe76c94b0031ab0f5a114e10823e5d74549deR421-R423
409
+ requiredSigners.push({
410
+ keyPath: keys.stake.path,
411
+ });
412
+ }
404
413
  else {
405
414
  requiredSigners.push({
406
415
  keyHash: signer,