OSDN Git Service

update key relavant logic
[bytom/Bytom-JS-SDK.git] / src / sdk / transaction.js
1 import {convertArgument, signTransaction} from '../wasm/func';
2 import { handleApiError, handleAxiosError } from '../utils/http';
3 import { getDB } from '../db/db';
4
5 function transactionSDK(bytom) {
6     this.http = bytom.serverHttp;
7     this.bytom = bytom;
8 }
9
10
11 /**
12  * List all the transactions related to a wallet or an address.
13  *
14  * @see https://gist.github.com/HAOYUatHZ/0c7446b8f33e7cddd590256b3824b08f#apiv1btmmerchantlist-transactions
15  * @param {String} guid unique id for each wallet
16  * @param {String} filter (optional) if provided, will only return transactions the filter condition is related to
17  * @param {String} sort (optional) if provided, will only return transactions the sort condition is related to
18  * @param {Number} start page start
19  * @param {Number} limit page limit
20  * @returns {Promise}
21  */
22 transactionSDK.prototype.list = function(address, filter,sort, start, limit) {
23     let net = this.bytom.net;
24     let pm = {};
25
26     if (filter) {
27         pm.filter = filter;
28     }
29
30     if (sort) {
31         pm.sort = sort;
32     }
33
34     let url = 'merchant/transactions';
35     let args = new URLSearchParams();
36     if (typeof start !== 'undefined') {
37         args.append('start', start);
38     }
39     if (limit) {
40         args.append('limit', limit);
41     }
42     if (address) {
43         args.append('address', address);
44     }
45     url = url + '?' + args.toString();
46     return this.http.request(url, pm, net);
47 };
48
49 /**
50  * Submit a signed transaction to the chain.
51  *
52  * @see https://gist.github.com/HAOYUatHZ/0c7446b8f33e7cddd590256b3824b08f#apiv1btmmerchantsubmit-payment
53  * @param {String} guid unique id for each wallet
54  * @param {String} raw_transaction raw transaction bytes encoded to string
55  * @param {Array} signatures signed data of each signing instruction
56  */
57 transactionSDK.prototype.submitPayment = function(address, raw_transaction, signatures) {
58     let net = this.bytom.net;
59     let pm = {raw_transaction: raw_transaction, signatures: signatures};
60     return this.http.request(`merchant/submit-payment?address=${address}`, pm, net);
61 };
62
63 /**
64  * Build a raw transaction transfered from the wallet. 
65  * May use all available addresses (under the wallet) as source addresses if not specified.
66  * 
67  * @see https://gist.github.com/HAOYUatHZ/0c7446b8f33e7cddd590256b3824b08f#apiv1btmmerchantbuild-payment
68  * @param {String} guid unique id for each wallet
69  * @param {String} to destination address
70  * @param {String} asset hexdecimal asset id
71  * @param {Number} amount transfer amount
72  * @param {Number} fee transaction fee amount
73  * @param {Number} confirmations - transaction confirmations
74  * @returns {Promise}
75  */
76 transactionSDK.prototype.buildPayment = function(address, to, asset, amount, confirmations, memo, forbidChainTx) {
77     let net = this.bytom.net;
78     let pm = {
79         asset: asset,
80         recipients: {},
81         forbid_chain_tx: false
82     };
83
84     pm['recipients'][`${to}`] = amount;
85
86     if (memo) {
87         pm.memo = memo;
88     }
89     if (forbidChainTx) {
90         pm.forbid_chain_tx = forbidChainTx;
91     }
92     if (confirmations) {
93         pm.confirmations = confirmations;
94     }
95     return this.http.request(`merchant/build-payment?address=${address}`, pm, net);
96 };
97
98 /**
99  * Build a cross chain transaction.
100  *
101  * @param {String} guid unique id for each wallet
102  * @param {String} to destination address
103  * @param {String} asset hexdecimal asset id
104  * @param {Number} amount transfer amount
105  * @param {Number} confirmations - transaction confirmations
106  * @returns {Promise}
107  */
108 transactionSDK.prototype.buildCrossChain = function(address, to, asset, amount, confirmations, forbidChainTx) {
109     let net = this.bytom.net;
110
111     let pm = {
112         asset: asset,
113         recipients: {},
114         forbid_chain_tx: false
115     };
116
117     pm['recipients'][`${to}`] = amount;
118
119     if (forbidChainTx) {
120         pm.forbid_chain_tx = forbidChainTx;
121     }
122
123     return this.http.request(`merchant/build-crosschain?address=${address}`, pm, net);
124 };
125
126 /**
127  * Build a Vote transaction.
128  *
129  * @param {String} guid unique id for each wallet
130  * @param {String} vote pubkey vote
131  * @param {String} memo memo key
132  * @param {Number} amount transfer amount
133  * @param {Number} confirmations - transaction confirmations
134  * @returns {Promise}
135  */
136 transactionSDK.prototype.buildVote = function(address, vote, amount, confirmations, memo, forbidChainTx) {
137     let net = this.bytom.net;
138     let pm = {vote, amount: amount, forbid_chain_tx: false};
139     if (confirmations) {
140         pm.confirmations = confirmations;
141     }
142     if (memo) {
143         pm.memo = memo;
144     }
145     if (forbidChainTx) {
146         pm.forbid_chain_tx = forbidChainTx;
147     }
148
149     return this.http.request(`merchant/build-vote?address=${address}`, pm, net);
150 };
151
152 transactionSDK.prototype.estimateFee = function(address, asset_amounts, confirmations=1) {
153     let net = this.bytom.net;
154     let pm = {asset_amounts, confirmations};
155
156     return this.http.request(`merchant/estimate-tx-fee?address=${address}`, pm, net);
157 };
158
159 /**
160  * Build a Veto transaction.
161  *
162  * @param {String} guid unique id for each wallet
163  * @param {String} vote pubkey vote
164  * @param {String} memo memo key
165  * @param {Number} amount transfer amount
166  * @param {Number} confirmations - transaction confirmations
167  * @returns {Promise}
168  */
169 transactionSDK.prototype.buildVeto = function(address, vote, amount, confirmations, memo,  forbidChainTx) {
170     let net = this.bytom.net;
171     let pm = { vote, amount: amount, forbid_chain_tx: false};
172     if (confirmations) {
173         pm.confirmations = confirmations;
174     }
175     if (memo) {
176         pm.memo = memo;
177     }
178     if (forbidChainTx) {
179         pm.forbid_chain_tx = forbidChainTx;
180     }
181
182     return this.http.request(`merchant/build-veto?address=${address}`, pm, net);
183 };
184
185 /**
186  * Advanced Build a raw transaction transfered from the wallet.
187  * May use all available addresses (under the wallet) as source addresses if not specified.
188  *
189  * @param {String} guid unique id for each wallet
190  * @param {Number} fee transaction fee amount
191  * @returns {Promise}
192  */
193 transactionSDK.prototype.buildTransaction = function(address, inputs, outputs, fee, confirmations, forbid_chain_tx = true) {
194     let net = this.bytom.net;
195     let pm = {
196         inputs,
197         outputs,
198         forbid_chain_tx
199     };
200     if (fee) {
201         pm.fee = fee;
202     }
203     if (confirmations) {
204         pm.confirmations = confirmations;
205     }
206     return this.http.request(`merchant/build-advanced-tx?address=${address}`, pm, net);
207 };
208
209 /**
210  * sign transaction
211  * @param {String} guid
212  * @param {String} transaction
213  * @param {String} password
214  * @returns {Object} signed data
215  */
216 transactionSDK.prototype.signTransaction = function(guid, transaction, password, getKeyByXPub) {
217     let bytom = this.bytom;
218     let retPromise = new Promise((resolve, reject) => {
219         getDB().then(db => {
220             let getRequest = db.transaction(['accounts-server'], 'readonly')
221                 .objectStore('accounts-server')
222                 .index('guid')
223                 .get(guid);
224             getRequest.onsuccess = function(e) {
225                 if (!e.target.result) {
226                     reject(new Error('not found guid'));
227                     return;
228                 }
229                 const res = getKeyByXPub(e.target.result.rootXPub)[0];
230                 if(!res){
231                     reject('not found xpub');
232                 }else{
233                     const key = res.key;
234                     let pm = {transaction: transaction, password: password, key: key};
235                     signTransaction(pm).then(res => {
236                         resolve(JSON.parse(res.data));
237                     }).catch(err => {
238                         reject(err);
239                     });
240                 }
241             };
242             getRequest.onerror = function() {
243                 reject(getRequest.error);
244             };
245         }).catch(error => {
246             reject(error);
247         });
248     });
249     return retPromise;
250 };
251
252 transactionSDK.prototype._signTransaction = function( transaction, password, key) {
253     let pm = {transaction: transaction, password: password, key: key};
254     return signTransaction(pm).then(res => {
255         return JSON.parse(res.data);
256     }).catch(err => {
257         throw (err);
258     });
259 };
260
261 /**
262  * Convert arguement.
263  *
264  * @param {String} type - type.
265  * @param {String} value - value.
266  */
267 transactionSDK.prototype.convertArgument = function(type, value) {
268     let retPromise = new Promise((resolve, reject) => {
269         let data = {};
270         data.type = type;
271         data.raw_data = JSON.stringify({value});
272         convertArgument(data).then((res) => {
273             let jsonData = JSON.parse(res.data);
274             resolve(jsonData);
275         }).catch(error => {
276             reject(error);
277         });
278     });
279     return retPromise;
280 };
281
282 export default transactionSDK;