added deploy_at, join_group, publish qdn

This commit is contained in:
Phillip 2023-02-23 23:20:15 +00:00
parent ed1eeac37e
commit 6568d7600d
4 changed files with 467 additions and 148 deletions

View File

@ -0,0 +1,91 @@
'use strict'
import TransactionBase from './TransactionBase.js'
export default class DeployAtTransaction extends TransactionBase {
constructor() {
super()
this.type = 16
}
render(html) {
return html`
${this._groupdialog5}
<div style="background: #eee; padding: 8px; margin: 8px 0; border-radius: 5px;">
<div>${this._atDeployDialog1}: <span style="color: #000;">${this._rName}</span></div>
<br>
<div>${this.atDeployDialog2}: <span style="color: #000;">${this._rDescription}</span></div>
<br>
</div>
</div>
${this._groupdialog6}
`
}
set atDeployDialog1(atDeployDialog1) {
this._atDeployDialog1 = atDeployDialog1
}
set atDeployDialog2(atDeployDialog2) {
this._atDeployDialog2 = atDeployDialog2
}
set fee(fee) {
this._fee = fee
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee)
}
set rAmount(rAmount) {
this._rAmount = rAmount
this._rAmountBytes = this.constructor.utils.int64ToBytes(this._rAmount)
}
set rName(rName) {
this._rName = rName
this._rNameBytes = this.constructor.utils.stringtoUTF8Array(this._rName.toLocaleLowerCase())
this._rNameLength = this.constructor.utils.int32ToBytes(this._rNameBytes.length)
}
set rDescription(rDescription) {
this._rDescription = rDescription
this._rDescriptionBytes = this.constructor.utils.stringtoUTF8Array(this._rDescription.toLocaleLowerCase())
this._rDescriptionLength = this.constructor.utils.int32ToBytes(this._rDescriptionBytes.length)
}
set atType(atType) {
this._atType = atType
this._atTypeBytes = this.constructor.utils.stringtoUTF8Array(this._atType)
this._atTypeLength = this.constructor.utils.int32ToBytes(this._atTypeBytes.length)
}
set rTags(rTags) {
this._rTags = rTags
this._rTagsBytes = this.constructor.utils.stringtoUTF8Array(this._rTags.toLocaleLowerCase())
this._rTagsLength = this.constructor.utils.int32ToBytes(this._rTagsBytes.length)
}
set rCreationBytes(rCreationBytes) {
const decode = this.constructor.Base58.decode(rCreationBytes)
console.log({decode})
this._rCreationBytes = this.constructor.utils.stringtoUTF8Array(decode)
this._rCreationBytesLength = this.constructor.utils.int32ToBytes(this._rCreationBytes.length)
}
set rAssetId(rAssetId) {
this._rAssetId = this.constructor.utils.int64ToBytes(rAssetId)
}
get params() {
const params = super.params
params.push(
this._rNameLength,
this._rNameBytes,
this._rDescriptionLength,
this._rDescriptionBytes,
this._atTypeLength,
this._atTypeBytes,
this._rTagsLength,
this._rTagsBytes,
this._rCreationBytesLength,
this._rCreationBytes,
this._rAmountBytes,
this._rAssetId,
this._feeBytes
)
return params
}
}

View File

@ -22,6 +22,7 @@ import LeaveGroupTransaction from './groups/LeaveGroupTransaction.js'
import RewardShareTransaction from './reward-share/RewardShareTransaction.js' import RewardShareTransaction from './reward-share/RewardShareTransaction.js'
import RemoveRewardShareTransaction from './reward-share/RemoveRewardShareTransaction.js' import RemoveRewardShareTransaction from './reward-share/RemoveRewardShareTransaction.js'
import TransferPrivsTransaction from './TransferPrivsTransaction.js' import TransferPrivsTransaction from './TransferPrivsTransaction.js'
import DeployAtTransaction from './DeployAtTransaction.js'
export const transactionTypes = { export const transactionTypes = {
2: PaymentTransaction, 2: PaymentTransaction,
@ -30,6 +31,7 @@ export const transactionTypes = {
5: SellNameTransacion, 5: SellNameTransacion,
6: CancelSellNameTransacion, 6: CancelSellNameTransacion,
7: BuyNameTransacion, 7: BuyNameTransacion,
16: DeployAtTransaction,
17: MessageTransaction, 17: MessageTransaction,
18: ChatTransaction, 18: ChatTransaction,
181: GroupChatTransaction, 181: GroupChatTransaction,

View File

@ -119,7 +119,7 @@ class WebBrowser extends LitElement {
this.path = this.path =
urlParams.get('path') != null urlParams.get('path') != null
? (urlParams.get('path').startsWith('/') ? '' : '/') + ? (urlParams.get('path').startsWith('/') ? '' : '/') +
urlParams.get('path') urlParams.get('path')
: ''; : '';
this.followedNames = []; this.followedNames = [];
this.blockedNames = []; this.blockedNames = [];
@ -166,23 +166,20 @@ class WebBrowser extends LitElement {
const render = () => { const render = () => {
const myNode = const myNode =
window.parent.reduxStore.getState().app.nodeConfig.knownNodes[ window.parent.reduxStore.getState().app.nodeConfig.knownNodes[
window.parent.reduxStore.getState().app.nodeConfig.node window.parent.reduxStore.getState().app.nodeConfig.node
]; ];
const nodeUrl = const nodeUrl =
myNode.protocol + '://' + myNode.domain + ':' + myNode.port; myNode.protocol + '://' + myNode.domain + ':' + myNode.port;
this.url = `${nodeUrl}/render/${this.service}/${this.name}${ this.url = `${nodeUrl}/render/${this.service}/${this.name}${this.path != null ? this.path : ''
this.path != null ? this.path : '' }?theme=${this.theme}&identifier=${this.identifier != null ? this.identifier : ''
}?theme=${this.theme}&identifier=${ }`;
this.identifier != null ? this.identifier : ''
}`;
}; };
const authorizeAndRender = () => { const authorizeAndRender = () => {
parentEpml parentEpml
.request('apiCall', { .request('apiCall', {
url: `/render/authorize/${ url: `/render/authorize/${this.name
this.name }?apiKey=${this.getApiKey()}`,
}?apiKey=${this.getApiKey()}`,
method: 'POST', method: 'POST',
}) })
.then((res) => { .then((res) => {
@ -231,7 +228,6 @@ class WebBrowser extends LitElement {
} }
render() { render() {
console.log(2, 'browser page here');
return html` return html`
<div id="websitesWrapper" style="width:auto; padding:10px; background: var(--white);"> <div id="websitesWrapper" style="width:auto; padding:10px; background: var(--white);">
<div class="layout horizontal center"> <div class="layout horizontal center">
@ -248,24 +244,22 @@ class WebBrowser extends LitElement {
<mwc-button @click=${() => this.goBackToList()} title="${translate( <mwc-button @click=${() => this.goBackToList()} title="${translate(
'browserpage.bchange3' 'browserpage.bchange3'
)}" class="address-bar-button"><mwc-icon>home</mwc-icon></mwc-button> )}" class="address-bar-button"><mwc-icon>home</mwc-icon></mwc-button>
<input disabled style="width: 550px; color: var(--black);" id="address" type="text" value="${ <input disabled style="width: 550px; color: var(--black);" id="address" type="text" value="${this.displayUrl
this.displayUrl }"></input>
}"></input>
<mwc-button @click=${() => this.delete()} title="${translate( <mwc-button @click=${() => this.delete()} title="${translate(
'browserpage.bchange4' 'browserpage.bchange4'
)} ${this.service} ${this.name} ${translate( )} ${this.service} ${this.name} ${translate(
'browserpage.bchange5' 'browserpage.bchange5'
)}" class="address-bar-button float-right"><mwc-icon>delete</mwc-icon></mwc-button> )}" class="address-bar-button float-right"><mwc-icon>delete</mwc-icon></mwc-button>
${this.renderBlockUnblockButton()} ${this.renderBlockUnblockButton()}
${this.renderFollowUnfollowButton()} ${this.renderFollowUnfollowButton()}
</div> </div>
<div class="iframe-container"> <div class="iframe-container">
<iframe id="browser-iframe" src="${ <iframe id="browser-iframe" src="${this.url
this.url }" sandbox="allow-scripts allow-forms allow-downloads">
}" sandbox="allow-scripts allow-forms allow-downloads">
<span style="color: var(--black);">${translate( <span style="color: var(--black);">${translate(
'browserpage.bchange6' 'browserpage.bchange6'
)}</span> )}</span>
</iframe> </iframe>
</div> </div>
</div> </div>
@ -273,6 +267,142 @@ class WebBrowser extends LitElement {
`; `;
} }
async unitJoinFee() {
const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node]
const nodeUrl = myNode.protocol + '://' + myNode.domain + ':' + myNode.port
const url = `${nodeUrl}/transactions/unitfee?txType=JOIN_GROUP`
const response = await fetch(url)
if (!response.ok) {
throw new Error('Error when fetching join fee');
}
const data = await response.json()
const joinFee = (Number(data) / 1e8).toFixed(8)
return joinFee
}
async deployAtFee() {
const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node]
const nodeUrl = myNode.protocol + '://' + myNode.domain + ':' + myNode.port
const url = `${nodeUrl}/transactions/unitfee?txType=DEPLOY_AT`
const response = await fetch(url)
if (!response.ok) {
throw new Error('Error when fetching join fee');
}
const data = await response.json()
const joinFee = data
return joinFee
}
async _joinGroup(groupId, groupName) {
const joinFeeInput = await this.unitJoinFee()
const getLastRef = async () => {
let myRef = await parentEpml.request('apiCall', {
type: 'api',
url: `/addresses/lastreference/${this.selectedAddress.address}`
})
return myRef
};
const validateReceiver = async () => {
let lastRef = await getLastRef();
let myTransaction = await makeTransactionRequest(lastRef)
const res = getTxnRequestResponse(myTransaction)
return res
}
const makeTransactionRequest = async (lastRef) => {
let groupdialog1 = get("transactions.groupdialog1")
let groupdialog2 = get("transactions.groupdialog2")
let myTxnrequest = await parentEpml.request('transaction', {
type: 31,
nonce: this.selectedAddress.nonce,
params: {
fee: joinFeeInput,
registrantAddress: this.selectedAddress.address,
rGroupName: groupName,
rGroupId: groupId,
lastReference: lastRef,
groupdialog1: groupdialog1,
groupdialog2: groupdialog2
}
})
return myTxnrequest
}
const getTxnRequestResponse = (txnResponse) => {
if (txnResponse.success === false && txnResponse.message) {
throw new Error(txnResponse.message)
} else if (txnResponse.success === true && !txnResponse.data.error) {
return txnResponse.data
} else if (txnResponse.data && txnResponse.data.message) {
throw new Error(txnResponse.data.message)
} else {
throw new Error('Server error. Could not perform action.')
}
}
const groupRes = await validateReceiver()
return groupRes
}
async _deployAt(name, description, tags, creationBytes, amount, assetId, fee, atType) {
const deployAtFee = await this.deployAtFee()
const getLastRef = async () => {
let myRef = await parentEpml.request('apiCall', {
type: 'api',
url: `/addresses/lastreference/${this.selectedAddress.address}`
})
return myRef
};
const validateReceiver = async () => {
let lastRef = await getLastRef();
let myTransaction = await makeTransactionRequest(lastRef)
const res = getTxnRequestResponse(myTransaction)
return res
}
const makeTransactionRequest = async (lastRef) => {
let groupdialog1 = get("transactions.groupdialog1")
let groupdialog2 = get("transactions.groupdialog2")
let myTxnrequest = await parentEpml.request('transaction', {
type: 16,
nonce: this.selectedAddress.nonce,
params: {
fee: fee || deployAtFee,
rName: name,
rDescription: description,
rTags: tags,
rAmount: amount,
rAssetId: assetId,
rCreationBytes: creationBytes,
atType: atType,
lastReference: lastRef,
atDeployDialog1: groupdialog1,
atDeployDialog2: groupdialog2
}
})
return myTxnrequest
}
const getTxnRequestResponse = (txnResponse) => {
if (txnResponse.success === false && txnResponse.message) {
throw new Error(txnResponse.message)
} else if (txnResponse.success === true && !txnResponse.data.error) {
return txnResponse.data
} else if (txnResponse.data && txnResponse.data.message) {
throw new Error(txnResponse.data.message)
} else {
throw new Error('Server error. Could not perform action.')
}
}
const groupRes = await validateReceiver()
return groupRes
}
firstUpdated() { firstUpdated() {
this.changeTheme(); this.changeTheme();
this.changeLanguage(); this.changeLanguage();
@ -320,9 +450,9 @@ class WebBrowser extends LitElement {
let data = event.data; let data = event.data;
console.log('UI received event: ' + JSON.stringify(data)); console.log('UI received event: ' + JSON.stringify(data));
switch (data.action) { switch (data.action) {
case 'GET_USER_ACCOUNT': case 'GET_USER_ACCOUNT':
case actions.GET_USER_ACCOUNT: case actions.GET_USER_ACCOUNT:
const res1 = await showModalAndWait( const res1 = await showModalAndWait(
actions.GET_USER_ACCOUNT actions.GET_USER_ACCOUNT
); );
@ -338,7 +468,7 @@ class WebBrowser extends LitElement {
const errorMsg = get('browserpage.bchange17'); const errorMsg = get('browserpage.bchange17');
data['error'] = errorMsg; data['error'] = errorMsg;
response = JSON.stringify(data); response = JSON.stringify(data);
return; break;
} }
case 'LINK_TO_QDN_RESOURCE': case 'LINK_TO_QDN_RESOURCE':
case actions.QDN_RESOURCE_DISPLAYED: case actions.QDN_RESOURCE_DISPLAYED:
@ -363,16 +493,29 @@ class WebBrowser extends LitElement {
this.displayUrl = url; this.displayUrl = url;
return; return;
case actions.PUBLISH_QDN_RESOURCE: case actions.PUBLISH_QDN_RESOURCE: {
const requiredFields = ['service', 'name', 'data64'];
const missingFields = [];
requiredFields.forEach((field) => {
if (!data[field]) {
missingFields.push(field);
}
});
if (missingFields.length > 0) {
const missingFieldsString = missingFields.join(', ');
const errorMsg = `Missing fields: ${missingFieldsString}`
let data = {};
data['error'] = errorMsg;
response = JSON.stringify(data);
break
}
// Use "default" if user hasn't specified an identifer // Use "default" if user hasn't specified an identifer
const service = data.service; const service = data.service;
const name = data.name; const name = data.name;
let identifier = data.identifier; let identifier = data.identifier;
const data64 = data.data64; const data64 = data.data64;
if (!service || !name || !data64) {
return;
}
if (data.identifier == null) { if (data.identifier == null) {
identifier = 'default'; identifier = 'default';
} }
@ -394,17 +537,16 @@ class WebBrowser extends LitElement {
worker: worker, worker: worker,
isBase64: true, isBase64: true,
}); });
let data = {};
data['data'] = resPublish; response = JSON.stringify(resPublish);
response = JSON.stringify(data);
worker.terminate(); worker.terminate();
} catch (error) { } catch (error) {
worker.terminate(); worker.terminate();
const data = {}; const obj = {};
const errorMsg = error.message || 'Upload failed'; const errorMsg = error.message || 'Upload failed';
data['error'] = errorMsg; obj['error'] = errorMsg;
response = JSON.stringify(data); response = JSON.stringify(obj);
console.error(error); console.error(error);
return; return;
} finally { } finally {
this.loader.hide(); this.loader.hide();
@ -417,6 +559,8 @@ class WebBrowser extends LitElement {
// then set the response string from the core to the `response` variable (defined above) // then set the response string from the core to the `response` variable (defined above)
// If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}` // If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}`
break; break;
}
case 'SEND_CHAT_MESSAGE': case 'SEND_CHAT_MESSAGE':
// Params: data.groupId, data.destinationAddress, data.message // Params: data.groupId, data.destinationAddress, data.message
@ -425,11 +569,60 @@ class WebBrowser extends LitElement {
// If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}` // If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}`
break; break;
case actions.JOIN_GROUP: case actions.JOIN_GROUP: {
const requiredFields = ['groupId'];
const missingFields = [];
requiredFields.forEach((field) => {
if (!data[field]) {
missingFields.push(field);
}
});
if (missingFields.length > 0) {
const missingFieldsString = missingFields.join(', ');
const errorMsg = `Missing fields: ${missingFieldsString}`
let data = {};
data['error'] = errorMsg;
response = JSON.stringify(data);
break
}
const groupId = data.groupId; const groupId = data.groupId;
if (!groupId) {
return; let groupInfo = null
try {
groupInfo = await parentEpml.request("apiCall", {
type: "api",
url: `/groups/${groupId}`,
});
} catch (error) {
const errorMsg = (error && error.message) || 'Group not found';
let obj = {};
obj['error'] = errorMsg;
response = JSON.stringify(obj);
break
}
if (!groupInfo || groupInfo.error) {
const errorMsg = (groupInfo && groupInfo.message) || 'Group not found';
let obj = {};
obj['error'] = errorMsg;
response = JSON.stringify(obj);
break
}
try {
this.loader.show();
const resJoinGroup = await this._joinGroup(groupId, groupInfo.groupName)
response = JSON.stringify(resJoinGroup);
} catch (error) {
const obj = {};
const errorMsg = error.message || 'Failed to join the group.';
obj['error'] = errorMsg;
response = JSON.stringify(obj);
} finally {
this.loader.hide();
} }
// Params: data.groupId // Params: data.groupId
@ -437,99 +630,132 @@ class WebBrowser extends LitElement {
// then set the response string from the core to the `response` variable (defined above) // then set the response string from the core to the `response` variable (defined above)
// If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}` // If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}`
break; break;
}
case 'DEPLOY_AT': case 'DEPLOY_AT': {
const requiredFields = ['name', 'description', 'tags', 'creationBytes', 'amount', 'assetId', 'type'];
const missingFields = [];
requiredFields.forEach((field) => {
if (!data[field]) {
missingFields.push(field);
}
});
if (missingFields.length > 0) {
const missingFieldsString = missingFields.join(', ');
const errorMsg = `Missing fields: ${missingFieldsString}`
let data = {};
data['error'] = errorMsg;
response = JSON.stringify(data);
break
}
try {
this.loader.show();
const fee = data.fee || undefined
const resJoinGroup = await this._deployAt(data.name, data.description, data.tags, data.creationBytes, data.amount, data.assetId, fee, data.type)
response = JSON.stringify(resJoinGroup);
} catch (error) {
const obj = {};
const errorMsg = error.message || 'Failed to join the group.';
obj['error'] = errorMsg;
response = JSON.stringify(obj);
} finally {
this.loader.hide();
}
// Params: data.creationBytes, data.name, data.description, data.type, data.tags, data.amount, data.assetId, data.fee // Params: data.creationBytes, data.name, data.description, data.type, data.tags, data.amount, data.assetId, data.fee
// TODO: prompt user to deploy an AT. If they confirm, sign+process a DEPLOY_AT transaction // TODO: prompt user to deploy an AT. If they confirm, sign+process a DEPLOY_AT transaction
// then set the response string from the core to the `response` variable (defined above) // then set the response string from the core to the `response` variable (defined above)
// If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}` // If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}`
break; break;
}
case 'GET_WALLET_BALANCE': case 'GET_WALLET_BALANCE':
// Params: data.coin (QORT / LTC / DOGE / DGB / C / ARRR) // Params: data.coin (QORT / LTC / DOGE / DGB / C / ARRR)
// TODO: prompt user to share wallet balance. If they confirm, call `GET /crosschain/:coin/walletbalance`, or for QORT, call `GET /addresses/balance/:address` // TODO: prompt user to share wallet balance. If they confirm, call `GET /crosschain/:coin/walletbalance`, or for QORT, call `GET /addresses/balance/:address`
// then set the response string from the core to the `response` variable (defined above) // then set the response string from the core to the `response` variable (defined above)
// If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}` // If they decline, send back JSON that includes an `error` key, such as `{"error": "User declined request"}`
console.log('case passed here');
console.log(data.coin, "data coin here"); const res3 = await showModalAndWait(
const res3 = await showModalAndWait(
actions.GET_WALLET_BALANCE actions.GET_WALLET_BALANCE
); );
if (res3.action === 'accept') { if (res3.action === 'accept') {
let coin = data.coin; let coin = data.coin;
if (coin === "QORT") { if (coin === "QORT") {
let qortAddress = window.parent.reduxStore.getState().app.selectedAddress.address let qortAddress = window.parent.reduxStore.getState().app.selectedAddress.address
try { try {
this.loader.show(); this.loader.show();
const QORTBalance = await parentEpml.request('apiCall', { const QORTBalance = await parentEpml.request('apiCall', {
url: `/addresses/balance/${qortAddress}?apiKey=${this.getApiKey()}`, url: `/addresses/balance/${qortAddress}?apiKey=${this.getApiKey()}`,
}) })
console.log({QORTBalance}) return QORTBalance;
return QORTBalance; } catch (error) {
} catch (error) { console.error(error);
console.error(error); const data = {};
const data = {}; const errorMsg = error.message || get("browserpage.bchange21");
const errorMsg = error.message || get("browserpage.bchange21"); data['error'] = errorMsg;
data['error'] = errorMsg; response = JSON.stringify(data);
response = JSON.stringify(data); return;
return; } finally {
} finally { this.loader.hide();
this.loader.hide(); }
} } else {
} else { let _url = ``
let _url = `` let _body = null
let _body = null
switch (coin) { switch (coin) {
case 'LTC': case 'LTC':
_url = `/crosschain/ltc/walletbalance?apiKey=${this.getApiKey()}` _url = `/crosschain/ltc/walletbalance?apiKey=${this.getApiKey()}`
_body = window.parent.reduxStore.getState().app.selectedAddress.ltcWallet.derivedMasterPublicKey _body = window.parent.reduxStore.getState().app.selectedAddress.ltcWallet.derivedMasterPublicKey
break break
case 'DOGE': case 'DOGE':
_url = `/crosschain/doge/walletbalance?apiKey=${this.getApiKey()}` _url = `/crosschain/doge/walletbalance?apiKey=${this.getApiKey()}`
_body = window.parent.reduxStore.getState().app.selectedAddress.dogeWallet.derivedMasterPublicKey _body = window.parent.reduxStore.getState().app.selectedAddress.dogeWallet.derivedMasterPublicKey
break break
case 'DGB': case 'DGB':
_url = `/crosschain/dgb/walletbalance?apiKey=${this.getApiKey()}` _url = `/crosschain/dgb/walletbalance?apiKey=${this.getApiKey()}`
_body = window.parent.reduxStore.getState().app.selectedAddress.dgbWallet.derivedMasterPublicKey _body = window.parent.reduxStore.getState().app.selectedAddress.dgbWallet.derivedMasterPublicKey
break break
case 'RVN': case 'RVN':
_url = `/crosschain/rvn/walletbalance?apiKey=${this.getApiKey()}` _url = `/crosschain/rvn/walletbalance?apiKey=${this.getApiKey()}`
_body = window.parent.reduxStore.getState().app.selectedAddress.rvnWallet.derivedMasterPublicKey _body = window.parent.reduxStore.getState().app.selectedAddress.rvnWallet.derivedMasterPublicKey
break break
case 'ARRR': case 'ARRR':
_url = `/crosschain/arrr/walletbalance?apiKey=${this.getApiKey()}` _url = `/crosschain/arrr/walletbalance?apiKey=${this.getApiKey()}`
_body = window.parent.reduxStore.getState().app.selectedAddress.arrrWallet.seed58 _body = window.parent.reduxStore.getState().app.selectedAddress.arrrWallet.seed58
break break
default: default:
break break
} }
try { try {
this.loader.show() this.loader.show()
await parentEpml.request('apiCall', { await parentEpml.request('apiCall', {
url: _url, url: _url,
method: 'POST', method: 'POST',
body: _body, body: _body,
}).then((res) => { }).then((res) => {
if (isNaN(Number(res))) { if (isNaN(Number(res))) {
throw new Error(get("browserpage.bchange21")); throw new Error(get("browserpage.bchange21"));
} else { } else {
console.log((Number(res) / 1e8).toFixed(8), "other wallet balance here"); console.log((Number(res) / 1e8).toFixed(8), "other wallet balance here");
return (Number(res) / 1e8).toFixed(8) return (Number(res) / 1e8).toFixed(8)
} }
}) })
} catch (error) { } catch (error) {
console.error(error); console.error(error);
const data = {}; const data = {};
const errorMsg = error.message || get("browserpage.bchange21"); const errorMsg = error.message || get("browserpage.bchange21");
data['error'] = errorMsg; data['error'] = errorMsg;
response = JSON.stringify(data); response = JSON.stringify(data);
return; return;
} finally { } finally {
this.loader.hide() this.loader.hide()
} }
} }
} else if (res3.action === 'reject') { } else if (res3.action === 'reject') {
response = '{"error": "User declined request"}'; response = '{"error": "User declined request"}';
} }
break; break;
@ -554,14 +780,16 @@ class WebBrowser extends LitElement {
// Not all responses will be JSON // Not all responses will be JSON
responseObj = response; responseObj = response;
} }
console.log({ responseObj })
// Respond to app // Respond to app
if (responseObj.error != null) { if (responseObj.error != null) {
console.log('hello error')
event.ports[0].postMessage({ event.ports[0].postMessage({
result: null, result: null,
error: responseObj, error: responseObj,
}); });
} else { } else {
console.log('hello success')
event.ports[0].postMessage({ event.ports[0].postMessage({
result: responseObj, result: responseObj,
error: null, error: null,
@ -654,15 +882,13 @@ class WebBrowser extends LitElement {
refresh() { refresh() {
const myNode = const myNode =
window.parent.reduxStore.getState().app.nodeConfig.knownNodes[ window.parent.reduxStore.getState().app.nodeConfig.knownNodes[
window.parent.reduxStore.getState().app.nodeConfig.node window.parent.reduxStore.getState().app.nodeConfig.node
]; ];
const nodeUrl = const nodeUrl =
myNode.protocol + '://' + myNode.domain + ':' + myNode.port; myNode.protocol + '://' + myNode.domain + ':' + myNode.port;
this.url = `${nodeUrl}/render/${this.service}/${this.name}${ this.url = `${nodeUrl}/render/${this.service}/${this.name}${this.path != null ? this.path : ''
this.path != null ? this.path : '' }?theme=${this.theme}&identifier=${this.identifier != null ? this.identifier : ''
}?theme=${this.theme}&identifier=${ }`;
this.identifier != null ? this.identifier : ''
}`;
} }
goBackToList() { goBackToList() {
@ -811,9 +1037,8 @@ class WebBrowser extends LitElement {
this.identifier == null ? 'default' : resource.identifier; this.identifier == null ? 'default' : resource.identifier;
let ret = await parentEpml.request('apiCall', { let ret = await parentEpml.request('apiCall', {
url: `/arbitrary/resource/${this.service}/${ url: `/arbitrary/resource/${this.service}/${this.name
this.name }/${identifier}?apiKey=${this.getApiKey()}`,
}/${identifier}?apiKey=${this.getApiKey()}`,
method: 'DELETE', method: 'DELETE',
}); });
@ -864,7 +1089,7 @@ class WebBrowser extends LitElement {
getApiKey() { getApiKey() {
const myNode = const myNode =
window.parent.reduxStore.getState().app.nodeConfig.knownNodes[ window.parent.reduxStore.getState().app.nodeConfig.knownNodes[
window.parent.reduxStore.getState().app.nodeConfig.node window.parent.reduxStore.getState().app.nodeConfig.node
]; ];
let apiKey = myNode.apiKey; let apiKey = myNode.apiKey;
return apiKey; return apiKey;
@ -883,10 +1108,10 @@ async function showModalAndWait(type, data) {
return new Promise((resolve) => { return new Promise((resolve) => {
// Create the modal and add it to the DOM // Create the modal and add it to the DOM
const modal = document.createElement('div'); const modal = document.createElement('div');
modal.id = "backdrop" modal.id = "backdrop"
modal.classList.add("backdrop"); modal.classList.add("backdrop");
modal.innerHTML = modal.innerHTML =
` <div class="modal my-modal-class"> ` <div class="modal my-modal-class">
<div class="modal-content"> <div class="modal-content">
<div class="modal-body"> <div class="modal-body">
${type === actions.GET_USER_ACCOUNT ? `<p class="modal-paragraph">${get("browserpage.bchange18")}</p>` : ''} ${type === actions.GET_USER_ACCOUNT ? `<p class="modal-paragraph">${get("browserpage.bchange18")}</p>` : ''}
@ -900,30 +1125,30 @@ async function showModalAndWait(type, data) {
</div> </div>
</div> </div>
`; `;
document.body.appendChild(modal); document.body.appendChild(modal);
// Add click event listeners to the buttons // Add click event listeners to the buttons
const okButton = modal.querySelector('#ok-button'); const okButton = modal.querySelector('#ok-button');
okButton.addEventListener('click', () => { okButton.addEventListener('click', () => {
const userData = {}; const userData = {};
if (modal.parentNode === document.body) { if (modal.parentNode === document.body) {
document.body.removeChild(modal); document.body.removeChild(modal);
} }
resolve({ action: 'accept', userData }); resolve({ action: 'accept', userData });
}); });
const backdropClick = document.getElementById('backdrop'); const backdropClick = document.getElementById('backdrop');
backdropClick.addEventListener('click', () => { backdropClick.addEventListener('click', () => {
if (modal.parentNode === document.body) { if (modal.parentNode === document.body) {
document.body.removeChild(modal); document.body.removeChild(modal);
} }
resolve({ action: 'reject' }); resolve({ action: 'reject' });
}); });
const cancelButton = modal.querySelector('#cancel-button'); const cancelButton = modal.querySelector('#cancel-button');
cancelButton.addEventListener('click', () => { cancelButton.addEventListener('click', () => {
if (modal.parentNode === document.body) { if (modal.parentNode === document.body) {
document.body.removeChild(modal); document.body.removeChild(modal);
} }
resolve({ action: 'reject' }); resolve({ action: 'reject' });
}); });
}); });
} }

View File

@ -148,7 +148,8 @@ export const publishData = async ({
} }
} }
try { try {
await validate() const validateRes = await validate()
return validateRes
} catch (error) { } catch (error) {
throw new Error(error.message) throw new Error(error.message)
} }