forked from unimatrix/web
19 lines
1.3 KiB
JavaScript
19 lines
1.3 KiB
JavaScript
// Account arithmetic shared by quest rewards, approved corrections and transfer
|
|
// instruments. Domain callers own authorisation, once-only keys and transactions.
|
|
const whole=n=>Number.isSafeInteger(n)&&n>=0;
|
|
function check(state){
|
|
if(!state||![state.totalXP,state.effectiveXP,state.reserveXP].every(whole)||state.totalXP!==state.effectiveXP+state.reserveXP)throw TypeError('Invalid XP account');
|
|
}
|
|
export function creditXP(state,amount,{capXP}){
|
|
check(state);if(!whole(amount)||!whole(capXP)||state.effectiveXP>capXP)throw TypeError('Invalid XP credit');
|
|
const totalXP=state.totalXP+amount;if(!whole(totalXP))throw TypeError('XP account overflow');
|
|
const available=Math.min(amount,capXP-state.effectiveXP);
|
|
return {...state,totalXP,effectiveXP:state.effectiveXP+available,reserveXP:state.reserveXP+amount-available};
|
|
}
|
|
export function transferReservedXP(state,{sealedAmount,capXP}){
|
|
check(state);
|
|
if(!whole(sealedAmount)||sealedAmount>state.reserveXP||!whole(capXP)||capXP<state.effectiveXP)throw TypeError('XP transfer does not match sealed reserve');
|
|
const released=Math.min(sealedAmount,capXP-state.effectiveXP);
|
|
// A rollover moves existing XP; it never creates lifetime XP a second time.
|
|
return {...state,effectiveXP:state.effectiveXP+released,reserveXP:state.reserveXP-released};
|
|
}
|

Staff