Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bump csl #3614

Merged
merged 5 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { LoadingButton } from '@mui/lab';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { parseDrepId } from '@yoroi/staking';
import * as React from 'react';
import { RustModule } from '../../../../api/ada/lib/cardanoCrypto/rustLoader';
import { dRepToMaybeCredentialHex } from '../../../../api/ada/lib/cardanoCrypto/utils';
import { TextInput } from '../../../components/Input/TextInput';
import { useModal } from '../../../components/modals/ModalContext';
import { useGovernance } from '../module/GovernanceContextProvider';
import { useStrings } from './useStrings';

type ChooseDRepModallProps = {
onSubmit?: (drepId: string) => void;
onSubmit?: (drepId: string, drepCredential: string) => void;
};

export const ChooseDRepModal = ({ onSubmit }: ChooseDRepModallProps) => {
Expand All @@ -25,13 +24,12 @@ export const ChooseDRepModal = ({ onSubmit }: ChooseDRepModallProps) => {
}, [drepId]);

const confirmDRep = () => {
parseDrepId(drepId, RustModule.CrossCsl.init('any'))
.then(_ => {
onSubmit?.(drepId);
})
.catch(_ => {
setError(true);
});
const dRepCredentialHex: string | null = dRepToMaybeCredentialHex(drepId);
if (dRepCredentialHex == null) {
setError(true);
} else {
onSubmit?.(drepId, dRepCredentialHex);
}
};

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import BigNumber from 'bignumber.js';
import moment from 'moment';
import { WalletTypeOption } from '../../../../api/ada/lib/storage/models/ConceptualWallet/interfaces';
import { maybe } from '../../../../coreUtils';
import { genLookupOrFail } from '../../../../stores/stateless/tokenHelpers';
import { calculateAndFormatValue } from '../../../../utils/unit-of-account';

Expand Down Expand Up @@ -89,14 +88,17 @@ export const getFormattedPairingValue = (getCurrentPrice, defaultTokenInfo, unit
};

const getTotalAmount = (walletAmount, rewards) => {
return maybe(walletAmount, w => rewards.joinAddCopy(w));
return walletAmount && rewards
? walletAmount.joinAddCopy(rewards)
: (walletAmount ?? rewards);
};

const getWalletTotalAdaBalance = (stores, selectedWallet) => {
const totalAmount = stores.transactions.getBalance(selectedWallet);
const rewards = stores.delegation.getRewardBalanceOrZero(selectedWallet);
const amount = getTotalAmount(totalAmount, rewards);
const defaultEntry = amount?.getDefaultEntry();
if (defaultEntry == null) return new BigNumber(0);
const getTokenInfo = genLookupOrFail(stores.tokenInfoStore.tokenInfo);
const tokenInfo = getTokenInfo(defaultEntry);
return defaultEntry.amount.shiftedBy(-tokenInfo.Metadata.numberOfDecimals);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const messages = Object.freeze(
},
drepId: {
id: 'governance.drepId',
defaultMessage: '!!!Drep ID:',
defaultMessage: '!!!Drep ID (Fingerprint):',
},
delegateToDRep: {
id: 'governance.delegateToDRep',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const GovernanceStatusSelection = () => {
const pageSubtitle = governanceStatus.status === 'none' ? strings.reviewSelection : strings.statusSelected(statusRawText);
const isPendindDrepDelegationTx = submitedTransactions.length > 0 && submitedTransactions[0]?.isDrepDelegation === true;

const openDRepIdModal = (onSubmit: (drepID: string) => void) => {
const openDRepIdModal = (onSubmit: (drepID: string, drepCredential: string) => void) => {
if (!governanceManager) {
return;
}
Expand All @@ -72,10 +72,10 @@ export const GovernanceStatusSelection = () => {
};

const handleDelegate = async () => {
openDRepIdModal(drepID => {
openDRepIdModal((drepID, drepCredential) => {
const vote: Vote = { kind: 'delegate', drepID };
governanceVoteChanged(vote);
createUnsignTx(drepID);
createUnsignTx(drepCredential);
});
};

Expand Down
16 changes: 16 additions & 0 deletions packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ export function transactionHexReplaceWitnessSet(txHex: string, witnessSetHex: st
});
}

export function dRepToMaybeCredentialHex(s: string): ?string {
return RustModule.WasmScope(Module => {
try {
if (s.startsWith('drep1')) {
return Module.WalletV4.Credential
.from_keyhash(Module.WalletV4.Ed25519KeyHash.from_bech32(s)).to_hex();
}
if (s.startsWith('drep_script1')) {
return Module.WalletV4.Credential
.from_scripthash(Module.WalletV4.ScriptHash.from_bech32(s)).to_hex();
}
} catch {} // eslint-disable-line no-empty
return null;
})
}

export function pubKeyHashToRewardAddress(hex: string, network: number): string {
return RustModule.WasmScope(Module =>
Module.WalletV4.RewardAddress.new(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { normalizeToAddress, unwrapStakingKey, } from './utils';
import type { IGetAllUtxosResponse, IGetStakingKey, } from '../models/PublicDeriver/interfaces';
import { MultiToken, } from '../../../../common/lib/MultiToken';
import { maybe, fail } from '../../../../../coreUtils';
import { isHex } from '@emurgo/yoroi-lib/dist/internals/utils/index';

export type GetDelegatedBalanceRequest = {|
publicDeriver: PublicDeriver<> & IGetStakingKey,
Expand Down Expand Up @@ -139,23 +138,20 @@ export async function getUtxoDelegatedBalance(
export const DREP_ALWAYS_ABSTAIN = 'ALWAYS_ABSTAIN';
export const DREP_ALWAYS_NO_CONFIDENCE = 'ALWAYS_NO_CONFIDENCE';

// <TODO:WASM_MONAD>
function parseKey(key: string): RustModule.WalletV4.Ed25519KeyHash {
return isHex(key)
? RustModule.WalletV4.Ed25519KeyHash.from_hex(key)
: RustModule.WalletV4.Ed25519KeyHash.from_bech32(key);
}

// <TODO:WASM_MONAD>
function parseDrep(drepCredential: string): RustModule.WalletV4.DRep {
const DRep = RustModule.WalletV4.DRep;
if (drepCredential === DREP_ALWAYS_ABSTAIN) return DRep.new_always_abstain();
if (drepCredential === DREP_ALWAYS_NO_CONFIDENCE) return DRep.new_always_no_confidence();
// <TODO:FIX> to handle script hashes
const credential = RustModule.WalletV4.Credential.from_keyhash(parseKey(drepCredential));
return maybe(credential.to_keyhash(), k => DRep.new_key_hash(k))
?? maybe(credential.to_scripthash(), s => DRep.new_script_hash(s))
?? fail('weird credential cannot be converted into a drep: ' + credential.to_hex())
try {
const DRep = RustModule.WalletV4.DRep;
if (drepCredential === DREP_ALWAYS_ABSTAIN) return DRep.new_always_abstain();
if (drepCredential === DREP_ALWAYS_NO_CONFIDENCE) return DRep.new_always_no_confidence();
const credential = RustModule.WalletV4.Credential.from_hex(drepCredential);
return maybe(credential.to_keyhash(), k => DRep.new_key_hash(k))
?? maybe(credential.to_scripthash(), s => DRep.new_script_hash(s))
?? fail('weird credential cannot be converted into a drep: ' + credential.to_hex())
} catch (e) {
console.log('Fail to parse a drep credential: ' + drepCredential, e);
throw e;
}
}

// <TODO:WASM_MONAD>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3054,7 +3054,7 @@ async function certificateToDb(
result.push((txId: number) => ({
certificate: {
Ordinal: cert.certIndex,
Kind: RustModule.WalletV4.CertificateKind.DrepRegistration,
Kind: RustModule.WalletV4.CertificateKind.DRepRegistration,
Payload: '',
TransactionId: txId,
},
Expand All @@ -3066,7 +3066,7 @@ async function certificateToDb(
result.push((txId: number) => ({
certificate: {
Ordinal: cert.certIndex,
Kind: RustModule.WalletV4.CertificateKind.DrepDeregistration,
Kind: RustModule.WalletV4.CertificateKind.DRepDeregistration,
Payload: '',
TransactionId: txId,
},
Expand All @@ -3078,7 +3078,7 @@ async function certificateToDb(
result.push((txId: number) => ({
certificate: {
Ordinal: cert.certIndex,
Kind: RustModule.WalletV4.CertificateKind.DrepUpdate,
Kind: RustModule.WalletV4.CertificateKind.DRepUpdate,
Payload: '',
TransactionId: txId,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,8 @@ function formatLedgerWithdrawals(
}

type WasmCertWithAnchor =
RustModule.WalletV4.DrepRegistration
| RustModule.WalletV4.DrepUpdate;
RustModule.WalletV4.DRepRegistration
| RustModule.WalletV4.DRepUpdate;

function wasmCertToAnchor(wasmCert: WasmCertWithAnchor): ?AnchorParams {
const wasmAnchor = wasmCert.anchor();
Expand Down Expand Up @@ -372,9 +372,9 @@ function wasmCertToStakeCredential(wasmCert: WasmCertWithStakeCredential, getPat
}

type WasmCertWithDrepCredential =
RustModule.WalletV4.DrepRegistration
| RustModule.WalletV4.DrepUpdate
| RustModule.WalletV4.DrepDeregistration;
RustModule.WalletV4.DRepRegistration
| RustModule.WalletV4.DRepUpdate
| RustModule.WalletV4.DRepDeregistration;

function wasmCertToDRepCredential(wasmCert: WasmCertWithDrepCredential, getPath: RustModule.WalletV4.Credential => number[]): CredentialParams {
return {
Expand Down Expand Up @@ -521,7 +521,7 @@ function convertCertificate(
wasmCertToVoteDelegation(wasmCert, getPath),
];
}
case RustModule.WalletV4.CertificateKind.DrepRegistration: {
case RustModule.WalletV4.CertificateKind.DRepRegistration: {
const wasmCert = forceNonNull(wasmCertificateWrap.as_drep_registration());
return [{
type: CertificateType.DREP_REGISTRATION,
Expand All @@ -532,7 +532,7 @@ function convertCertificate(
},
}];
}
case RustModule.WalletV4.CertificateKind.DrepUpdate: {
case RustModule.WalletV4.CertificateKind.DRepUpdate: {
const wasmCert = forceNonNull(wasmCertificateWrap.as_drep_update());
return [{
type: CertificateType.DREP_UPDATE,
Expand All @@ -542,7 +542,7 @@ function convertCertificate(
},
}];
}
case RustModule.WalletV4.CertificateKind.DrepDeregistration: {
case RustModule.WalletV4.CertificateKind.DRepDeregistration: {
const wasmCert = forceNonNull(wasmCertificateWrap.as_drep_deregistration());
return [{
type: CertificateType.DREP_DEREGISTRATION,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -900,11 +900,11 @@ export default class TransactionRevamp extends Component<Props, State> {
return intl.formatMessage(shelleyCertificateKinds.CommitteeHotAuth);
case Scope.WalletV4.CertificateKind.CommitteeColdResign:
return intl.formatMessage(shelleyCertificateKinds.CommitteeColdResign);
case Scope.WalletV4.CertificateKind.DrepRegistration:
case Scope.WalletV4.CertificateKind.DRepRegistration:
return intl.formatMessage(shelleyCertificateKinds.DrepRegistration);
case Scope.WalletV4.CertificateKind.DrepDeregistration:
case Scope.WalletV4.CertificateKind.DRepDeregistration:
return intl.formatMessage(shelleyCertificateKinds.DrepDeregistration);
case Scope.WalletV4.CertificateKind.DrepUpdate:
case Scope.WalletV4.CertificateKind.DRepUpdate:
return intl.formatMessage(shelleyCertificateKinds.DrepUpdate);
default: {
throw new Error(`${nameof(this.shelleyCertificateToText)} unexpected kind ${kind}`);
Expand Down
10 changes: 5 additions & 5 deletions packages/yoroi-extension/app/connector/stores/ConnectorStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -852,11 +852,11 @@ export default class ConnectorStore extends Store<StoresMap, ActionsMap> {
cip95Info.push({
type: 'VotingProcedure',
voterType: voter.kind(),
voterHash: voter.to_constitutional_committee_hot_cred()?.to_scripthash()?.to_hex() ||
voter.to_constitutional_committee_hot_cred()?.to_keyhash()?.to_hex() ||
voter.to_drep_cred()?.to_scripthash()?.to_hex() ||
voter.to_drep_cred()?.to_keyhash()?.to_hex() ||
voter.to_staking_pool_key_hash()?.to_hex() ||
voterHash: voter.to_constitutional_committee_hot_credential()?.to_scripthash()?.to_hex() ||
voter.to_constitutional_committee_hot_credential()?.to_keyhash()?.to_hex() ||
voter.to_drep_credential()?.to_scripthash()?.to_hex() ||
voter.to_drep_credential()?.to_keyhash()?.to_hex() ||
voter.to_stake_pool_key_hash()?.to_hex() ||
(() => { throw new Error('unexpected voter'); })(),
govActionTxId: govActionId.transaction_id().to_hex(),
govActionIndex: govActionId.index(),
Expand Down
2 changes: 1 addition & 1 deletion packages/yoroi-extension/app/i18n/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -1070,7 +1070,7 @@
"governance.noConfidenceInfo": "You are expressing a lack of trust for all proposals now and in the future.",
"governance.learnMore": "Learn more About Governance",
"governance.becomeADrep": "Want to became a Drep?",
"governance.drepId": "Drep ID:",
"governance.drepId": "Drep ID (Fingerprint):",
"governance.statusSelected": "You have selected {status} as your governance status. You can change it at any time by clicking in the card bellow",
"governance.statusPending": "You have chosen your governance status, this process may take a while.",
"governance.registerGovernance": "Register in Governance",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { ReactComponent as goBackIcon } from '../../assets/images/top-bar/back-a
import environment from '../../environment';
import globalMessages, { connectorMessages } from '../../i18n/global-messages';
import { ROUTES } from '../../routes-config';
import { isTrezorTWallet } from '../../api/ada/lib/storage/models/ConceptualWallet';

export type SidebarCategory = {|
+className: string,
Expand Down Expand Up @@ -182,7 +183,7 @@ export const allCategoriesRevamp: Array<SidebarCategoryRevamp> = [
route: '/governance',
icon: governanceIcon,
label: globalMessages.sidebarGovernance,
isVisible: _request => true,
isVisible: ({ selected }) => selected != null && !isTrezorTWallet(selected.getParent()),
featureFlagName: 'governance',
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,9 @@ export default class DelegationStore extends Store<StoresMap, ActionsMap> {
try {
const { BackendService } = publicDeriver.getParent().getNetworkInfo().Backend;
const transitionResult = await maybe(currentPool, p =>
new PoolInfoApi(forceNonNull(BackendService) + '/api').getTransition(p, RustModule.CrossCsl.init)
new PoolInfoApi(forceNonNull(BackendService) + '/api')
// $FlowIgnore
.getTransition(p, RustModule.CrossCsl.init)
);

const response = {
Expand Down Expand Up @@ -319,6 +321,7 @@ export default class DelegationStore extends Store<StoresMap, ActionsMap> {
oldBackendUrl: String(backendService),
newBackendUrl: String(backendServiceZero),
networkId,
// $FlowIgnore
wasmFactory: RustModule.CrossCsl.init,
});

Expand Down
8 changes: 4 additions & 4 deletions packages/yoroi-extension/chrome/extension/connector/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -581,15 +581,15 @@ const CERT_TO_KEYHASH_FUNCS = [
([
cert => cert.as_drep_registration(),
cert => cert.voting_credential().to_keyhash(),
]: CertToKeyhashFuncs<RustModule.WalletV4.DrepRegistration>),
]: CertToKeyhashFuncs<RustModule.WalletV4.DRepRegistration>),
([
cert => cert.as_drep_deregistration(),
cert => cert.voting_credential().to_keyhash(),
]: CertToKeyhashFuncs<RustModule.WalletV4.DrepDeregistration>),
]: CertToKeyhashFuncs<RustModule.WalletV4.DRepDeregistration>),
([
cert => cert.as_drep_update(),
cert => cert.voting_credential().to_keyhash(),
]: CertToKeyhashFuncs<RustModule.WalletV4.DrepUpdate>),
]: CertToKeyhashFuncs<RustModule.WalletV4.DRepUpdate>),
([
cert => cert.as_pool_registration(),
cert => {
Expand Down Expand Up @@ -640,7 +640,7 @@ function getCertificatesRequiredSignKeys(
if (!voter) {
throw new Error('unexpectedly missing voter');
}
const keyHash = voter.to_drep_cred()?.to_keyhash();
const keyHash = voter.to_drep_credential()?.to_keyhash();
if (keyHash) {
result.add(keyHash.to_hex());
}
Expand Down
Loading
Loading