@ledgerhq/live-common
Version:
Common ground for the Ledger Live apps
69 lines • 2.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useBakers = useBakers;
exports.useDelegation = useDelegation;
exports.useBaker = useBaker;
exports.useRandomBaker = useRandomBaker;
exports.useStakingPositions = useStakingPositions;
const react_1 = require("react");
const index_1 = require("@ledgerhq/coin-tezos/network/index");
function useBakers(whitelistAddresses) {
const [whitelistedBakers, setWhitelistedBakers] = (0, react_1.useState)(() => index_1.bakers.listBakersWithDefault(whitelistAddresses));
(0, react_1.useEffect)(() => {
index_1.bakers.listBakers(whitelistAddresses).then(setWhitelistedBakers);
}, [whitelistAddresses]);
return whitelistedBakers;
}
function useDelegation(account) {
const [delegation, setDelegation] = (0, react_1.useState)(() => index_1.bakers.getAccountDelegationSync(account));
(0, react_1.useEffect)(() => {
let cancelled = false;
index_1.bakers.loadAccountDelegation(account).then(delegation => {
if (cancelled)
return;
setDelegation(delegation);
});
return () => {
cancelled = true;
};
}, [account]);
return delegation;
}
function useBaker(addr) {
const [baker, setBaker] = (0, react_1.useState)(() => index_1.bakers.getBakerSync(addr));
index_1.bakers.loadBaker(addr).then(setBaker);
return baker;
}
// select a random baker for the mount time (assuming bakers length don't change)
function useRandomBaker(bakers) {
const randomBakerIndex = (0, react_1.useMemo)(() => {
const nonFullBakers = bakers.filter(b => b.capacityStatus !== "full");
if (nonFullBakers.length > 0) {
// if there are non full bakers, we pick one
const i = Math.floor(Math.random() * nonFullBakers.length);
return bakers.indexOf(nonFullBakers[i]);
}
// fallback on random between only full bakers
return Math.floor(Math.random() * bakers.length); // for perf, we only want to re-calc on bakers.length changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [bakers.length]);
return bakers[randomBakerIndex];
}
function useStakingPositions(account) {
const delegation = useDelegation(account);
return (0, react_1.useMemo)(() => {
if (account.type !== "Account" || !delegation?.address)
return [];
return [
{
uid: account.freshAddress,
address: account.freshAddress,
delegate: delegation.address,
state: "active",
asset: { type: "native" },
amount: BigInt(account.balance.toString()),
},
];
}, [account, delegation]);
}
//# sourceMappingURL=react.js.map