Skip to content
This repository has been archived by the owner on Dec 11, 2019. It is now read-only.

Commit

Permalink
Adds BAT support
Browse files Browse the repository at this point in the history
Resolves #9740
Resolves #10945
Resolves #11251 
Resolves #11264
Resolves #11285
Resolves #11289
Resolves #11292
Resolves #11293
  • Loading branch information
NejcZdovc committed Oct 6, 2017
1 parent 5de3dcb commit 5813411
Show file tree
Hide file tree
Showing 20 changed files with 719 additions and 1,442 deletions.
50 changes: 14 additions & 36 deletions app/browser/api/ledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const qr = require('qr-image')
const underscore = require('underscore')
const tldjs = require('tldjs')
const urlFormat = require('url').format
const queryString = require('querystring')
const levelUp = require('level')
const random = require('random-lib')
const uuid = require('uuid')
Expand Down Expand Up @@ -91,7 +90,8 @@ const clientOptions = {
rulesTestP: process.env.LEDGER_RULES_TESTING,
verboseP: process.env.LEDGER_VERBOSE,
server: process.env.LEDGER_SERVER_URL,
createWorker: electron.app.createWorker
createWorker: electron.app.createWorker,
version: 'v2'
}
const fileTypes = {
bmp: new Buffer([0x42, 0x4d]),
Expand Down Expand Up @@ -1319,7 +1319,7 @@ const enable = (state, paymentsEnabled) => {
}

if (!ledgerPublisher) {
ledgerPublisher = require('ledger-publisher')
ledgerPublisher = require('bat-publisher')
}
synopsis = new (ledgerPublisher.Synopsis)()
const stateSynopsis = ledgerState.getSynopsis(state)
Expand Down Expand Up @@ -1434,7 +1434,7 @@ const cacheRuleSet = (state, ruleset) => {
}

const clientprep = () => {
if (!ledgerClient) ledgerClient = require('ledger-client')
if (!ledgerClient) ledgerClient = require('bat-client')
_internal.debugP = ledgerClient.prototype.boolion(process.env.LEDGER_PUBLISHER_DEBUG)
_internal.verboseP = ledgerClient.prototype.boolion(process.env.LEDGER_PUBLISHER_VERBOSE)
}
Expand Down Expand Up @@ -1513,28 +1513,6 @@ const roundtrip = (params, options, callback) => {
if (options.payload) console.log('<<< ' + JSON.stringify(params.payload, null, 2).split('\n').join('\n<<< '))
}

const updateLedgerInfo = (state) => {
const ledgerInfo = ledgerState.getInfoProps(state)
const now = new Date().getTime()

if (ledgerInfo.get('buyURLExpires') > now) {
state = ledgerState.setInfoProp(state, 'buyMaximumUSD', 6)
}
if (typeof process.env.ADDFUNDS_URL !== 'undefined') {
state = ledgerState.setInfoProp(state, 'buyURLFrame', true)
const buyURL = process.env.ADDFUNDS_URL + '?' +
queryString.stringify({
currency: ledgerInfo.get('currency'),
amount: getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT),
address: ledgerInfo.get('address')
})
state = ledgerState.setInfoProp(state, 'buyURL', buyURL)
state = ledgerState.setInfoProp(state, 'buyMaximumUSD', false)
}

return state
}

const observeTransactions = (state, transactions) => {
const current = ledgerState.getInfoProp(state, 'transactions')
if (current && current.size === transactions.length) {
Expand All @@ -1558,9 +1536,10 @@ const getStateInfo = (state, parsedData) => {
return state
}

if (!ledgerClient) ledgerClient = require('bat-client')
const newInfo = {
paymentId: parsedData.properties.wallet.paymentId,
passphrase: parsedData.properties.wallet.keychains.passphrase,
passphrase: ledgerClient.prototype.getWalletPassphrase(parsedData),
created: !!parsedData.properties.wallet,
creating: !parsedData.properties.wallet,
reconcileFrequency: parsedData.properties.days,
Expand All @@ -1576,7 +1555,7 @@ const getStateInfo = (state, parsedData) => {

let transactions = []
if (!parsedData.transactions) {
return updateLedgerInfo(state)
return state
}

for (let i = parsedData.transactions.length - 1; i >= 0; i--) {
Expand All @@ -1599,13 +1578,12 @@ const getStateInfo = (state, parsedData) => {
}

observeTransactions(state, transactions)
state = ledgerState.setInfoProp(state, 'transactions', Immutable.fromJS(transactions))
return updateLedgerInfo(state)
return ledgerState.setInfoProp(state, 'transactions', Immutable.fromJS(transactions))
}

const generatePaymentData = (state) => {
const ledgerInfo = ledgerState.getInfoProps(state)
const paymentURL = `bitcoin:${ledgerInfo.get('address')}?amount=${ledgerInfo.get('btc')}&label=${encodeURI('Brave Software')}`
const paymentURL = `bitcoin:${ledgerInfo.get('address')}?amount=${ledgerInfo.get('bat')}&label=${encodeURI('Brave Software')}`
if (ledgerInfo.get('paymentURL') !== paymentURL) {
state = ledgerState.setInfoProp(state, 'paymentURL', paymentURL)
try {
Expand Down Expand Up @@ -1679,8 +1657,8 @@ const onWalletProperties = (state, body) => {
if (amount && currency) {
const bodyCurrency = body.getIn(['rates', 'currency'])
if (bodyCurrency) {
const btc = (amount / bodyCurrency).toFixed(8)
state = ledgerState.setInfoProp(state, 'btc', btc)
const bat = (amount / bodyCurrency).toFixed(8)
state = ledgerState.setInfoProp(state, 'bat', bat)
}
}

Expand Down Expand Up @@ -1744,7 +1722,7 @@ const getBalance = (state) => {
return
}

if (!ledgerBalance) ledgerBalance = require('ledger-balance')
if (!ledgerBalance) ledgerBalance = require('bat-balance')
ledgerBalance.getBalance(address, underscore.extend({balancesP: true}, client.options),
(err, provider, result) => {
if (err) {
Expand All @@ -1769,7 +1747,7 @@ const balanceReceived = (state, unconfirmed) => {
if (clientOptions.verboseP) {
console.log('\ngetBalance refreshes ledger info: ' + ledgerState.getInfoProp(state, 'unconfirmed'))
}
return updateLedgerInfo(state)
return state
}

if (ledgerState.getInfoProp(state, 'unconfirmed') === '0.0000') {
Expand Down Expand Up @@ -1896,7 +1874,7 @@ const initialize = (state, paymentsEnabled) => {
return state
}

if (!ledgerPublisher) ledgerPublisher = require('ledger-publisher')
if (!ledgerPublisher) ledgerPublisher = require('bat-publisher')
let ruleset = []
ledgerPublisher.ruleset.forEach(rule => {
if (rule.consequent) ruleset.push(rule)
Expand Down
1 change: 1 addition & 0 deletions app/browser/reducers/ledgerReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ const ledgerReducer = (state, action, immutableAction) => {
}
case appConstants.APP_NAVIGATOR_HANDLER_REGISTERED:
{
// TODO will this be changed when switching to BAT
const hasBitcoinHandler = (action.get('protocol') === 'bitcoin')
state = ledgerState.setInfoProp(state, 'hasBitcoinHandler', hasBitcoinHandler)
break
Expand Down
25 changes: 16 additions & 9 deletions app/common/lib/ledgerUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,24 @@ const shouldTrackView = (view, responseList) => {
return false
}

const btcToCurrencyString = (btc, ledgerData) => {
const balance = Number(btc || 0)
const batToCurrencyString = (bat, ledgerData) => {
const balance = Number(bat || 0)
const currency = (ledgerData && ledgerData.get('currency')) || 'USD'

if (balance === 0) {
return `0 ${currency}`
}

if (ledgerData && ledgerData.get('btc') && typeof ledgerData.get('amount') === 'number') {
const btcValue = ledgerData.get('btc') / ledgerData.get('amount')
const fiatValue = (balance / btcValue).toFixed(2)
if (ledgerData == null) {
return `${balance} BAT`
}

const ledgerBat = ledgerData.get('bat')
const amount = ledgerData.get('amount')

if (ledgerBat && typeof amount === 'number') {
const batValue = ledgerBat / amount
const fiatValue = (balance / batValue).toFixed(2)
let roundedValue = Math.floor(fiatValue)
const diff = fiatValue - roundedValue

Expand All @@ -87,7 +94,7 @@ const btcToCurrencyString = (btc, ledgerData) => {
return `${roundedValue.toFixed(2)} ${currency}`
}

return `${balance} BTC`
return `${balance} BAT`
}

const formattedTimeFromNow = (timestamp) => {
Expand All @@ -110,11 +117,11 @@ const walletStatus = (ledgerData) => {
const pendingFunds = Number(ledgerData.get('unconfirmed') || 0)

if (pendingFunds + Number(ledgerData.get('balance') || 0) <
0.9 * Number(ledgerData.get('btc') || 0)) {
0.9 * Number(ledgerData.get('bat') || 0)) {
status.id = 'insufficientFundsStatus'
} else if (pendingFunds > 0) {
status.id = 'pendingFundsStatus'
status.args = {funds: btcToCurrencyString(pendingFunds, ledgerData)}
status.args = {funds: batToCurrencyString(pendingFunds, ledgerData)}
} else if (transactions && transactions.size > 0) {
status.id = 'defaultWalletStatus'
} else {
Expand Down Expand Up @@ -206,7 +213,7 @@ const stickyP = (state, publisherKey) => {

module.exports = {
shouldTrackView,
btcToCurrencyString,
batToCurrencyString,
formattedTimeFromNow,
formattedDateFromTimestamp,
walletStatus,
Expand Down
20 changes: 0 additions & 20 deletions app/extensions/brave/locales/en-US/preferences.properties
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,7 @@ backupLedger=Backup your wallet
balanceRecovered={{balance}} was recovered and transferred to your Brave wallet.
beta=beta
bitcoin=Bitcoin
bitcoinAdd=Use your existing Bitcoin wallet/account
bitcoinAddDescription=Use any BTC wallet that can transfer Bitcoin to your Brave wallet.
bitcoinBalance=Please transfer:&nbsp;
bitcoinBuy=Buy Bitcoin
bitcoinCopyAddress=Copy Bitcoin address to clipboard
bitcoinPaymentURL=Your Brave wallet address
bitcoinQR=Your Brave wallet QR code
bitcoinQRImg.title=Brave wallet QR code
bitcoinVisitAccount=Transfer BTC
bitcoinWalletNotAvailable=Wallet information not available. :(
bitwarden=bitwarden&reg;
blockAttackSites=Block reported attack sites (not available yet)
blockedCountBadge=Display block count badge on shields button
Expand All @@ -60,8 +51,6 @@ cancel=Cancel
checkDefaultOnStartup=Always check on startup
clearAll=Clear all
clearBrowsingDataNow=Clear Browsing Data Now…
coinbaseMessage=debit/credit funding powered by coinbase
coinbaseNotAvailable=Sorry! Adding funds with a credit/debit card is available only for contributions of $5/month at the moment.
comingSoon=Coming soon!
compactBraveryPanel=Use compact panel
contentSettings=Content Settings
Expand Down Expand Up @@ -95,7 +84,6 @@ defaultWalletStatus=Thanks for helping support your favorite websites!
defaultZoomLevel=Default zoom level
disableTitleMode=Always show the URL bar
disconnect=Disconnect
displayQRCode=Display QR code
dollarsPaid=Amount
done=Done
doNotManageMyPasswords=Don't manage my passwords
Expand Down Expand Up @@ -132,9 +120,6 @@ flashTroubleshooting=Flash not working? Try the troubleshooting tips on our
fr-FR=French (France)
fullscreenContent=Full Screen Content
fullscreenPermission=Fullscreen access
fundingDisabled1=Card funding is temporarily unavailable.
fundingDisabled2=We apologize for the inconvenience.
fundingDisabled3=Learn more...
general=General
generalSettings=General Settings
geolocationPermission=Location access
Expand Down Expand Up @@ -185,8 +170,6 @@ minimumVisitsHigh=10 visits
minimumVisitsLow=1 visit
minimumVisitsMedium=5 visits
minimumVisitsSetting=Minimum visits for publisher relevancy
moneyAdd=Use your debit/credit card
moneyAddSubTitle=No Bitcoin needed!
monthlyBudget=monthly budget
ms-MY=Malay (Malaysia)
multipleHomePages.title=Multiple home pages
Expand All @@ -213,7 +196,6 @@ ok=Ok
on=on
onePassword=1Password&reg; (requires application)
openExternalPermission=Open external applications
outsideUSAPayment=Buy Bitcoin at our recommended source
pageNofMText=Page {{n}} of {{m}}
paintTabs=Show tabs in page theme color
passwordManager=Password Manager
Expand Down Expand Up @@ -302,7 +284,6 @@ site=Site
sitePermissions=Saved Site Permissions
sitePermissionsExceptions=Saved Site Exceptions
sl=Slovenian
smartphoneTitle=Use your smartphone app to transfer Bitcoin
startsWith=Brave starts with
startsWithOptionHomePage=Home page
startsWithOptionLastTime=My windows / tabs from last time
Expand Down Expand Up @@ -368,7 +349,6 @@ timeSpent=Time Spent
toolbarUserInterfaceScale=Toolbar and UI elements scale
totalAmount=Total Amount
tr-TR=Turkish (Turkey)
transferTime=Transfer may take up to 40 minutes
uk=Ukrainian
update=Update
updateToPreviewReleases=Update to preview releases *
Expand Down
1 change: 0 additions & 1 deletion app/locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,6 @@ var rendererIdentifiers = function () {
'turnOffNotifications',
'copyToClipboard',
'smartphoneTitle',
'displayQRCode',
'updateLater',
'updateHello',
// notifications
Expand Down
18 changes: 18 additions & 0 deletions app/renderer/components/preferences/payment/addFounds.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')

// Components
const ImmutableComponent = require('../../immutableComponent')

class AddFounds extends ImmutableComponent {
render () {
return <section data-test-id='addFounds'>
Add founds
</section>
}
}

module.exports = AddFounds
18 changes: 18 additions & 0 deletions app/renderer/components/preferences/payment/addFoundsFooter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')

// Components
const ImmutableComponent = require('../../immutableComponent')

class AddFoundsFooter extends ImmutableComponent {
render () {
return <section data-test-id='addFoundsFooter'>
Add founds footer
</section>
}
}

module.exports = AddFoundsFooter
Loading

0 comments on commit 5813411

Please sign in to comment.