testing speed

This commit is contained in:
Phillip 2023-08-09 23:52:26 +03:00
parent 774393312f
commit 9705febe65
6 changed files with 399 additions and 431 deletions

View File

@ -9,29 +9,29 @@ import '@material/mwc-dialog'
const parentEpml = new Epml({ type: 'WINDOW', source: window.parent })
class ChatModals extends LitElement {
static get properties() {
return {
openDialogPrivateMessage: {type: Boolean},
openDialogBlockUser: {type: Boolean},
isLoading: { type: Boolean },
nametodialog: { type: String, attribute: true },
hidePrivateMessageModal: {type: Function},
hideBlockUserModal: {type: Function},
toblockaddress: { type: String, attribute: true },
chatBlockedAdresses: { type: Array }
static get properties() {
return {
openDialogPrivateMessage: { type: Boolean },
openDialogBlockUser: { type: Boolean },
isLoading: { type: Boolean },
nametodialog: { type: String, attribute: true },
hidePrivateMessageModal: { type: Function },
hideBlockUserModal: { type: Function },
toblockaddress: { type: String, attribute: true },
chatBlockedAdresses: { type: Array }
}
}
}
constructor() {
super()
this.isLoading = false
this.hidePrivateMessageModal = () => {}
this.hideBlockUserModal = () => {}
this.chatBlockedAdresses = []
}
constructor() {
super()
this.isLoading = false
this.hidePrivateMessageModal = () => { }
this.hideBlockUserModal = () => { }
this.chatBlockedAdresses = []
}
static get styles() {
return css`
static get styles() {
return css`
.input {
width: 90%;
border: none;
@ -60,52 +60,48 @@ class ChatModals extends LitElement {
--mdc-theme-primary: red;
}
`
}
firstUpdated() {
const stopKeyEventPropagation = (e) => {
e.stopPropagation();
return false;
}
this.shadowRoot.getElementById('sendTo').addEventListener('keydown', stopKeyEventPropagation);
this.shadowRoot.getElementById('messageBox').addEventListener('keydown', stopKeyEventPropagation);
firstUpdated() {
const stopKeyEventPropagation = (e) => {
e.stopPropagation();
return false;
}
this.shadowRoot.getElementById('sendTo').addEventListener('keydown', stopKeyEventPropagation);
this.shadowRoot.getElementById('messageBox').addEventListener('keydown', stopKeyEventPropagation);
parentEpml.ready().then(() => {
parentEpml.subscribe('selected_address', async selectedAddress => {
this.selectedAddress = {}
selectedAddress = JSON.parse(selectedAddress)
if (!selectedAddress || Object.entries(selectedAddress).length === 0) return
this.selectedAddress = selectedAddress
})
parentEpml.ready().then(() => {
parentEpml.subscribe('selected_address', async selectedAddress => {
this.selectedAddress = {}
selectedAddress = JSON.parse(selectedAddress)
if (!selectedAddress || Object.entries(selectedAddress).length === 0) return
this.selectedAddress = selectedAddress
})
parentEpml.request('apiCall', {
url: `/addresses/balance/${window.parent.reduxStore.getState().app.selectedAddress.address}`
}).then(res => {
this.balance = res
})
})
parentEpml.imReady()
parentEpml.imReady()
}
// Send Private Message
// Send Private Message
_sendMessage() {
this.isLoading = true;
_sendMessage() {
this.isLoading = true;
const recipient = this.shadowRoot.getElementById('sendTo').value;
const messageBox = this.shadowRoot.getElementById('messageBox');
const messageText = messageBox.value;
const recipient = this.shadowRoot.getElementById('sendTo').value;
const messageBox = this.shadowRoot.getElementById('messageBox');
const messageText = messageBox.value;
if (recipient.length === 0) {
this.isLoading = false
} else if (messageText.length === 0) {
this.isLoading = false
} else {
this.sendMessage()
if (recipient.length === 0) {
this.isLoading = false
} else if (messageText.length === 0) {
this.isLoading = false
} else {
this.sendMessage()
}
}
}
async sendMessage() {
this.isLoading = true
@ -172,77 +168,77 @@ class ChatModals extends LitElement {
}
};
const sendMessageRequest = async (isEncrypted, _publicKey) => {
const messageObject = {
messageText,
images: [''],
repliedTo: '',
version: 1
}
const stringifyMessageObject = JSON.stringify(messageObject)
let chatResponse = await parentEpml.request('chat', {
type: 18,
nonce: this.selectedAddress.nonce,
params: {
timestamp: sendTimestamp,
recipient: recipient,
recipientPublicKey: _publicKey,
hasChatReference: 0,
message: stringifyMessageObject,
lastReference: reference,
proofOfWorkNonce: 0,
isEncrypted: isEncrypted,
isText: 1
const sendMessageRequest = async (isEncrypted, _publicKey) => {
const messageObject = {
messageText,
images: [''],
repliedTo: '',
version: 1
}
})
_computePow(chatResponse)
}
const stringifyMessageObject = JSON.stringify(messageObject)
let chatResponse = await parentEpml.request('chat', {
type: 18,
nonce: this.selectedAddress.nonce,
params: {
timestamp: sendTimestamp,
recipient: recipient,
recipientPublicKey: _publicKey,
hasChatReference: 0,
message: stringifyMessageObject,
lastReference: reference,
proofOfWorkNonce: 0,
isEncrypted: isEncrypted,
isText: 1
}
})
_computePow(chatResponse)
}
const _computePow = async (chatBytes) => {
const _computePow = async (chatBytes) => {
const _chatBytesArray = Object.keys(chatBytes).map(function (key) { return chatBytes[key]; })
const chatBytesArray = new Uint8Array(_chatBytesArray)
const chatBytesHash = new window.parent.Sha256().process(chatBytesArray).finish().result
const hashPtr = window.parent.sbrk(32, window.parent.heap)
const hashAry = new Uint8Array(window.parent.memory.buffer, hashPtr, 32)
hashAry.set(chatBytesHash)
const _chatBytesArray = Object.keys(chatBytes).map(function (key) { return chatBytes[key]; })
const chatBytesArray = new Uint8Array(_chatBytesArray)
const chatBytesHash = new window.parent.Sha256().process(chatBytesArray).finish().result
const hashPtr = window.parent.sbrk(32, window.parent.heap)
const hashAry = new Uint8Array(window.parent.memory.buffer, hashPtr, 32)
hashAry.set(chatBytesHash)
const difficulty = this.balance < 4 ? 18 : 8
const difficulty = this.balance < 4 ? 18 : 8
const workBufferLength = 8 * 1024 * 1024;
const workBufferPtr = window.parent.sbrk(workBufferLength, window.parent.heap)
const workBufferLength = 8 * 1024 * 1024;
const workBufferPtr = window.parent.sbrk(workBufferLength, window.parent.heap)
let nonce = window.parent.computePow(hashPtr, workBufferPtr, workBufferLength, difficulty)
let nonce = window.parent.computePow(hashPtr, workBufferPtr, workBufferLength, difficulty)
let _response = await parentEpml.request('sign_chat', {
nonce: this.selectedAddress.nonce,
chatBytesArray: chatBytesArray,
chatNonce: nonce
})
getSendChatResponse(_response)
}
let _response = await parentEpml.request('sign_chat', {
nonce: this.selectedAddress.nonce,
chatBytesArray: chatBytesArray,
chatNonce: nonce
})
getSendChatResponse(_response)
}
const getSendChatResponse = (response) => {
const getSendChatResponse = (response) => {
if (response === true) {
messageBox.value = ''
let err2string = get('welcomepage.wcchange8')
parentEpml.request('showSnackBar', `${err2string}`)
this.isLoading = false
this.shadowRoot.querySelector('#startPmDialog').close()
} else if (response.error) {
parentEpml.request('showSnackBar', response.message)
this.isLoading = false
this.shadowRoot.querySelector('#startPmDialog').close()
} else {
let err3string = get('welcomepage.wcchange9')
parentEpml.request('showSnackBar', `${err3string}`)
this.isLoading = false
this.shadowRoot.querySelector('#startPmDialog').close()
}
if (response === true) {
messageBox.value = ''
let err2string = get('welcomepage.wcchange8')
parentEpml.request('showSnackBar', `${err2string}`)
this.isLoading = false
this.shadowRoot.querySelector('#startPmDialog').close()
} else if (response.error) {
parentEpml.request('showSnackBar', response.message)
this.isLoading = false
this.shadowRoot.querySelector('#startPmDialog').close()
} else {
let err3string = get('welcomepage.wcchange9')
parentEpml.request('showSnackBar', `${err3string}`)
this.isLoading = false
this.shadowRoot.querySelector('#startPmDialog').close()
}
}
getAddressPublicKey()
}
getAddressPublicKey()
}
_textArea(e) {
@ -276,8 +272,8 @@ class ChatModals extends LitElement {
fetch(`${nodeUrl}/names/address/${item}?limit=0&reverse=true`).then(res => {
return res.json()
}).then(jsonRes => {
if(jsonRes.length) {
jsonRes.map (item => {
if (jsonRes.length) {
jsonRes.map(item => {
obj.push(item)
})
} else {
@ -291,7 +287,7 @@ class ChatModals extends LitElement {
relMessages() {
setTimeout(() => {
window.location.href = window.location.href.split( '#' )[0]
window.location.href = window.location.href.split('#')[0]
}, 500)
}
@ -345,8 +341,8 @@ class ChatModals extends LitElement {
return ret
}
render() {
return html`
render() {
return html`
<mwc-dialog
id='sendPMDialog'
tabindex='0'
@ -366,9 +362,9 @@ class ChatModals extends LitElement {
<textarea class='textarea' @keydown=${(e) => this._textArea(e)} ?disabled=${this.isLoading} id='messageBox' placeholder='${translate('welcomepage.wcchange5')}' rows='1'></textarea>
</p>
<mwc-button ?disabled='${this.isLoading}' slot='primaryAction' @click=${() => {
this._sendMessage();
}
}>${translate('welcomepage.wcchange6')}
this._sendMessage();
}
}>${translate('welcomepage.wcchange6')}
</mwc-button>
<mwc-button
?disabled='${this.isLoading}'
@ -409,7 +405,7 @@ class ChatModals extends LitElement {
</mwc-button>
</mwc-dialog>
`;
}
}
}
customElements.define('chat-modals', ChatModals)

View File

@ -118,7 +118,7 @@ class ChatPage extends LitElement {
}
static get styles() {
return css`
return css`
html {
scroll-behavior: smooth;
}
@ -1443,14 +1443,7 @@ class ChatPage extends LitElement {
` : ''}
<div class="chat-text-area" style="${`${(this.repliedToMessageObj || this.editedMessageObj) && "min-height: 120px"}`}">
<!-- gif div -->
<chat-gifs
class="chat-gifs"
style=${this.openGifModal ? "display: flex;" : "display: none;"}
.webWorkerImage=${this.webWorkerFile}
.setGifsLoading=${(val) => this.setGifsLoading(val)}
.sendMessage=${(val) => this._sendMessage(val)}
.setOpenGifModal=${(val) => this.setOpenGifModal(val)}>
</chat-gifs>
<div
class='last-message-ref'
style=${(this.lastMessageRefVisible && !this.imageFile && !this.openGifModal) ? 'opacity: 1;' : 'opacity: 0;'}>
@ -1600,18 +1593,18 @@ class ChatPage extends LitElement {
</div>
<div class="modal-button-row">
<button class="modal-button-red" @click=${() => {
this.removeImage()
}}>
this.removeImage()
}}>
${translate("chatpage.cchange33")}
</button>
<button
class="modal-button"
@click=${() => {
const chatTextEditor = this.shadowRoot.getElementById('chatTextCaption')
chatTextEditor.sendMessageFunc({
type: 'image',
})
}}
const chatTextEditor = this.shadowRoot.getElementById('chatTextCaption')
chatTextEditor.sendMessageFunc({
type: 'image',
})
}}
>
${translate("chatpage.cchange9")}
</button>
@ -1652,18 +1645,18 @@ class ChatPage extends LitElement {
</div>
<div class="modal-button-row">
<button class="modal-button-red" @click=${() => {
this.removeAttachment()
}}>
this.removeAttachment()
}}>
${translate("chatpage.cchange33")}
</button>
<button
class="modal-button"
@click=${() => {
const chatTextEditor = this.shadowRoot.getElementById('chatAttachmentId')
chatTextEditor.sendMessageFunc({
type: 'attachment',
})
}}
const chatTextEditor = this.shadowRoot.getElementById('chatAttachmentId')
chatTextEditor.sendMessageFunc({
type: 'attachment',
})
}}
>
${translate("chatpage.cchange9")}
</button>
@ -2398,11 +2391,7 @@ class ChatPage extends LitElement {
if (!selectedAddress || Object.entries(selectedAddress).length === 0) return
this.selectedAddress = selectedAddress
})
parentEpml.request('apiCall', {
url: `/addresses/balance/${window.parent.reduxStore.getState().app.selectedAddress.address}`
}).then(res => {
this.balance = res
})
})
parentEpml.imReady()
@ -2559,15 +2548,15 @@ class ChatPage extends LitElement {
return this.decodeMessage(eachMessage)
})
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodeMsgs,
parentEpml,
isReceipient: this.isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodeMsgs,
// parentEpml,
// isReceipient: this.isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey
// })
this.messagesRendered = [...replacedMessages, ...this.messagesRendered].sort(function (a, b) {
this.messagesRendered = [...decodeMsgs, ...this.messagesRendered].sort(function (a, b) {
return a.timestamp
- b.timestamp
})
@ -2589,15 +2578,15 @@ class ChatPage extends LitElement {
return this.decodeMessage(eachMessage)
})
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodeMsgs,
parentEpml,
isReceipient: this.isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodeMsgs,
// parentEpml,
// isReceipient: this.isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey
// })
this.messagesRendered = [...replacedMessages, ...this.messagesRendered].sort(function (a, b) {
this.messagesRendered = [...decodeMsgs, ...this.messagesRendered].sort(function (a, b) {
return a.timestamp
- b.timestamp
})
@ -2623,15 +2612,15 @@ class ChatPage extends LitElement {
return this.decodeMessage(eachMessage)
})
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodeMsgs,
parentEpml,
isReceipient: this.isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodeMsgs,
// parentEpml,
// isReceipient: this.isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey
// })
this.messagesRendered = [...replacedMessages, ...this.messagesRendered].sort(function (a, b) {
this.messagesRendered = [...decodeMsgs, ...this.messagesRendered].sort(function (a, b) {
return a.timestamp
- b.timestamp
})
@ -2655,15 +2644,15 @@ class ChatPage extends LitElement {
return this.decodeMessage(eachMessage)
})
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodeMsgs,
parentEpml,
isReceipient: this.isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodeMsgs,
// parentEpml,
// isReceipient: this.isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey
// })
this.messagesRendered = [...replacedMessages, ...this.messagesRendered].sort(function (a, b) {
this.messagesRendered = [...decodeMsgs, ...this.messagesRendered].sort(function (a, b) {
return a.timestamp
- b.timestamp
})
@ -2690,15 +2679,15 @@ class ChatPage extends LitElement {
return this.decodeMessage(eachMessage)
})
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodeMsgs,
parentEpml,
isReceipient: this.isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodeMsgs,
// parentEpml,
// isReceipient: this.isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey
// })
this.messagesRendered = [...this.messagesRendered, ...replacedMessages].sort(function (a, b) {
this.messagesRendered = [...this.messagesRendered, ...decodeMsgs].sort(function (a, b) {
return a.timestamp
- b.timestamp
})
@ -2722,15 +2711,15 @@ class ChatPage extends LitElement {
return this.decodeMessage(eachMessage)
})
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodeMsgs,
parentEpml,
isReceipient: this.isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodeMsgs,
// parentEpml,
// isReceipient: this.isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey
// })
this.messagesRendered = [...this.messagesRendered, ...replacedMessages].sort(function (a, b) {
this.messagesRendered = [...this.messagesRendered, ...decodeMsgs].sort(function (a, b) {
return a.timestamp
- b.timestamp
})
@ -2762,35 +2751,36 @@ class ChatPage extends LitElement {
})
if (isInitial) {
this.chatEditorPlaceholder = await this.renderPlaceholder()
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodedMessages,
parentEpml,
isReceipient: isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodedMessages,
// parentEpml,
// isReceipient: isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey
// })
this._messages = replacedMessages.sort(function (a, b) {
this._messages = decodedMessages.sort(function (a, b) {
return a.timestamp
- b.timestamp
})
// TODO: Determine number of initial messages by screen height...
// this.messagesRendered = this._messages
this.messagesRendered = this._messages
this.isLoadingMessages = false
setTimeout(() => this.downElementObserver(), 500)
} else {
const replacedMessages = await replaceMessagesEdited({
decodedMessages: decodedMessages,
parentEpml,
isReceipient: isReceipient,
decodeMessageFunc: this.decodeMessage,
_publicKey: this._publicKey,
isNotInitial: true
})
// const replacedMessages = await replaceMessagesEdited({
// decodedMessages: decodedMessages,
// parentEpml,
// isReceipient: isReceipient,
// decodeMessageFunc: this.decodeMessage,
// _publicKey: this._publicKey,
// isNotInitial: true
// })
const renderEachMessage = replacedMessages.map(async (msg) => {
const renderEachMessage = decodedMessages.map(async (msg) => {
await this.renderNewMessage(msg)
})

View File

@ -217,9 +217,9 @@ class ChatWelcomePage extends LitElement {
<div
class="start-chat"
@click="${() => this.setOpenPrivateMessage({
name: "",
open: true
})}">
name: "",
open: true
})}">
${translate("welcomepage.wcchange2")}
</div>
</div>
@ -240,9 +240,9 @@ class ChatWelcomePage extends LitElement {
</p>
<mwc-button ?disabled="${this.isLoading}" slot="primaryAction" @click=${() => {
this._sendMessage();
}
}>
this._sendMessage();
}
}>
${translate("welcomepage.wcchange6")}</mwc-button>
<mwc-button
?disabled="${this.isLoading}"
@ -304,11 +304,7 @@ class ChatWelcomePage extends LitElement {
if (!selectedAddress || Object.entries(selectedAddress).length === 0) return
this.selectedAddress = selectedAddress
})
parentEpml.request('apiCall', {
url: `/addresses/balance/${window.parent.reduxStore.getState().app.selectedAddress.address}`
}).then(res => {
this.balance = res
})
})
parentEpml.imReady()

View File

@ -101,7 +101,7 @@ class LevelFounder extends LitElement {
}
firstUpdated() {
this.checkAddressInfo()
console.log('levelFounder')
parentEpml.ready().then(() => {
parentEpml.subscribe('selected_address', async selectedAddress => {
@ -115,28 +115,28 @@ class LevelFounder extends LitElement {
}
async checkAddressInfo() {
let toCheck = this.checkleveladdress
const memberInfo = await parentEpml.request('apiCall', {
url: `/addresses/${toCheck}`
})
this.memberInfo = memberInfo
// let toCheck = this.checkleveladdress
// const memberInfo = await parentEpml.request('apiCall', {
// url: `/addresses/${toCheck}`
// })
// this.memberInfo = memberInfo
}
renderFounder() {
let adressfounder = this.memberInfo.flags
if (adressfounder === 1) {
return html `
return html`
<span id="founderTooltip" class="badge">F</span>
<paper-tooltip class="custom" for="founderTooltip" position="top">FOUNDER</paper-tooltip>
`
} else {
return html ``
return html``
}
}
renderLevel() {
let adresslevel = this.memberInfo.level
return adresslevel ? html `
return adresslevel ? html`
<img id="level-img" src=${`/img/badges/level-${adresslevel}.png`} alt=${`badge-${adresslevel}`} class="message-data-level" />
<paper-tooltip class="level-img-tooltip" for="level-img" position="top" >
${translate("mintingpage.mchange27")} ${adresslevel}

View File

@ -228,9 +228,9 @@ class NameMenu extends LitElement {
<textarea class="textarea" @keydown=${(e) => this._textArea(e)} ?disabled=${this.isLoading} id="messageBox" placeholder="${translate("welcomepage.wcchange5")}" rows="1"></textarea>
</p>
<mwc-button ?disabled="${this.isLoading}" slot="primaryAction" @click=${() => {
this._sendMessage();
}
}>
this._sendMessage();
}
}>
${translate("welcomepage.wcchange6")}</mwc-button>
<mwc-button
?disabled="${this.isLoading}"
@ -247,11 +247,11 @@ class NameMenu extends LitElement {
firstUpdated() {
this.getChatBlockedAdresses()
setInterval(() => {
this.getChatBlockedAdresses()
}, 60000)
setInterval(() => {
this.getChatBlockedAdresses()
}, 60000)
window.onclick = function(event) {
window.onclick = function (event) {
if (!event.target.matches('.block')) {
var dropdowns = document.getElementsByClassName('dropdown-content');
var i;
@ -290,11 +290,7 @@ class NameMenu extends LitElement {
if (!selectedAddress || Object.entries(selectedAddress).length === 0) return
this.selectedAddress = selectedAddress
})
parentEpml.request('apiCall', {
url: `/addresses/balance/${window.parent.reduxStore.getState().app.selectedAddress.address}`
}).then(res => {
this.balance = res
})
})
parentEpml.imReady()
}
@ -333,7 +329,7 @@ class NameMenu extends LitElement {
relMessages() {
setTimeout(() => {
window.location.href = window.location.href.split( '#' )[0]
window.location.href = window.location.href.split('#')[0]
}, 500)
}
@ -407,8 +403,8 @@ class NameMenu extends LitElement {
fetch(`${nodeUrl}/names/address/${item}?limit=0&reverse=true`).then(res => {
return res.json()
}).then(jsonRes => {
if(jsonRes.length) {
jsonRes.map (item => {
if (jsonRes.length) {
jsonRes.map(item => {
obj.push(item)
})
} else {

View File

@ -9,21 +9,21 @@ import { use, get, translate, translateUnsafeHTML, registerTranslateConfig } fro
const parentEpml = new Epml({ type: "WINDOW", source: window.parent });
export class TipUser extends LitElement {
static get properties() {
return {
userName: { type: String },
walletBalance: { type: Number },
sendMoneyLoading: { type: Boolean },
closeTipUser: { type: Boolean },
btnDisable: { type: Boolean },
errorMessage: { type: String },
successMessage: { type: String },
setOpenTipUser: { attribute: false },
static get properties() {
return {
userName: { type: String },
walletBalance: { type: Number },
sendMoneyLoading: { type: Boolean },
closeTipUser: { type: Boolean },
btnDisable: { type: Boolean },
errorMessage: { type: String },
successMessage: { type: String },
setOpenTipUser: { attribute: false },
}
}
}
constructor() {
super()
constructor() {
super()
this.sendMoneyLoading = false
this.btnDisable = false
this.errorMessage = ""
@ -33,8 +33,8 @@ export class TipUser extends LitElement {
static styles = [tipUserStyles]
async firstUpdated() {
await this.fetchWalletDetails()
async firstUpdated() {
await this.fetchWalletDetails()
}
updated(changedProperties) {
@ -48,12 +48,12 @@ export class TipUser extends LitElement {
}
async getLastRef() {
let myRef = await parentEpml.request("apiCall", {
type: "api",
url: `/addresses/lastreference/${this.myAddress.address}`,
})
return myRef
}
let myRef = await parentEpml.request("apiCall", {
type: "api",
url: `/addresses/lastreference/${this.myAddress.address}`,
})
return myRef
}
renderSuccessText() {
return html`${translate("chatpage.cchange55")}`
@ -70,168 +70,158 @@ export class TipUser extends LitElement {
}
async fetchWalletDetails() {
await parentEpml.request('apiCall', {
url: `/addresses/balance/${this.myAddress.address}?apiKey=${this.getApiKey()}`,
})
.then((res) => {
if (isNaN(Number(res))) {
let snack4string = get("chatpage.cchange48")
parentEpml.request('showSnackBar', `${snack4string}`)
} else {
this.walletBalance = Number(res).toFixed(8)
}
})
}
async sendQort() {
const amount = this.shadowRoot.getElementById("amountInput").value
let recipient = this.userName
this.sendMoneyLoading = true
this.btnDisable = true
const amount = this.shadowRoot.getElementById("amountInput").value
let recipient = this.userName
this.sendMoneyLoading = true
this.btnDisable = true
if (parseFloat(amount) + parseFloat(0.001) > parseFloat(this.walletBalance)) {
this.sendMoneyLoading = false
this.btnDisable = false
let snack1string = get("chatpage.cchange51")
parentEpml.request('showSnackBar', `${snack1string}`)
return false
}
if (parseFloat(amount) <= 0) {
this.sendMoneyLoading = false
this.btnDisable = false
let snack2string = get("chatpage.cchange52")
parentEpml.request('showSnackBar', `${snack2string}`)
return false
}
if (recipient.length === 0) {
this.sendMoneyLoading = false
this.btnDisable = false
let snack3string = get("chatpage.cchange53")
parentEpml.request('showSnackBar', `${snack3string}`)
return false
}
const validateName = async (receiverName) => {
let myRes
let myNameRes = await parentEpml.request('apiCall', {
type: 'api',
url: `/names/${receiverName}`,
})
if (myNameRes.error === 401) {
myRes = false
} else {
myRes = myNameRes
}
return myRes;
}
const validateAddress = async (receiverAddress) => {
let myAddress = await window.parent.validateAddress(receiverAddress)
return myAddress
}
const validateReceiver = async (recipient) => {
let lastRef = await this.getLastRef()
let isAddress
try {
isAddress = await validateAddress(recipient)
} catch (err) {
isAddress = false
if (parseFloat(amount) + parseFloat(0.001) > parseFloat(this.walletBalance)) {
this.sendMoneyLoading = false
this.btnDisable = false
let snack1string = get("chatpage.cchange51")
parentEpml.request('showSnackBar', `${snack1string}`)
return false
}
if (isAddress) {
let myTransaction = await makeTransactionRequest(recipient, lastRef)
getTxnRequestResponse(myTransaction)
} else {
let myNameRes = await validateName(recipient)
if (myNameRes !== false) {
let myNameAddress = myNameRes.owner
let myTransaction = await makeTransactionRequest(myNameAddress, lastRef)
if (parseFloat(amount) <= 0) {
this.sendMoneyLoading = false
this.btnDisable = false
let snack2string = get("chatpage.cchange52")
parentEpml.request('showSnackBar', `${snack2string}`)
return false
}
if (recipient.length === 0) {
this.sendMoneyLoading = false
this.btnDisable = false
let snack3string = get("chatpage.cchange53")
parentEpml.request('showSnackBar', `${snack3string}`)
return false
}
const validateName = async (receiverName) => {
let myRes
let myNameRes = await parentEpml.request('apiCall', {
type: 'api',
url: `/names/${receiverName}`,
})
if (myNameRes.error === 401) {
myRes = false
} else {
myRes = myNameRes
}
return myRes;
}
const validateAddress = async (receiverAddress) => {
let myAddress = await window.parent.validateAddress(receiverAddress)
return myAddress
}
const validateReceiver = async (recipient) => {
let lastRef = await this.getLastRef()
let isAddress
try {
isAddress = await validateAddress(recipient)
} catch (err) {
isAddress = false
}
if (isAddress) {
let myTransaction = await makeTransactionRequest(recipient, lastRef)
getTxnRequestResponse(myTransaction)
} else {
console.error(this.renderReceiverText())
this.errorMessage = this.renderReceiverText()
let myNameRes = await validateName(recipient)
if (myNameRes !== false) {
let myNameAddress = myNameRes.owner
let myTransaction = await makeTransactionRequest(myNameAddress, lastRef)
getTxnRequestResponse(myTransaction)
} else {
console.error(this.renderReceiverText())
this.errorMessage = this.renderReceiverText()
this.sendMoneyLoading = false
this.btnDisable = false
}
}
}
const getName = async (recipient) => {
try {
const getNames = await parentEpml.request("apiCall", {
type: "api",
url: `/names/address/${recipient}`,
});
if (getNames?.length > 0) {
return getNames[0].name
} else {
return ''
}
} catch (error) {
return ""
}
}
const makeTransactionRequest = async (receiver, lastRef) => {
let myReceiver = receiver
let mylastRef = lastRef
let dialogamount = get("transactions.amount")
let dialogAddress = get("login.address")
let dialogName = get("login.name")
let dialogto = get("transactions.to")
let recipientName = await getName(myReceiver)
let myTxnrequest = await parentEpml.request('transaction', {
type: 2,
nonce: this.myAddress.nonce,
params: {
recipient: myReceiver,
recipientName: recipientName,
amount: amount,
lastReference: mylastRef,
fee: 0.001,
dialogamount: dialogamount,
dialogto: dialogto,
dialogAddress,
dialogName
},
})
return myTxnrequest
}
const getTxnRequestResponse = (txnResponse) => {
if (txnResponse.success === false && txnResponse.message) {
this.errorMessage = txnResponse.message
this.sendMoneyLoading = false
this.btnDisable = false
}
}
}
const getName = async (recipient)=> {
try {
const getNames = await parentEpml.request("apiCall", {
type: "api",
url: `/names/address/${recipient}`,
});
if (getNames?.length > 0 ) {
return getNames[0].name
throw new Error(txnResponse)
} else if (txnResponse.success === true && !txnResponse.data.error) {
this.shadowRoot.getElementById('amountInput').value = ''
this.errorMessage = ''
this.successMessage = this.renderSuccessText()
this.sendMoneyLoading = false
this.btnDisable = false
setTimeout(() => {
this.setOpenTipUser(false)
this.successMessage = ""
}, 3000)
} else {
return ''
this.errorMessage = txnResponse.data.message
this.sendMoneyLoading = false
this.btnDisable = false
throw new Error(txnResponse)
}
} catch (error) {
return ""
}
validateReceiver(recipient)
}
const makeTransactionRequest = async (receiver, lastRef) => {
let myReceiver = receiver
let mylastRef = lastRef
let dialogamount = get("transactions.amount")
let dialogAddress = get("login.address")
let dialogName = get("login.name")
let dialogto = get("transactions.to")
let recipientName = await getName(myReceiver)
let myTxnrequest = await parentEpml.request('transaction', {
type: 2,
nonce: this.myAddress.nonce,
params: {
recipient: myReceiver,
recipientName: recipientName,
amount: amount,
lastReference: mylastRef,
fee: 0.001,
dialogamount: dialogamount,
dialogto: dialogto,
dialogAddress,
dialogName
},
})
return myTxnrequest
}
const getTxnRequestResponse = (txnResponse) => {
if (txnResponse.success === false && txnResponse.message) {
this.errorMessage = txnResponse.message
this.sendMoneyLoading = false
this.btnDisable = false
throw new Error(txnResponse)
} else if (txnResponse.success === true && !txnResponse.data.error) {
this.shadowRoot.getElementById('amountInput').value = ''
this.errorMessage = ''
this.successMessage = this.renderSuccessText()
this.sendMoneyLoading = false
this.btnDisable = false
setTimeout(() => {
this.setOpenTipUser(false)
this.successMessage = ""
}, 3000)
} else {
this.errorMessage = txnResponse.data.message
this.sendMoneyLoading = false
this.btnDisable = false
throw new Error(txnResponse)
}
}
validateReceiver(recipient)
}
render() {
return html`
render() {
return html`
<div class="tip-user-header">
<img src="/img/qort.png" width="32" height="32">
<p class="tip-user-header-font">${translate("chatpage.cchange43")} ${this.userName}</p>
@ -240,11 +230,11 @@ export class TipUser extends LitElement {
<p class="tip-available">${translate("chatpage.cchange47")}: ${this.walletBalance} QORT</p>
<input id="amountInput" class="tip-input" type="number" placeholder="${translate("chatpage.cchange46")}" />
<p class="tip-available">${translate("chatpage.cchange49")}: 0.001 QORT</p>
${this.sendMoneyLoading ?
html`
${this.sendMoneyLoading ?
html`
<paper-progress indeterminate style="width: 100%; margin: 4px;">
</paper-progress>`
: html`
</paper-progress>`
: html`
<div style=${"text-align: center;"}>
<vaadin-button
?disabled=${this.btnDisable}
@ -257,21 +247,21 @@ export class TipUser extends LitElement {
</div>
`}
${this.successMessage ?
html`
${this.successMessage ?
html`
<p class="success-msg">
${this.successMessage}
</p>
`
: this.errorMessage ?
html`
: this.errorMessage ?
html`
<p class="error-msg">
${this.errorMessage}
</p>
`
: null}
: null}
</div>
`;
}
}
}
customElements.define('tip-user', TipUser)