OSDN Git Service

removed update-base from font-end
[bytom/Bytom-Dapp-Demo.git] / src / components / layout / save / action.js
1 import {
2   spendUTXOAction, spendWalletAction, controlProgramAction,
3   controlAddressAction, listDappUTXO, updateUtxo ,updateBalances,
4   contractArguments
5 } from '../../bytom'
6 import {
7   depositProgram, profitProgram, assetDeposited, assetBill, gas
8 } from "../../constants";
9
10 export function FixedLimitDeposit(account, amount, address) {
11   return new Promise((resolve, reject) => {
12     return listDappUTXO({
13       "program": depositProgram,
14       "asset": assetBill
15     }).then(resp => {
16       const billAmount = resp.amount
17       const billAsset = resp.asset
18       const utxo = resp.hash
19
20       if(amount > billAmount){
21         throw 'input amount must be smaller or equal to ' + billAmount +'.'
22       }else{
23         const input = []
24         const output = []
25
26         const args = contractArguments(amount, address)
27
28         input.push(spendUTXOAction(utxo))
29         input.push(spendWalletAction(amount, assetDeposited))
30
31         if(amount < billAmount){
32           output.push(controlProgramAction(amount, assetDeposited, profitProgram))
33           output.push(controlAddressAction(amount, billAsset, address))
34           output.push(controlProgramAction((billAmount-amount), billAsset, depositProgram))
35         }else{
36           output.push(controlProgramAction(amount, assetDeposited, profitProgram))
37           output.push(controlAddressAction(billAmount, billAsset, address))
38         }
39
40         window.bytom.advancedTransfer(account, input, output, gas*10000000, args)
41           .then((resp) => {
42             if(resp.action === 'reject'){
43               reject('user reject the request')
44             }else if(resp.action === 'success'){
45               updateUtxo({"hash": utxo})
46                 .then(()=>{
47                   updateBalances({
48                     address,
49                     "asset": assetDeposited,
50                     "amount": -amount
51                   }).then(()=>{
52                     updateBalances({
53                       address,
54                       "asset": assetBill,
55                       "amount": amount
56                     }).then(()=>{
57                       resolve()
58                     }).catch(err => {
59                       throw err
60                     })
61                   }).catch(err => {
62                     throw err
63                   })
64                 })
65                 .catch(err => {
66                   throw err
67                 })
68             }
69           })
70           .catch(err => {
71             throw err
72           })
73       }
74     }).catch(err => {
75       reject(err)
76     })
77   })
78 }