Commit 33f5c0c5 authored by Allan Juma's avatar Allan Juma

update swap backend

parent 97336715
......@@ -143,8 +143,8 @@ class PoolAddAction {
//check if contract has enough balance first
console.log(parseFloat(this._store.settings.chains.algo.account.balance)*100, (amount*1.1));
if(parseFloat(this._store.settings.chains.algo.account.balance)*100 > (amount*1.1)){
console.log(parseFloat(this._store.settings.chains.algo.account.balance)*100, (amount*1.01));
if(parseFloat(this._store.settings.chains.algo.account.balance)*100 > (amount*1.01)){
console.log('INFO! contract has sufficient balance');
}else{
......
......@@ -4,7 +4,8 @@
*/
import { PREFIX_URI } from '../config';
import { toSatoshis } from '../helper';
import { toSatoshis, addAsaQuote } from '../helper';
class PoolRemoveLiqAction {
constructor(store, grpc, nav, notification, clipboard) {
......@@ -20,12 +21,13 @@ class PoolRemoveLiqAction {
* and then navigating to the view.
* @return {undefined}
*/
init() {
async init() {
this._store.invoice.amount = '';
this._store.invoice.note = 'POOL:REMOVE:98044b80f029ae6d007a6344b66d850435dace8533fb4aa16848d37031c4d459';
this._store.invoice.encoded = '';
this._store.invoice.uri = '';
this._nav.goPoolRemoveLiquid();
this._quote = await addAsaQuote(this._grpc,this._store,75685483, 0);
}
/**
......@@ -35,6 +37,10 @@ class PoolRemoveLiqAction {
*/
setAmount({ amount }) {
this._store.invoice.amount = amount;
console.log('INFO! ASA tokens sold are :', amount/this._quote);
}
/**
......@@ -58,21 +64,25 @@ class PoolRemoveLiqAction {
* the necessary error handling and notification display.
* @return {Promise<undefined>}
*/
async confirmRem() {
var amount = this._store.invoice.amount/this._store.selectedPool.quote;
var poolStats = await this._grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', this._store.selectedPool.assetID , 0, parseInt(amount), this._store.settings.chains.algo.account.address, this._store.settings.chains.algo.account.mnemonic, 'remove' ]);
console.log(poolStats);
}
async generateUri() {
try {
const { invoice, settings } = this._store;
const satAmount = toSatoshis(invoice.amount, settings);
this.checkAmount({ satAmount });
const response = await this._grpc.sendCommand('addInvoice', {
value: satAmount,
memo: invoice.note,
expiry: 172800,
private: true,
});
invoice.encoded = response.paymentRequest;
invoice.uri = `${PREFIX_URI}${invoice.encoded}`;
//this._nav.goInvoiceQR();
this._nav.goPoolRemLiqConf();
} catch (err) {
this._notification.display({ msg: 'Creating invoice failed!', err });
}
......
......@@ -60,12 +60,15 @@ class PoolAction {
var grpc = hii._grpc;
var store = hii._store;
console.log(pool);
var ret = {
id: pool.id,
cat: 'micro',
type: 'algorand',
icon: pool.bannerPath,
quote: await addAsaQuote(grpc,store,75685483, 0),
//quote: await addAsaQuote(grpc,store,75685483, 0),
quote: await addAsaQuote(grpc,store,pool.poolID.id, 0),
assetID: pool.poolID.id,
banner: pool.bannerPath,
url: 'https://demo1.bitsoko.org',
title: pool.name,
......@@ -88,7 +91,7 @@ var ret = {
async getPools() {
try {
const uri = 'https://gateway.bitsoko.org/getEnterprise/?servEntID=1';
const uri = 'https://dooca.bitsoko.org/getEnterprise/?servEntID=1';
//const uri = 'https://gateway.bitsoko.org/getEnterpriseRoute';
const response = checkHttpStatus(await fetch(uri));
......@@ -99,12 +102,9 @@ var ret = {
var quote = await this.addQuote;
var pooled = await Promise.allSettled(pools.map(this.poolsToPool));
console.log(pooled);
pooled = pooled.filter(function(pl){
console.log(pl.quote);
return pl.status == 'fulfilled' && pl.value.quote != undefined;
});
console.log(pooled);
this._store.pools = pooled.map(function(pl){
if(pl.status == 'fulfilled'){
var ret = pl.value;
......
......@@ -99,12 +99,12 @@ class TinymanClient:
class TinymanTestnetClient(TinymanClient):
def __init__(self, algod_client=None, user_address=None):
if algod_client is None:
algod_client = AlgodClient('', 'https://api.testnet.algoexplorer.io', headers={'User-Agent': 'algosdk'})
algod_client = AlgodClient('', 'https://api.testnet.algoexplorer.io/v2', headers={'User-Agent': 'algosdk'})
super().__init__(algod_client, validator_app_id=TESTNET_VALIDATOR_APP_ID, user_address=user_address)
class TinymanMainnetClient(TinymanClient):
def __init__(self, algod_client=None, user_address=None):
if algod_client is None:
algod_client = AlgodClient('', 'https://api.algoexplorer.io', headers={'User-Agent': 'algosdk'})
algod_client = AlgodClient('', 'https://api.algoexplorer.io/v2', headers={'User-Agent': 'algosdk'})
super().__init__(algod_client, validator_app_id=MAINNET_VALIDATOR_APP_ID, user_address=user_address)
......@@ -68,24 +68,24 @@ def swap(client,action,aID1,aID2,account,mne,amount):
wait_for_confirmation(txid)
# Fetch our two assets of interest
ASA = Asset(id=aID1, name='ASA', unit_name='ASA', decimals=0)
BTC = Asset(id=aID2, name='Algo', unit_name='ALGO', decimals=6)
BTC = Asset(id=aID2, name='BTC satoshis', unit_name='BTC', decimals=6)
# Create the pool we will work with and fetch its on-chain state
pool = Pool(client, asset_a=ASA, asset_b=BTC, fetch=True)
amount = 10_000_000
#amount = 10_000_000
# Get a quote for a swap of 1 ALGO to TINYUSDC with 1% slippage tolerance
if action == 'add':
quote = pool.fetch_fixed_input_swap_quote(BTC(10_000_000), slippage=0.01)
quote = pool.fetch_fixed_input_swap_quote(BTC(amount), slippage=0.01)
elif action == 'remove':
quote = pool.fetch_fixed_input_swap_quote(ASA(1_0), slippage=0.01)
quote = pool.fetch_fixed_input_swap_quote(ASA(amount), slippage=0.01)
#
print(quote)
print(f'ASA per BTC: {str(quote.price)}')
print(f'ASA per BTC (worst case): {str(quote.price_with_slippage)}')
print(f'ASA per BTC satoshi: {str(quote.price)}')
print(f'ASA per BTC satoshi (worst case): {str(quote.price_with_slippage)}')
# We only want to sell if BTC is > 0 ASA
if quote.price_with_slippage > 0:
......@@ -101,8 +101,8 @@ def swap(client,action,aID1,aID2,account,mne,amount):
for i, txn in enumerate(transaction_group.transactions):
if txn.sender == account['address']:
transaction_group.signed_transactions[i] = txn.sign(account['private_key'])
txid = algod.send_transactions(transaction_group.signed_transactions)
wait_for_confirmation(algod, txid)
txid = client.algod.send_transactions(transaction_group.signed_transactions)
wait_for_confirmation(client.algod, txid)
# Check if any excess remaining after the swap
excess = pool.fetch_excess_amounts(account['address'])
......@@ -116,8 +116,8 @@ def swap(client,action,aID1,aID2,account,mne,amount):
for i, txn in enumerate(transaction_group.transactions):
if txn.sender == account['address']:
transaction_group.signed_transactions[i] = txn.sign(account['private_key'])
txid = algod.send_transactions(transaction_group.signed_transactions)
wait_for_confirmation(algod, txid)
txid = client.algod.send_transactions(transaction_group.signed_transactions)
wait_for_confirmation(client.algod, txid)
......@@ -151,19 +151,16 @@ if action == "swap":
action = sys.argv[7]
aID1 = int(sys.argv[2])
aID2 = int(sys.argv[3])
amount = sys.argv[4]
amount = int(sys.argv[4])
priv_key = mnemonic.to_private_key(mne)
account = {
'address': pooler_address,
'private_key': priv_key,
}
algod = AlgodClient('', 'https://api.testnet.algoexplorer.io', headers={'User-Agent': 'algosdk'})
client = TinymanClient(
algod_client=algod,
validator_app_id=62368684,
)
client = TinymanTestnetClient(user_address=account['address'])
swap(client,action,aID1,aID2,account,mne,amount)
......@@ -190,6 +187,8 @@ if action == "swap":
if action == "quote":
client = TinymanTestnetClient()
aID1 = int(sys.argv[2])
......@@ -203,8 +202,8 @@ if action == "quote":
# Fetch the pool we will work with
pool = client.fetch_pool(ASA, BTC)
# Get a quote for a swap of 1 BTC to ASA with 1% slippage tolerance
quote = pool.fetch_fixed_input_swap_quote(BTC(1_000_000), slippage=0.01)
# Get a quote for a swap of 1 ASA with 1% slippage tolerance
quote = pool.fetch_fixed_input_swap_quote(ASA(1), slippage=0.01)
reg = re.search("('([^/,]*)')",str(quote.amount_out))
result = reg.group(1)
......
......@@ -145,10 +145,12 @@ export const toAmountLabel = (satoshis, settings) => {
export const addAsaQuote = async (grpc, store, aID1, aID2) => {
var quote = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'quote', aID1, aID2 ]);
console.log(quote);
try{
var q = quote.split("'")[1].split("'")[0];
var ql = toAmountLabel(parseInt((1/parseInt(q))*1000000),store.settings);
var amt = parseInt(parseFloat(q)*1000000);
//console.log(amt);
if(!Number.isInteger(amt)) amt = 0;
var ql = toAmount(amt,store.settings);
return ql;
}catch(er){console.error(er)}
}
......
......@@ -39,7 +39,7 @@ ChartJS.register(ArcElement, Tooltip, Legend);
if(parseFloat(store.settings.chains.algo.account.balance)*100 > (amount*1.01)){
console.log('INFO! sufficient BTC in contract. skipping lightning swap...');
var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', 75685483 , 0, 10, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 'add' ]);
var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', store.selectedPool.assetID , 0, amount, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 'add' ]);
if(poolStats.includes('confirmed in round')){
......@@ -54,10 +54,9 @@ ChartJS.register(ArcElement, Tooltip, Legend);
}
} else if ( store.payment.address != '' ) {
//return this._notification.display({ msg: 'INFO! swapping lightning BTC to contract BTC' });
// first test is contract can complete transaction
var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', 75685483 , 0, 10, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 'add' ]);
var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', store.selectedPool.assetID , 0, amount, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 'add' ]);
console.log(poolStats);
if(poolStats.includes('confirmed in round')){
......@@ -67,11 +66,14 @@ ChartJS.register(ArcElement, Tooltip, Legend);
return true;
}
const { payment, settings } = store;
try{
const request = await grpc.sendCommand('decodePayReq', {
payReq: store.payment.address,
});
payment.amount = toAmount(request.numSatoshis, settings);
payment.note = request.description;
/*
......@@ -108,7 +110,7 @@ var pH = btoa(String.fromCharCode.apply(null, paymentHash.paymentHash));
*/
// then add converted contract satoshis to merchant pool
var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', 75685483 , 0, 10, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 'add' ]);
var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', store.selectedPool.assetID , 0, amount, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 'add' ]);
console.log(poolStats);
//this._notification.display({ msg: 'Swap completed!' });
......
......@@ -117,11 +117,11 @@ const PoolRemLiqConfView = ({ store, nav, poolremoveliq }) => (
<Button onPress={() => nav.goHome()} style={styles.doneBtn}>
<Button onPress={() => poolremoveliq.confirmRem()} style={styles.doneBtn}>
<ButtonText style={styles.doneRemText}>REMOVE</ButtonText>
</Button>
<Button onPress={() => nav.goPoolRemLiqConf()} style={styles.doneBtn}>
<ButtonText style={styles.doneBtnText}>Cancel</ButtonText>
<Button onPress={() => nav.goPoolRemoveLiquid()} style={styles.doneBtn}>
<ButtonText style={styles.doneBtnText}>back</ButtonText>
</Button>
</Card>
<CopiedNotification
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment