|
| 1 | +import { ISDK } from '@cypherock/sdk-core'; |
| 2 | +import { |
| 3 | + createStatusListener, |
| 4 | + assert, |
| 5 | + uint8ArrayToHex, |
| 6 | + createLoggerWithPrefix, |
| 7 | +} from '@cypherock/sdk-utils'; |
| 8 | +import { APP_VERSION } from '../../constants/appId'; |
| 9 | +import { |
| 10 | + SeedGenerationStatus, |
| 11 | + SignTxnStatus, |
| 12 | +} from '../../proto/generated/types'; |
| 13 | +import { |
| 14 | + assertOrThrowInvalidResult, |
| 15 | + OperationHelper, |
| 16 | + logger as rootLogger, |
| 17 | +} from '../../utils'; |
| 18 | +import { ISignTxnParams, ISignTxnResult, SignTxnEvent } from './types'; |
| 19 | + |
| 20 | +export * from './types'; |
| 21 | + |
| 22 | +const logger = createLoggerWithPrefix(rootLogger, 'SignTxn'); |
| 23 | + |
| 24 | +export const signTxn = async ( |
| 25 | + sdk: ISDK, |
| 26 | + params: ISignTxnParams, |
| 27 | +): Promise<ISignTxnResult> => { |
| 28 | + assert(params, 'Params should be defined'); |
| 29 | + assert(params.walletId, 'walletId should be defined'); |
| 30 | + assert(params.txn, 'txn should be defined'); |
| 31 | + assert(typeof params.txn === 'object', 'txn should be an object'); |
| 32 | + assert(params.derivationPath, 'derivationPath should be defined'); |
| 33 | + assert( |
| 34 | + params.derivationPath.length === 5, |
| 35 | + 'derivationPath should be equal to 5', |
| 36 | + ); |
| 37 | + |
| 38 | + await sdk.checkAppCompatibility(APP_VERSION); |
| 39 | + |
| 40 | + const { onStatus, forceStatusUpdate } = createStatusListener({ |
| 41 | + enums: SignTxnEvent, |
| 42 | + operationEnums: SignTxnStatus, |
| 43 | + seedGenerationEnums: SeedGenerationStatus, |
| 44 | + onEvent: params.onEvent, |
| 45 | + logger, |
| 46 | + }); |
| 47 | + |
| 48 | + const helper = new OperationHelper({ |
| 49 | + sdk, |
| 50 | + queryKey: 'signTxn', |
| 51 | + resultKey: 'signTxn', |
| 52 | + onStatus, |
| 53 | + }); |
| 54 | + |
| 55 | + await helper.sendQuery({ |
| 56 | + initiate: { |
| 57 | + walletId: params.walletId, |
| 58 | + derivationPath: params.derivationPath, |
| 59 | + }, |
| 60 | + }); |
| 61 | + |
| 62 | + const { confirmation } = await helper.waitForResult(); |
| 63 | + assertOrThrowInvalidResult(confirmation); |
| 64 | + forceStatusUpdate(SignTxnEvent.CONFIRM); |
| 65 | + |
| 66 | + await helper.sendQuery({ |
| 67 | + txnData: params.txn, |
| 68 | + }); |
| 69 | + |
| 70 | + const accepted = await helper.waitForResult(); |
| 71 | + assertOrThrowInvalidResult(accepted.unsignedTxnAccepted); |
| 72 | + |
| 73 | + await helper.sendQuery({ |
| 74 | + signature: {}, |
| 75 | + }); |
| 76 | + const result = await helper.waitForResult(); |
| 77 | + assertOrThrowInvalidResult(result.signature); |
| 78 | + |
| 79 | + forceStatusUpdate(SignTxnEvent.PIN_CARD); |
| 80 | + |
| 81 | + return { |
| 82 | + signature: uint8ArrayToHex(result.signature.signature), |
| 83 | + }; |
| 84 | +}; |
0 commit comments