xrpl.js icon indicating copy to clipboard operation
xrpl.js copied to clipboard

convert currency codes

Open shortthefomo opened this issue 3 years ago • 2 comments

Currency codes are parsed as Hex in all ledger objects.

Would be great to have a standard helper function to convert the hex value to the human readable string value.

shortthefomo avatar Dec 24 '21 02:12 shortthefomo

There is the xrpl.convertHexToString function. Taking the SOLO currency which is represented by the following hexadecimal string 534F4C4F00000000000000000000000000000000

let currency = xrpl
.convertHexToString('534F4C4F00000000000000000000000000000000') // returns "SOLO\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"
.replaceAll('\u0000', ''); //Removes the Unicode NULL char \u0000

console.log(currency); // -> "SOLO"

ocean-drop avatar Jan 01 '22 17:01 ocean-drop

Be careful with doing that because with the example above it's possible to make a currency code that decodes to "XRP" but isn't actually XRP.

Here's a more thorough parser from the XRPL-Services frontend in TypeScript:

 	export function normalizeCurrencyCodeXummImpl(currencyCode: string, maxLength = 20): string {
	    if(!currencyCode) return "";
	
	    if(currencyCode.length === 3 && currencyCode.trim().toLowerCase() !== 'xrp') {
	        // Normal currency code
	        return currencyCode.trim()
	    }
	
	    if(currencyCode.match(/^[a-fA-F0-9]{4,40}$/) && !isNaN(parseInt(currencyCode, 16))) {
	        //console.log("is hex xumm impl")
	        // HEX currency code
	        const hex = currencyCode.toString().replace(/(00)+$/g, '')
	        if (hex.startsWith('01')) {
	            return convertDemurrageToUTF8(currencyCode);
	        }
	        if (hex.startsWith('02')) {
	            const xlf15d = Buffer.from(hex, 'hex').slice(8).toString('utf-8').slice(0, maxLength).trim()
	            if (xlf15d.match(/[a-zA-Z0-9]{3,}/) && xlf15d.toLowerCase() !== 'xrp') {
	            return xlf15d
	            }
	        }
	        const decodedHex = Buffer.from(hex, 'hex').toString('utf-8').slice(0, maxLength).trim()
	        if (decodedHex.match(/[a-zA-Z0-9]{3,}/) && decodedHex.toLowerCase() !== 'xrp') {
	            return decodedHex
	        }
	    }
	    return "";
	};

mDuo13 avatar Jan 21 '22 01:01 mDuo13