Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function generateHtlcTransaction(sender, recipient, hash, value, timeout) {
const hashAlgo = Nimiq.Hash.Algorithm.SHA256
const hashCount = 1
value = Nimiq.Policy.coinsToSatoshis(value)
timeout = $.blockchain.height + timeout
const bufferSize = sender.serializedSize
+ recipient.serializedSize
+ /* hashAlgo */ 1
+ hash.byteLength
+ /* hashCount */ 1
+ /* timeout */ 4;
const buffer = new Nimiq.SerialBuffer(bufferSize);
sender.serialize(buffer);
recipient.serialize(buffer);
buffer.writeUint8(hashAlgo);
buffer.write(hash);
buffer.writeUint8(hashCount);
buffer.writeUint32(timeout);async function nimForEth() {
const ethWallet = eth.addWallet(nim.getWalletPrivateKey())
console.log('Local ETH wallet address =', ethWallet);
let nimRecipient = await prompt('Enter NIM address of recipient: ')
let value = await prompt('Enter NIM amount to send: ')
value = parseFloat(value)
const ethRecipient = await prompt('Enter ETH address to receive funds: ')
const secret = randomBytes(32)
console.log('Secret:', '0x' + Buffer.from(secret).toString('hex'));
let hash = Nimiq.Hash.computeSha256(secret)
const nimHtlcAddress = await nim.deployHTLC(nimRecipient, hash, value)
hash = '0x' + Buffer.from(hash).toString('hex')
const ethHtlcAddress = await eth.deployHTLC(ethWallet, ethRecipient, hash)
console.log('NIM HTLC address:', nimHtlcAddress);
console.log('ETH HTLC address:', ethHtlcAddress);
console.log(`Enter 1 if agreed amount of ETH has been sent to ${ethHtlcAddress}`);
let answer = await prompt('Or enter 2 to recover your NIM after the timeout (wait 1 hour): ')
switch (answer) {
case '1':
console.log('Resolving ETH HTLC...');
await eth.resolveHTLC(ethWallet, ethHtlcAddress, '0x' + secret.toString('hex'))
break
case '2':
nimRecipient = await prompt('Enter NIM address to receive funds: ')
await nim.refundHTLC(nimHtlcAddress, nimRecipient)
breakaddress = Nimiq.Address.fromString(address)
recipient = Nimiq.Address.fromString(recipient)
const account = await $.consensus.getAccount(address)
const tx = new Nimiq.ExtendedTransaction(
address, Nimiq.Account.Type.HTLC,
recipient, Nimiq.Account.Type.BASIC,
account.balance, 0,
$.blockchain.height + 1,
Nimiq.Transaction.Flag.NONE, new Uint8Array(0))
const sig = Nimiq.Signature.create($.wallet.keyPair.privateKey, $.wallet.publicKey, tx.serializeContent())
const sigProof = new Nimiq.SignatureProof($.wallet.publicKey, new Nimiq.MerklePath([]), sig)
tx.proof = new Nimiq.SerialBuffer(3 + 2 * Nimiq.Hash.SIZE.get(Nimiq.Hash.Algorithm.SHA256) + sigProof.serializedSize)
tx.proof.writeUint8(Nimiq.HashedTimeLockedContract.ProofType.REGULAR_TRANSFER)
tx.proof.writeUint8(Nimiq.Hash.Algorithm.SHA256)
tx.proof.writeUint8(1)
Nimiq.Hash.fromHex(hashRoot.slice(2)).serialize(tx.proof)
Nimiq.Hash.fromHex(preImage.slice(2)).serialize(tx.proof)
sigProof.serialize(tx.proof)
await sendTransaction(tx)
}