Skip to content

Instantly share code, notes, and snippets.

@abrkn
Created January 30, 2019 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abrkn/ae4c20ac037c2d559036b7e16ca35576 to your computer and use it in GitHub Desktop.
Save abrkn/ae4c20ac037c2d559036b7e16ca35576 to your computer and use it in GitHub Desktop.
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