Tron TRC20 HD Wallet for generate multi deposit address for one account - cryptocurrency

I created an account with:
TronWeb.utils.accounts.generateAccount()
Now I want to create child address of above account for every users.
When users deposit to these addresses, I want to manage balance from main account and transfer to another users all balances with one transaction.
Like HD Wallet on Bitcoin or ADA Cardano and etc.

Before these Mnemonic functionality in tronweb was not available in packge npm version 4.4.0. It was recently released. Usage examples:
const TronWeb = require('tronweb');
console.log(TronWeb.fromMnemonic('patch left empty genuine rain normal syrup yellow consider moon stock denial',"m/44'/195'/0'/0/3"));
exit:
{
privateKey: '781C49346BC8F7BCE6FF54FCD6D1A486E5F01238207124FC57DBFBDD91F325B6',
publicKey: '0421274E7431BFEE7428A42E71DB43D97773813CC50CE9FCA6D82CC72AED36618A1A3BF81B56967D888586F8240DE2078F798CB653AB1C7B681D2C2E82EA2B5A14',
address: {
base58: 'TFaC1WRiabPe8PU7NEFtPuPuLoHmtUSEkK',
hex: '413D765BFA4E0D353931737D80393C6AD78F459EB7'
}
}
Visit: https://developers.tron.network/reference/frommnemonic

As Tron transaction has no inputs and outputs concept you need to collect coins from all addresses manually creating a transaction for each address to send coin from it to desired target address.
And you need to pay fee for each such transaction. Actually for bitcoin you usually pay the same atomic fees because adding each output to bitcoin transaction costs according to memory added to transaction.
If you want it to be a single transaction you can try to design a smart contract accumulating coins from all your addresses and sending them to some target address.

Related

Firebase Firestore Stock Count updating?

I am using firebase purely to integrate a simple ticket buying system.
I would think this is a very common scenario people have and wondering what the solutions are.
I have an issue with the write limit time, it means I can't keep the stock count updated.
Due to Firebase's 1 second write limit and the way transactions work, they keep timing out when there is a large buy of tickets at one point in time.
For example:
Let's say we have a simple ticket document like this
{
name: "Taylor Bieber Concert"
stock: 100
price: 1000
}
I use a firebase transaction server side that does (pseudo)
transaction{
ticket = t.get(ticketRef).data() //get the data of ticketRef doc
guard (ticket .stock > 0) else return //check the stock is more than 0
t.update(ticketRef, {stock : increment(-1) }) //update the document and remove 1 stock value
}
The transaction and functionality all works however if I get 20-100 people trying to buy a ticket as it releases, it goes into contention it seems and times out a bunch of the requests...
Is there a way to avoid these timeouts? Some sort of queue or something?
I have tried using Transactions server-side in firebase functions to update the stock value, when many people try to purchase the product simultaneously it leads to majority of the transactions being locked out / Aborted Code 10

Flink or kafka stream in case where any change in stream result in processing all data

I have a use case where lets i get balances based on date and I want to show correct balances of each day. If get an update on older date all my balances of that account from that date gets changed.
for eg
Account Date balance Total balance
IBM 1Jun 100 100
IBM 2Jun 50 150
IBM 10Jun 200 350
IBM 12Jun 200 550
Now I get a message of date 4 Jun (this is the scenario some transaction is done back dated, or some correction and its frequent scenario)
Account Date balance Total balance
IBM 1Jun 100 100
IBM 2Jun 50 150
IBM 4Jun 300 450 ----------- all data from this point changes
IBM 10Jun 200 650
IBM 12Jun 200 850
Its a streaming data and at any point I want the correct balance to be shown for each account.
I know flink and kafka are good for streaming use case where if an update of a particular date doesnt trigger update on all data from that point onwards. But can we achieve this scenario as well efficiently or is this NOT a use case of these streaming tech at all ?
Please help
You can't modify a past message in the queue, therefore you should introduce a new message that invalidates previous one. For instance, you can use an ID for each transaction (and repeat it if you need to modified it). In case you have two or more messages with the same ID, you keep with the last one.
Take a look to KTable from Kafka Streams. It can help you to aggregate data using that ID (or any other aggregation factor) and generate a table as a result with the valid resume until now. If a new message arrives, table updates will be emitted

Multi currency - what to store and when to convert?

I have read different Q&A on SO regarding multi currency but none of them are clear to me or do not provide enough details with regards to my use case.
Scenario:
Company Raddo has 3 branch locations, UK, France and USA. Raddo has base currency US dollars. Budgets are created in US dollars. Raddo stores supported curencies exchange rates in the database.
Employees in UK create purchase orders in GBP and in France create purchase orders in Euros.
Q1: What should be stored in Purchase Orders/Order items database table - Branch location currency and current exchange rate or converted amounts in base currency US dollars? Please keep in mind that exchange rate must be the one at the time of PO created.
Q2: What to convert and when, to be able to generate reports in US dollars/base currency?
Q3: what is the impact on the exising data if someone say after 2 years change the base currency from US dollars to AUS Australian dollar?
Q4: What is the best way to deal with multi currencies so application handles minimum amount of conversions?
Bear in mind that the answers you receive will be subjective. With that disclaimer out of the way, this is how I would go about setting up such a system.
TL;DR: Use a currency rates table to store currency rates for different currencies and dates when they are applicable. Store amounts in both the local currency and a calculated USD value.
A Currency Rates Table
Create a currency table (FX rates) of the form:
FX_RATES
--------
SOURCE_CURRENCY -- e.g. USD, GBP, EUR
TARGET_CURRENCY -- as above
EXCHANGE_RATE -- a suitable decimal field representing the conversion
VALID_FROM_DATE -- date range when the above exchange rate is valid
VALID_TO_DATE -- as above
The combination of the first 4 columns will represent a unique record.
It is recommended that whenever a record for a pair of currencies (USD -> GBP) is entered, the equivalent reverse record is also inserted (GBP -> USD), either with the true exchange rate (conversions one way might use a different rate than the other way), or with the inverse of the original record.
For a pair of currencies, successive rows must exhibit continuity of dates (i.e. for a pair of currencies, there should never be a date that does not fall between VALID_FROM_DATE and VALID_TO_DATE in exactly one row).
For convenience, also enter a single row ('USD', 'USD', 1, smallest_date, largest_date) with the smallest and largest dates supported by the databases. This makes it easier to handle cases when entries are made in the base currency itself.
You will need to determine a source of currency FX rates that feeds this table, as well as a frequency of updation. For example, your financial team might issue a weekly FX rates table (even if the values in the currency market changes daily).
A sample table would look like the following. Although it appears there are overlaps between the end date of one row and the start date of the next, the lookup operation checks for equality only on one column (i.e. >= VALID_FROM_DATE AND < VALID_TO_DATE)
SOURCE_CURRENCY TARGET_CURRENCY EXCHANGE_RATE VALID_FROM_DATE VALID_TO_DATE
--------------- --------------- ---------------------- --------------- --------------
GBP USD 1.250000 06-Mar-2017 13-Mar-2017
GBP USD 1.260000 13-Mar-2017 20-Mar-2017
GBP USD 1.240000 20-Mar-2017 27-Mar-2017
GBP USD 1.250000 27-Mar-2017 03-Apr-2017
USD GBP 0.800000 06-Mar-2017 13-Mar-2017
USD GBP 0.793651 13-Mar-2017 20-Mar-2017
USD GBP 0.806452 20-Mar-2017 27-Mar-2017
USD GBP 0.800000 27-Mar-2017 03-Apr-2017
USD USD 1.000000 01-Jan-1900 31-Dec-9999
Columns in PO Table
In the purchase orders table, keep the following fields:
PURCHASE_ORDERS
---------------
... other fields
PO_TXN_DATE -- Date for the PO that represents the financial transaction
ORDER_VALUE_LOC -- Decimal field with the order value in local currency
ORDER_CURRENCY_LOC -- The currency used for ORDER_VALUE_LOC (e.g. GBP/EUR)
ORDER_VALUE_USD -- The order value in USD (as this is the company's base currency)
... other fields
Populating the PO Columns
There will already be a process that populates the PO table, which will have to be extended to populate the following fields:
PO_TXN_DATE is the date of the financial transaction on the PO. Based on your business rules, this may or may not be the date the PO is created/raised.
ORDER_VALUE_LOC is the value of the transaction in the local currency.
ORDER_CURRENCY_LOC is the currency code for the local currency.
These three fields will be used to look up the FX rates table.
ORDER_VALUE_USD is populated by looking up the exchange rate in the FX_RATES table:
Populating ORDER_VALUE_USD is demonstrated by the following pseudo-code
ORDER_VALUE_USD = PURCHASE_ORDERS.ORDER_VALUE_LOC * FX_RATES.EXCHANGE_RATE
WHERE
FX_RATES.SOURCE_CURRENCY = PURCHASE_ORDERS.ORDER_CURRENCY_LOC
AND FX_RATES.TARGET_CURRENCY = 'USD'
AND PURCHASE_ORDERS.PO_TXN_DATE >= FX_RATES.VALID_FROM_DATE
AND PURCHASE_ORDERS.PO_TXN_DATE < FX_RATES.VALID_TO_DATE
Answers to OP's Questions
Q1: What should be stored in Purchase Orders/Order items database
table - Branch location currency and current exchange rate or
converted amounts in base currency US dollars? Please keep in mind
that exchange rate must be the one at the time of PO created.
As mentioned, within the purchase orders table store the local currency value, transaction date, local currency name; also calculate and store the value in the base currency (USD). The exchange rate can be looked up again if required, there's no need to redundantly store it here.
The USD value is stored here to allow easier aggregation in a single currency (e.g. to generate a report that shows total value of outstanding POs to send to the head office). If the need for such a use case is low, then there's no need to store the USD value, it can be calculated from the FX rates table for the times it is required. However, the following question implies that there will be a reasonable need for getting the value in the base currency (USD).
Q2: What to convert and when, to be able to generate reports in US
dollars/base currency?
By storing the values in both the base currency and USD, such reporting will be greatly simplified. This is the reason we take the one-time cost of calculating and storing the USD value, so it can be read many times.
Q3: What is the impact on the existing data if someone - say after 2
years - changes the base currency from US dollars to AUD Australian
dollar?
Technically, if such a change is expected, then don't name any database structures with USD, instead use something generic like BASE. :-)
If such a change is done, the finance division of the company will instruct you how to restate the financial data - e.g. should you recalculate the base values based on the prevailing FX rate at the time of the transaction, or just use a flat conversion factor? In any case, once this decision is given to you, you just need to enter the appropriate conversion factors into the FX_RATES table, and run a one-off process to repopulate the PURCHASE_ORDERS.ORDER_VALUE_BASE column. Apart from the FX rate, all the other information for this lookup is already present and unchanged in the PURCHASE_ORDERS table.
Q4: What is the best way to deal with multiple currencies so application
handles minimum amount of conversions?
This will again be driven by your business needs, it will not be a technical decision. If there is a need to frequently report on both the local currency as well as the base (USD) currency, it helps to store the relevant transaction values in both currencies. By calculating it once and storing it, you can benefit from accessing stored data thereafter.
Also, since you're not discarding any data, you can always recalculate the financials if required. Some scenarios where this might be required are:
A corporate decision is made that the base currency is calculated using the prevailing exchange rate at the time of the PO being raised, but the base (USD) currency is to be recalculated when the PO is closed or invoiced. In such a case, you'd use a different date to look up the FX_RATES table at the time of closing the PO.
If the pound suddenly tanks, and changes from 1 GBP = 1.25 USD to 1.5 GBP = 1 USD, you might be required to calculate the dollar impact of such a change. Then, you can get the difference between the stored value ORDER_VALUE_USD and a re-calculated value using today's exchange rate from the FX_RATES table, to determine the dollar impact of such a shift.
Q5: Can't the exchange rate at the time of transaction be stored in the
purchase orders table? This way, system wont need to look up the
exchange rate in FX rates table. (Asked via a follow-up comment)
The exchange rate can definitely be stored in the PO table, instead of the USD amount. There is nothing intrinsically "wrong" about storing exchange rates in the PO table, nor is there anything "right" about storing the USD amount instead.
Of course, that then will lead on to a question of - where do you get the exchange rate from in order to populate it into the PO table, if you don't store it in some lookup table in the first place. Bear in mind that in large/global corporations, FX rates will in all likelihood not be populated via the LOB application itself, it will be some external source, such as a FX rates team that determines FX rates to be used across the company. In such a case, storing the FX rates in a separate table is more convenient.
I've listed some of the benefits of different approaches below. You'd need to pick the one(s) you use based on your needs.
Benefit of Storing USD in the PO Table: Amounts in USD are directly available without needing any further calculation (i.e. no need to calculate ORDER_VALUE_LOC x EXCHANGE_RATE when running a report).
Benefit of a separate FX Rates table: FX rates are centrally stored in a single table, making it easier to update & review (remember large corporations might have a separate team fixing the FX rates for company-wide use), as well as validate (e.g. to check for continuity of FX rates - in the above example, it is trivially simple to check that there no gaps for FX rates by stringing together the valid from/to dates on successive rows). FX rates are not scattered around multiple tables.
Benefit of Storing FX Rate in the PO Table: No need for a separate FX_RATES table.
Of course, you could redundantly store additional information (trading off storage) to gain a benefit (for example, in the PO table you store the local currency amount, FX rate and USD amount, as well as keep a separate FX rates table. This allows you to easily print out PO documents that displays the local currency amount, and the FX rate used to convert it to the USD amount. At the same time, the FX rates table remains as an authoritative source of exchange rates).
Remember, the question - and its answers - are subjective, so there's no right nor wrong. Tailor all these recommendations to your requirements, and your company's standards.
Usually you use the currency of the country where the company has its base and pay its taxes. So you should convert the other currencies to US$ with valid exchange rate at the time of transaction.
Conversions takes place as soon as you get all the data.
The impact of changing currency is unknown as it can change multitude of things not only the currency.
I dont know what is the best way, but it seems logical to keep track of all the exchange rates whenever any transaction happens, so you can give appropriate data.

Possibilities of AngularFire, sum of values entered by users, obtaining sum at main site with angular?

Suppose we want to develop a website. Key features:
home page (access for all) the main element on the page is the
sum of payments
registration and login page - mail address and password, account activation
the payment will be declared by the registered and logged in users through the form and a checkbox, when the checkbox is selected data should be uploaded to the server and saved if "pass verification" for example, do not exceed $ 10, each user in one day can only declare one payment
after possitive verification the sum from "number 1 above" is updated
additional features - user notification: when the last payment hasn't been made for more than six months, or if the total sum exceeds a certain level eg $ 1,000...
Is it possible that the whole solution would be based on angularfire? In particular:
the sum of payments - on main site the information about
the sum avaible for all visitors, so each time somebody visits the website
we will have to send request to Firebase to get all the records and
add the payments to finally show the sum on web site? With Angular we can do that?
Firebase enables queries/limits: e.g. last 20, but to get the whole amount you need to have knowledge of the previous value - in this case, increase in payments and visits will result in sending large amounts of data client side vs firebase - whether and how it can be optimized?
suppose that the activation of user account will require small payment
(paypal/transfer) is it possible to set account active when the
payment is done?

How many address fields would you use for a UK database?

Address records are probably used in most database, but I've seen a number of slightly different sets of fields used to store them. The number of fields seems to vary from 3-7, and sometimes all fields are simple labelled address1..addressN, other times given specific meaning (town, city, etc).
This is UK specific, though I'm open to comments about the rest of the world too. Here you need the first line of the address (actually just the number) and the post code to identify the address - everything else is mostly an added bonus.
I'm currently favouring:
Address 1
Address 2
Address 3
Town
County
Post Code
We could add Country if we ever needed it (unlikely).
What do you think? Is this too little, too much?
The Post Office suggests (http://www.postoffice.co.uk/portal/po/content1?catId=19100182&mediaId=19100267) 7 lines:
Addressees Name
Company/Organisation
Building Name
Number of building and name of thoroughfare
Locality Name
Post Town
Post Code
They then say you do not need to include a County name provided the Post Town and Postcode are used.
The BSI have BS 7666 - that covers all addressing. I recommend you look there.
The 2000 version recommends
An address shall be based upon a logical data model comprising the following entities:
addressable object, with sub-types:
primary addressable object;
secondary addressable object;
street;
locality;
town;
administrative area, a.k.a. district;
county;
postcode.
See: http://landregistry.data.gov.uk/def/common/BS7666Address
I don't know whether this is minimal (I doubt it) but the heading on my cheque book says something pretty close to:
Lloyds TSB
Isle of Man Offshore Centre
Peveril Buildings
Peveril Square
Douglas
Isle of Man
IM99 0XX
United Kingdom
This causes fits when I try to enter it into the US banking system.
If I were you, I'd call Royal Mail and ask them... or look on their website for postcode lookup as a best practice.
There's different types of addresses, and each different type has a slightly different structure. Forward sorting offices have a different postal address structure than a residential home with a street number. What if the house has a name instead of a number? There are so many factors to consider.
Since I moved to Canada I had to do something similar and it's far more complicated than a straightforward residential address which generally has:
Street Number if applicable
Street Number Suffix if applicable
House Name
Street Name
Street Type
Street Direction if applicable
Unit Number for flats, townhouses or other types of building/location
Minor Municipality (Village)
Major Municipality (Major Town/City)
County
PostCode
Country if you include Scotland, Wales, Northern Ireland (and now I noticed Eire)
Then you get businesses that have their own Delivery Route, PO Boxes, Forward Sortation Offices...
It gets complicated in a real hurry.
Best bet - give Royal Mail a call and they should be able to give you information on their standard address templates.
EDIT: Your 3 field method isn't a bad one...particularly. However, data sanitization may be a significant issue using the field setup you have and you may need a fairly complex strategy for making sure that the address entered is valid. It's far easier to sanitize single dedicated fields to make sure input is correct than it is to parse various address tokens out of combined fields.
Another simpler way to gain this info is to go on the Royal Mail website and check their postcode lookup page.
On their main postcode lookup, they use 4 fields and I guess they have some form of validation on the street name/type field. They separate the house number and name and I guess they only allow major municipality. I'm assuming the county/country are assumed. If you break out their advanced search, they give you two extra fields for flat number and business name.
Given that some fields are combined on their site, you have to assume that there's some amount of validation to make sure that data entered can be gainfully used.
Premises elements
Sub Building Name
Building Name
Building Number
Organisation Name
Department Name
PO Box Number
Thoroughfare elements
Dependent Thoroughfare Name
Dependent Thoroughfare Descriptor
Thoroughfare Name
Thoroughfare Descriptor
Locality elements
Double Dependent Locality
Dependent Locality
Post Town
Postcode element
Postcode
This answer may be a few years late, but it's aimed at those like myself looking for guidance on how to correctly format postal addresses for both storing in a database (or the likes of it) and for printing purposes.
Taken from Royal Mail Doc, link below - conveniently titled the 'Programmers Guide'
Technical specififcation for users of PAF
Page 27 - 42 was most helpful for me.
It's very likely that a "UK" will be opened to Eire as well, and in some lines of business there will be legal differences, generally between Scotland / NI / the channel islands and England and Wales.
In short, I would add country to the list. Otherwise it's fine (no fewer certainly), though of course any address is traceable from a building reference, a post code and a country alone.
Where we live in France its just 3 lines:-
myname
village/location name
6 digit postcode followed by post town name in uppercase
Even from UK that's all that is required

Resources