edge-core-js
Version:
Edge account & wallet management library
73 lines (64 loc) • 2.74 kB
JavaScript
function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
/**
* Upgrades the memo fields inside an EdgeSpendTarget,
* so any combination of legacy or modern apps or plugins will work.
*/
export function upgradeMemos(
spendInfo,
currencyInfo
) {
const legacyMemos = []
// If this chain supports legacy memos, grab those:
const { memoType } = currencyInfo
if (memoType === 'hex' || memoType === 'number' || memoType === 'text') {
for (const target of spendInfo.spendTargets) {
if (target.memo != null) {
legacyMemos.push({
type: memoType,
value: target.memo
})
} else if (target.uniqueIdentifier != null) {
legacyMemos.push({
type: memoType,
value: target.uniqueIdentifier
})
} else if (typeof _optionalChain([target, 'access', _ => _.otherParams, 'optionalAccess', _2 => _2.uniqueIdentifier]) === 'string') {
legacyMemos.push({
type: memoType,
value: target.otherParams.uniqueIdentifier
})
}
}
}
// We need to support 0x prefixes for backwards compatibility:
for (const memo of legacyMemos) {
if (memo.type === 'hex') memo.value = memo.value.replace(/^0x/i, '')
}
// Make a modern, legacy-free spend target:
const out = {
...spendInfo,
// Delete any legacy memo fields:
spendTargets: spendInfo.spendTargets.map(target => ({
...target,
memo: undefined,
uniqueIdentifier: undefined
})),
// Only use the legacy memos if new ones are missing:
memos: _nullishCoalesce(spendInfo.memos, () => ( legacyMemos))
}
// If we have exactly one memo, copy it to the legacy fields
// to support out-dated currency plugins:
if (_optionalChain([out, 'access', _3 => _3.memos, 'optionalAccess', _4 => _4.length]) === 1 && out.spendTargets.length >= 1) {
const [memo] = out.memos
if (memo.type === currencyInfo.memoType) {
const [target] = out.spendTargets
target.memo = memo.value
target.uniqueIdentifier = memo.value
target.otherParams = {
...target.otherParams,
uniqueIdenfitifer: memo.value
}
}
}
return out
}