const cors = require('cors')
const { json } = require('body-parser')
const fetch = require('node-fetch')
const { Server, Transaction, TransactionBuilder, Networks, BASE_FEE, Operation, Asset, Memo } = require('stellar-sdk')
const express = require('@runkit/tyvdh/express-endpoint/1.0.0')
const sendError = require('@runkit/tyvdh/send-error/1.0.1')
const app = express(exports)
const server = new Server('https://horizon-testnet.stellar.org')
const functionHash = '4161c53f59e9dcec9c424d31e16fae9f42c09d2dc70060897be8031902ad0369'
const turrets = [{
'url': `https://tss-wrangler.elliotfriend.workers.dev/tx-functions/${functionHash}`,
'token': 'Bearer WyIwMDAwMDAwMDZmYjdkNTNkMGFiMzIxMmVjY2JkMWU2ZmM1OGVkZTlhMjBjMWMxMTFmYzA0NDQ0ZTAyYWNjMDEwMjFhYjcwOTAiLCJlZjkzYzBkZDYyNDc1MGRkNWFhYmI2MzlmNjNiYzk0Mzk2NDg5NDBiYmZhZDg4ZmY2NGQ4MmViNWZjOTk5YzMwODQyMjM3ZjJmOGIyMTNmNDllYWQ0MzExMTQzMzI1YTY4NmY3Mzc5OGVjNzkwMzEwMDYyMTExZjVhMDc1MDMwZSJd',
},
{
'url': `https://tss-wrangler.sdf-ecosystem.workers.dev/tx-functions/${functionHash}`,
'token': 'Bearer WyIwMDAwMDAwMGE2OTU0ZDlmOTY3ZjJlMmZmYWY1NDI3NmNhYzViOTkzMjM2ODViY2UzZDlhMjZiMWM3NDE0ZTE4NTgzYWM2ZDQiLCI1ODNlYTdjZGI5NWVmOWM2YmI2ZjE5YjQ2ODJhNGU3N2EyNzczYzVlY2ZlMTk1ZDMyOTMxZTU5MzNjYmY2MGY4NzM1MzFjOGQzNmUxNjI3MzQ2YWY3MTBhZTQxYzA1YTQxYmQ0MzUzNzcxMWM2M2E4MTRiMjJhZTQyNmI1MTkwMyJd'
}]
async function getTssSignatures( {url, token}, data = {}) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': token
},
body: JSON.stringify(data)
})
return response.json()
}
app.use(cors())
app.use(json())
app.post('/', async (req, res) => {
try {
const { source, destination } = req.body
const lastTransactions = await server.payments().forAccount(source).limit(2).order("desc").call()
let nextAmount = ((lastTransactions.records[0].amount - 0) + (lastTransactions.records[1].amount - 0)).toString()
const fibData = {
source: source,
destination: destination,
amount: nextAmount
}
let response0 = await getTssSignatures(turrets[0], fibData)
let response1 = await getTssSignatures(turrets[1], fibData)
const transaction = new Transaction(response0.xdr, Networks.TESTNET)
transaction.addSignature(response0.signer, response0.signature)
transaction.addSignature(response1.signer, response1.signature)
const transactionResult = await server.submitTransaction(transaction)
res.send(transactionResult.successful)
}
catch(err) {
sendError(err, res)
}
})