Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const assert = require('assert');
const delay = require('delay');
const { getRpc } = require('../rpcs');
const { n } = require('../utils');
const config = require('../config');
const debug = require('consol').debugger('sideshift:pay:zaddr');
const FEE = 0.0001;
module.exports = async function payWithZaddr(paymentMethod, paymentDetails) {
const { zcashSourceZaddr: sourceAddress } = config;
assert(sourceAddress);
const rpc = getRpc(paymentMethod.node);
if (!rpc) {
throw Object.assign(new Error(`Rpc not found for node ${paymentMethod.node}`), { sent: false });
}
const fetchOperastionResult = async operationId => {
while (true) {
const [result] = await rpc.cmdAsync('z_getoperationresult', [operationId]);
if (!result) {
await delay(1000);
continue;
}
return result;
}
};
const { amount, destination } = paymentDetails;
const { address } = destination;
const balanceOfSourceAddress = await rpc.cmdAsync('z_getbalance', sourceAddress);
debug(`Source address ${sourceAddress} has a balance of ${balanceOfSourceAddress}`);
const amountWithFeeN = n(amount).plus(FEE);
if (n(balanceOfSourceAddress).lt(amountWithFeeN)) {
const message = `Cant afford to send ${amount} plus ${FEE} fee. Have ${balanceOfSourceAddress}`;
throw Object.assign(new Error(message), { sent: false });
}
const changeAmountN = n(balanceOfSourceAddress).minus(amountWithFeeN);
const sendManyAmunts = [{ address, amount }, { address: sourceAddress, amount: changeAmountN }];
debug('Will send', { sendManyAmunts });
const operationId = await rpc.cmdAsync('z_sendmany', sourceAddress, sendManyAmunts, 1, FEE);
const operationResult = await fetchOperastionResult(operationId);
assert.equal(operationResult.status, 'success');
const { txid } = operationResult.result;
assert(txid);
return {
sentAmount: amount,
networkFee: FEE.toString(),
tx: { txid },
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.