@ledgerhq/coin-icon
Version:
Ledger Icon Coin integration
83 lines • 2.93 kB
JavaScript
import { BigNumber } from "bignumber.js";
import { Observable } from "rxjs";
import { encodeOperationId } from "@ledgerhq/coin-framework/operation";
import { buildTransaction } from "./buildTransaction";
import { calculateAmount, getNonce } from "./logic";
import { FeeNotLoaded } from "@ledgerhq/errors";
import IconService from "icon-sdk-js";
const { IconUtil, IconConverter } = IconService;
const buildOptimisticOperation = (account, transaction, fee) => {
const type = "OUT";
const value = new BigNumber(transaction.amount).plus(fee);
const operation = {
id: encodeOperationId(account.id, "", type),
hash: "",
type,
value,
fee,
blockHash: null,
blockHeight: null,
senders: [account.freshAddress],
recipients: [transaction.recipient].filter(Boolean),
accountId: account.id,
transactionSequenceNumber: getNonce(account),
date: new Date(),
extra: {},
};
return operation;
};
/**
* Adds signature to unsigned transaction. Will likely be a call to Icon SDK
*/
const addSignature = (rawTransaction, signature) => {
return {
rawTransaction: {
...rawTransaction,
signature: signature,
},
signature,
};
};
/**
* Sign Transaction with Ledger hardware
*/
export const buildSignOperation = (signerContext) => ({ account, transaction, deviceId, }) => new Observable(o => {
let cancelled = false;
async function main() {
if (!transaction.fees) {
throw new FeeNotLoaded();
}
const transactionToSign = {
...transaction,
amount: calculateAmount({
account: account,
transaction: transaction,
}),
};
const { unsigned } = await buildTransaction(account, transactionToSign, transactionToSign.stepLimit);
o.next({ type: "device-signature-requested" });
const res = (await signerContext(deviceId, signer => signer.signTransaction(account.freshAddressPath, IconUtil.generateHashKey(IconConverter.toRawTransaction(unsigned)))));
const signed = addSignature(unsigned, res.signedRawTxBase64);
if (cancelled)
return;
o.next({ type: "device-signature-granted" });
if (!signed.signature) {
throw new Error("No signature");
}
const operation = buildOptimisticOperation(account, transactionToSign, transactionToSign.fees ?? new BigNumber(0));
o.next({
type: "signed",
signedOperation: {
operation,
signature: signed.signature,
rawData: signed.rawTransaction,
},
});
}
main().then(() => o.complete(), e => o.error(e));
return () => {
cancelled = true;
};
});
export default buildSignOperation;
//# sourceMappingURL=signOperation.js.map