import BigNumber from "bignumber.js"; import { INSTRUCTION_PREFIX, MESSAGE_PREFIX } from "./Constants"; import { decodeBase58, encodeBase58 } from "./Encoding" var shajs = require('sha.js') export type BuildTransactionArgs = { from: string, to: string, amount: string, fees: string, blockHash: string, signature?: Buffer } export function buildTransactionHelper(args: BuildTransactionArgs): any{ let fromBytes = decodeBase58(args.from); let toBytes = decodeBase58(args.to); let blockBytes = decodeBase58(args.blockHash); let buffer = Buffer.alloc(0); if(args.signature !=null){ buffer = Buffer.concat([ buffer, Buffer.from([0x01]), //Signature count args.signature//Signature ]); } //Add message prefix: buffer = Buffer.concat([ buffer, MESSAGE_PREFIX ]); //Add accounts buffer = Buffer.concat([ buffer, Buffer.from([0x03]), //Number of accounts fromBytes, toBytes, Buffer.alloc(32) ]); //Add blockhash buffer = Buffer.concat([buffer, blockBytes]); //Get amountBytes let amountBN = new BigNumber(args.amount).times(new BigNumber(1000000000)); let amount = BigInt(amountBN.toFixed()); let amountBytes = getBytes(amount).reverse(); while(amountBytes.length % 4 != 0){ amountBytes = Buffer.concat([amountBytes, Buffer.alloc(1)]) } let paramLength = amountBytes.length + 8; //Add instruction buffer = Buffer.concat([ buffer, INSTRUCTION_PREFIX, Buffer.from([paramLength]), Buffer.from([0x02, 0x00, 0x00, 0x00]), amountBytes, Buffer.alloc(4) ]); return buffer; } export function getHolaParametersHelper(args: BuildTransactionArgs): {blk: any[], u32: number[]}{ //Get blk let blkData = []; blkData.push(buildTransactionHelper(args)); //Get fees: let feesBN = new BigNumber(args.fees).times(new BigNumber(1000000)); let fees = BigInt(feesBN.toFixed()); let feesBytes = getBytes(fees).reverse(); blkData.push(feesBytes); //Get u32 let u32Data = []; let valueD = new BigNumber(args.amount).toFixed();; let amountPrecision = 1; if(valueD.includes(".")){ amountPrecision = valueD.split(".")[1].length; } u32Data.push(amountPrecision); let feesD = new BigNumber(args.fees).toFixed();; let feesPrecision = 1; if(feesD.includes(".")){ feesPrecision = feesD.split(".")[1].length; } u32Data.push(feesPrecision); return {blk: blkData, u32: u32Data}; } export function getHolaParameters_LINKHelper(args: BuildTransactionArgs): {blk: any[]}{ //Get blk let blkData = []; //Get tx let tx = buildTransactionHelper(args); //let hash = shajs('sha512').update(tx).digest() blkData.push(tx); return {blk: blkData} } export function getBytes(data: bigint): Buffer{ let hexS = data.toString(16); if(hexS.length % 2 != 0) {hexS = '0' + hexS }; let bytes = Buffer.alloc(hexS.length /2); let cont = 0; for(var i = 0; i< hexS.length; i+=2){ var byte = parseInt(hexS.substring(i, i+2), 16); bytes[cont] = byte; cont++; } return bytes; }