import { isAddress } from "@ethersproject/address";
import { AddressZero } from "@ethersproject/constants";
import { encodeDepositFunds, encodeWithdrawFunds } from "./interface";
import { getFunds } from "./subgraph";
// Implementation
export async function depositFunds(args) {
    const { fundsTokenAddress = AddressZero } = args;
    if (!isAddress(fundsTokenAddress)) {
        throw new Error(`Invalid fundsTokenAddress: ${fundsTokenAddress}`);
    }
    const isNativeCoin = fundsTokenAddress === AddressZero;
    const transactionRequest = {
        to: args.contractAddress,
        data: encodeDepositFunds(args.entityId, fundsTokenAddress, args.fundsAmount),
        value: isNativeCoin ? args.fundsAmount : "0"
    };
    if (args.returnTxInfo) {
        return transactionRequest;
    }
    else {
        return args.web3Lib.sendTransaction(transactionRequest);
    }
}
// Implementation
export async function withdrawFunds(args) {
    const transactionRequest = {
        to: args.contractAddress,
        data: encodeWithdrawFunds(args.entityId, args.tokensToWithdraw, args.amountsToWithdraw)
    };
    if (args.returnTxInfo) {
        return transactionRequest;
    }
    else {
        return args.web3Lib.sendTransaction(transactionRequest);
    }
}
// Implementation
export async function withdrawAllAvailableFunds(args) {
    const funds = await getFunds(args.subgraphUrl, {
        fundsFilter: {
            accountId: args.entityId.toString()
        }
    });
    const { tokensToWithdraw, amountsToWithdraw } = funds
        .filter((fund) => Number(fund.availableAmount))
        .reduce((acc, fund) => {
        acc.tokensToWithdraw.push(fund.token.address);
        acc.amountsToWithdraw.push(fund.availableAmount);
        return acc;
    }, {
        tokensToWithdraw: [],
        amountsToWithdraw: []
    });
    const transactionRequest = {
        to: args.contractAddress,
        data: encodeWithdrawFunds(args.entityId, tokensToWithdraw, amountsToWithdraw)
    };
    if (args.returnTxInfo) {
        return transactionRequest;
    }
    else {
        return args.web3Lib.sendTransaction(transactionRequest);
    }
}
//# sourceMappingURL=handler.js.map