import { Network, Signature } from "./types" import { encodeByte, encodeElement, encodeList } from "./Encoder"; import { getAddressBytes } from "./AddressHelper"; import { formatV, getBytes } from "./TransactionHelper"; import BigNumber from "bignumber.js"; import { Keccak } from "sha3"; var bigInt = require('big-integer') export type BuildERC20TransactionArgs = { nonce: string, gasPrice: string, gasLimit: number, contractAddress: string, toAddress: string, amount: string, contractDecimals: number, contractName: string signature?: Signature, network: Network } export function buildERC20TransactionHelper(args: BuildERC20TransactionArgs): Buffer { let nonce = bigInt(args.nonce); let gasPriceBN = new BigNumber(args.gasPrice); gasPriceBN = gasPriceBN.times(new BigNumber(1000000000)); //GWei to wei let gasPrice = bigInt(gasPriceBN.toFixed()); let gasLimit = bigInt(args.gasLimit); let contractWei = new BigNumber(10).exponentiatedBy(new BigNumber(args.contractDecimals)); let amountBN = new BigNumber(args.amount).times(contractWei); //Ether to wei let value = bigInt(amountBN.toFixed()); let encodedData = []; //Add nonce let nonceB = getBytes(nonce); if (nonceB.length == 1) { encodedData.push(encodeByte(nonceB[0])); } else { encodedData.push(encodeElement(nonceB)); } //Add gasPrice encodedData.push(encodeElement(getBytes(gasPrice))); //Add gasLimit encodedData.push(encodeElement(getBytes(gasLimit))); //Add toAddress encodedData.push(encodeElement(getAddressBytes(args.contractAddress))); //Add amount encodedData.push(encodeElement(Buffer.alloc(0))); //Add message //Add transfer function, toAddress and amount to data let fullToAddress = fillBytes(getAddressBytes(args.toAddress)); let fullValue = fillBytes(getBytes(value)); let dataMessage = Buffer.concat([ Buffer.from([0xa9, 0x05, 0x9c, 0xbb]), fullToAddress, fullValue ]) let message = encodeElement(dataMessage); encodedData.push(message); if (args.signature == null) { let network = formatV(args.network); encodedData.push(encodeElement(network)); encodedData.push(encodeElement(Buffer.alloc(0))); encodedData.push(encodeElement(Buffer.alloc(0))); } else { let v = formatV(args.signature.v) encodedData.push(encodeElement(v)); encodedData.push(encodeElement(args.signature.r)); encodedData.push(encodeElement(args.signature.s)); } let transaction = encodeList(encodedData); return transaction; } export function getERC20HolaParameters_LINKHelper(args: BuildERC20TransactionArgs): {blk: any[]}{ let tx = buildERC20TransactionHelper(args); let hashK256 = new Keccak(256); let resKeccak = hashK256.update(tx).digest(); let blkData = []; blkData.push(resKeccak); return {blk: blkData}; } function fillBytes(data: Buffer): Buffer { let fullBytes = Buffer.alloc(32); if (data.length > fullBytes.length) { throw Error("Data is too long"); } for (let i = 0; i <= data.length; i++) { fullBytes[32 - i] = data[data.length - i]; } return fullBytes; }