import { decodeAddress } from "./AddressHelper"; import { CONTEXT, GENESISHASH_MAIN, GENESISHASH_TEST, Network, Signature } from "./types"; import { BigNumber } from "bignumber.js"; const cbor = require('cbor') import { sha512_256 } from "js-sha512"; export type BuildTransactionArgs = { toAddress: string; amount: string; gas: string; nonce: number; network: Network; signature?: Signature; } const BuildUnsignedTransaction = (args: BuildTransactionArgs) =>{ let txBody = new Map(); let feeData = new Map(); feeData.set("gas", parseInt(args.gas)); feeData.set("amount", Buffer.alloc(0)); txBody.set("fee", feeData); let bodyData = new Map(); bodyData.set("to", decodeAddress(args.toAddress)) let amountBN = new BigNumber(args.amount); amountBN = amountBN.times(new BigNumber(1000000000)); let amountS = amountBN.toString(16); if(amountS.length % 2 != 0) amountS = "0" + amountS; bodyData.set("amount", Buffer.from(amountS, 'hex')); txBody.set("body", bodyData); txBody.set("nonce", args.nonce); txBody.set("method", "staking.Transfer") let encoded = cbor.encode(txBody); return Buffer.from(encoded); } export const BuildTransactionHelper = (args: BuildTransactionArgs) =>{ const unsignedTx = BuildUnsignedTransaction(args); if((args.signature == null)) return unsignedTx; let txBody = new Map(); let signatureData = new Map(); signatureData.set("signature", args.signature.signature); signatureData.set("public_key", args.signature.publicKey); txBody.set("signature", signatureData); txBody.set("untrusted_raw_value", unsignedTx); let encoded = cbor.encode(txBody); let txBytes = Buffer.from(encoded); //Add initial bytes, so tx is ready to be broadcasted let finalBytes = Buffer.concat([ Buffer.alloc(4), //4 zero bytes Buffer.from([txBytes.length]), //txBody length (its always < 255) TODO: Check this. txBytes ]) return finalBytes; } const buildDataToSign = (args: BuildTransactionArgs) => { let unsignedTx = BuildUnsignedTransaction(args); let contextS = CONTEXT; if(args.network == Network.Mainnet){ contextS += GENESISHASH_MAIN; }else{ contextS += GENESISHASH_TEST; } let context = Buffer.from(contextS, "ascii"); return Buffer.concat([ context, unsignedTx ]) } export const getHolaParameters_LINKHelper = (args: BuildTransactionArgs) => { //Get blk let dataToHash = buildDataToSign(args); let sha = sha512_256.create(); sha.update(dataToHash); let blkData = []; blkData.push(Buffer.from(sha.digest())); return { blk: blkData }; };