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

Support create vesting account msg #126

Merged
merged 19 commits into from
Jun 12, 2023
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
@@ -0,0 +1,80 @@
import { useAppContext } from "../../../context/AppContext";
import { printableCoins } from "../../../lib/displayHelpers";
import { TxMsgCreateVestingAccount } from "../../../types/txMsg";
import HashView from "../HashView";

interface TxMsgCreateVestingAccountDetailsProps {
readonly msg: TxMsgCreateVestingAccount;
}

const TxMsgCreateVestingAccountDetails = ({ msg }: TxMsgCreateVestingAccountDetailsProps) => {
const { state } = useAppContext();
const endTimeDateObj = new Date(msg.value.endTime.multiply(1000).toNumber());
const endTimeDate = endTimeDateObj.toLocaleDateString();
const endTimeHours = endTimeDateObj.toLocaleTimeString().slice(0, -3);

return (
<>
<li>
<h3>MsgCreateVestingAccount</h3>
</li>
<li>
<label>Amount:</label>
<div>{printableCoins(msg.value.amount, state.chain)}</div>
</li>
<li>
<label>From:</label>
<div title={msg.value.fromAddress}>
<HashView hash={msg.value.fromAddress} />
</div>
</li>
<li>
<label>To:</label>
<div title={msg.value.toAddress}>
<HashView hash={msg.value.toAddress} />
</div>
</li>
<li>
<label>End time:</label>
<div title={String(msg.value.endTime)}>
<p>
{endTimeDate} {endTimeHours}
</p>
</div>
</li>
<li>
<label>Delayed:</label>
<div title={String(msg.value.endTime)}>
<p>{msg.value.delayed ? "Yes" : "No"}</p>
</div>
</li>
<style jsx>{`
li:not(:has(h3)) {
background: rgba(255, 255, 255, 0.03);
padding: 6px 10px;
border-radius: 8px;
display: flex;
align-items: center;
}
li + li:nth-child(2) {
margin-top: 25px;
}
li + li {
margin-top: 10px;
}
li div {
padding: 3px 6px;
}
label {
font-size: 12px;
background: rgba(255, 255, 255, 0.1);
padding: 3px 6px;
border-radius: 5px;
display: block;
}
`}</style>
</>
);
};

export default TxMsgCreateVestingAccountDetails;
5 changes: 5 additions & 0 deletions components/dataViews/TransactionInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useAppContext } from "../../../context/AppContext";
import { printableCoins } from "../../../lib/displayHelpers";
import {
isTxMsgClaimRewards,
isTxMsgCreateVestingAccount,
isTxMsgDelegate,
isTxMsgRedelegate,
isTxMsgSend,
Expand All @@ -11,6 +12,7 @@ import {
import { DbTransaction } from "../../../types";
import StackableContainer from "../../layout/StackableContainer";
import TxMsgClaimRewardsDetails from "./TxMsgClaimRewardsDetails";
import TxMsgCreateVestingAccountDetails from "./TxMsgCreateVestingAccountDetails";
import TxMsgDelegateDetails from "./TxMsgDelegateDetails";
import TxMsgRedelegateDetails from "./TxMsgRedelegateDetails";
import TxMsgSendDetails from "./TxMsgSendDetails";
Expand Down Expand Up @@ -59,6 +61,9 @@ const TransactionInfo = ({ tx }: Props) => {
{isTxMsgSetWithdrawAddress(msg) ? (
<TxMsgSetWithdrawAddressDetails msg={msg} />
) : null}
{isTxMsgCreateVestingAccount(msg) ? (
<TxMsgCreateVestingAccountDetails msg={msg} />
) : null}
</StackableContainer>
))}
</StackableContainer>
Expand Down
190 changes: 190 additions & 0 deletions components/forms/CreateTxForm/MsgForm/MsgCreateVestingAccountForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import { Decimal } from "@cosmjs/math";
import { assert } from "@cosmjs/utils";
import { useEffect, useState } from "react";
import { MsgGetter } from "..";
import { useAppContext } from "../../../../context/AppContext";
import { timestampFromDatetimeLocal } from "../../../../lib/dateHelpers";
import { checkAddress, exampleAddress } from "../../../../lib/displayHelpers";
import { isTxMsgCreateVestingAccount } from "../../../../lib/txMsgHelpers";
import { TxMsg, TxMsgCreateVestingAccount } from "../../../../types/txMsg";
import Input from "../../../inputs/Input";
import StackableContainer from "../../../layout/StackableContainer";

/*
One month from now
With stripped seconds and milliseconds
Matching the crazy datetime-local input format
*/
const getMinEndTime = (): string => {
const minTimestamp = Date.now() + 1000 * 60 * 60 * 24 * 30;
const minDate = new Date(minTimestamp);

const minMonth = minDate.getMonth() + 1; // It's 0-indexed
const minMonthStr = minMonth < 10 ? `0${minMonth}` : String(minMonth);

const minDay = minDate.getDate();
const minDayStr = minDay < 10 ? `0${minDay}` : String(minDay);

const minHours = minDate.getHours();
const minHoursStr = minHours < 10 ? `0${minHours}` : String(minHours);

const minMinutes = minDate.getMinutes();
const minMinutesStr = minMinutes < 10 ? `0${minMinutes}` : String(minMinutes);

return `${minDate.getFullYear()}-${minMonthStr}-${minDayStr}T${minHoursStr}:${minMinutesStr}`;
};

interface MsgCreateVestingAccountFormProps {
readonly fromAddress: string;
readonly setMsgGetter: (msgGetter: MsgGetter) => void;
readonly deleteMsg: () => void;
}

const MsgCreateVestingAccountForm = ({
fromAddress,
setMsgGetter,
deleteMsg,
}: MsgCreateVestingAccountFormProps) => {
const { state } = useAppContext();
assert(state.chain.addressPrefix, "addressPrefix missing");

const [toAddress, setToAddress] = useState("");
const [amount, setAmount] = useState("0");
const minEndTime = getMinEndTime();
const [endTime, setEndTime] = useState(minEndTime);
const [delayed, setDelayed] = useState(true);

const [toAddressError, setToAddressError] = useState("");
const [amountError, setAmountError] = useState("");
const [endTimeError, setEndTimeError] = useState("");

useEffect(() => {
try {
assert(state.chain.denom, "denom missing");

setToAddressError("");
setAmountError("");
setEndTimeError("");

const isMsgValid = (msg: TxMsg): msg is TxMsgCreateVestingAccount => {
assert(state.chain.addressPrefix, "addressPrefix missing");

const addressErrorMsg = checkAddress(toAddress, state.chain.addressPrefix);
if (addressErrorMsg) {
setToAddressError(
`Invalid address for network ${state.chain.chainId}: ${addressErrorMsg}`,
);
return false;
}

if (!amount || Number(amount) <= 0) {
setAmountError("Amount must be greater than 0");
return false;
}

if (!endTime) {
setEndTimeError("End time is required");
return false;
}

return isTxMsgCreateVestingAccount(msg);
};

const amountInAtomics = amount
? Decimal.fromUserInput(amount, Number(state.chain.displayDenomExponent)).atomics
: "0";

const msg: TxMsgCreateVestingAccount = {
typeUrl: "/cosmos.vesting.v1beta1.MsgCreateVestingAccount",
value: {
fromAddress,
toAddress,
amount: [{ amount: amountInAtomics, denom: state.chain.denom }],
endTime: timestampFromDatetimeLocal(endTime),
delayed,
Comment on lines +100 to +104
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you pull this out into a const createMsgValue: MsgCreateVestingAccount = { ... to ensure we have type-safety for that part?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, you have that in TxMsgCreateVestingAccount. Never mind then.

},
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This msg looks alright here. You can add type-dafety if you store the value: MsgCreateVestingAccount in an extra line.

But how does the object look like when it was written to Fauna and read from Fauna as part of the signing process? I'd assume this breaks the Long.

      const {
        data: { transactionID },
      } = await axios.post("/api/transaction", {
        dataJSON: JSON.stringify(tx),
      });

writed the whole tx including the messages to JSON. There it looks like this:

> const Long = require("long")
undefined
> Long.fromNumber(123)
Long { low: 123, high: 0, unsigned: false }
> let a = { endTime: Long.fromNumber(123) }
undefined
> JSON.stringify(a)
'{"endTime":{"low":123,"high":0,"unsigned":false}}'

Then in const txInfo: DbTransaction = transactionJSON ? JSON.parse(transactionJSON) : null; this becomes something like

JSON.parse('{"endTime":{"low":123,"high":0,"unsigned":false}}')
{ endTime: { low: 123, high: 0, unsigned: false } }.

I'm a bit surprised the proto encoding does not fail entirely.

How does props.tx.msgs look like in this code block?

      const { bodyBytes, signatures } = await signingClient.sign(
        signerAddress,
        props.tx.msgs,
        props.tx.fee,
        props.tx.memo,
        signerData,
      );

Copy link
Contributor Author

@abefernan abefernan Jun 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

props.tx.msgs looks like this:

image

I checked that only the methods go away in serialization, so when reading the tx from db I re-build the Long obj with Long.fromValue to be able to use longObj.multiply(1000)


setMsgGetter({ isMsgValid, msg });
} catch {}
}, [
amount,
delayed,
endTime,
fromAddress,
setMsgGetter,
state.chain.addressPrefix,
state.chain.chainId,
state.chain.denom,
state.chain.displayDenomExponent,
toAddress,
]);

return (
<StackableContainer lessPadding lessMargin>
<button className="remove" onClick={() => deleteMsg()}>
</button>
<h2>MsgCreateVestingAccount</h2>
<div className="form-item">
<Input
label="Recipient Address"
name="recipient-address"
value={toAddress}
onChange={({ target }) => setToAddress(target.value)}
error={toAddressError}
placeholder={`E.g. ${exampleAddress(0, state.chain.addressPrefix)}`}
/>
</div>
<div className="form-item">
<Input
type="number"
label={`Amount (${state.chain.displayDenom})`}
name="amount"
value={amount}
onChange={({ target }) => setAmount(target.value)}
error={amountError}
/>
</div>
<div className="form-item">
<Input
type="datetime-local"
label="End time"
name="end-time"
value={endTime}
min={minEndTime}
onChange={({ target }) => setEndTime(target.value)}
error={endTimeError}
/>
</div>
<div className="form-item">
<Input
type="checkbox"
label="Delayed"
name="delayed"
checked={delayed}
value={String(delayed)}
onChange={({ target }) => setDelayed(target.checked)}
/>
</div>
<style jsx>{`
.form-item {
margin-top: 1.5em;
}
button.remove {
background: rgba(255, 255, 255, 0.2);
width: 30px;
height: 30px;
border-radius: 50%;
border: none;
color: white;
position: absolute;
right: 10px;
top: 10px;
}
`}</style>
</StackableContainer>
);
};

export default MsgCreateVestingAccountForm;
3 changes: 3 additions & 0 deletions components/forms/CreateTxForm/MsgForm/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { MsgGetter } from "..";
import { MsgType } from "../../../../types/txMsg";
import MsgClaimRewardsForm from "./MsgClaimRewardsForm";
import MsgCreateVestingAccountForm from "./MsgCreateVestingAccountForm";
import MsgDelegateForm from "./MsgDelegateForm";
import MsgRedelegateForm from "./MsgRedelegateForm";
import MsgSendForm from "./MsgSendForm";
Expand Down Expand Up @@ -28,6 +29,8 @@ const MsgForm = ({ msgType, senderAddress, ...restProps }: MsgFormProps) => {
return <MsgClaimRewardsForm delegatorAddress={senderAddress} {...restProps} />;
case "setWithdrawAddress":
return <MsgSetWithdrawAddressForm delegatorAddress={senderAddress} {...restProps} />;
case "createVestingAccount":
return <MsgCreateVestingAccountForm fromAddress={senderAddress} {...restProps} />;
default:
return null;
}
Expand Down
4 changes: 4 additions & 0 deletions components/forms/CreateTxForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ const CreateTxForm = ({ router, senderAddress, accountOnChain }: CreateTxFormPro
label="Add MsgSetWithdrawAddress"
onClick={() => addMsgType("setWithdrawAddress")}
/>
<Button
label="Add MsgCreateVestingAccount"
onClick={() => addMsgType("createVestingAccount")}
/>
</StackableContainer>
<Button
label="Create Transaction"
Expand Down
6 changes: 5 additions & 1 deletion components/forms/TransactionSigning.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MultisigThresholdPubkey, makeCosmoshubPath } from "@cosmjs/amino";
import { toBase64 } from "@cosmjs/encoding";
import { toBase64, toHex } from "@cosmjs/encoding";
import { LedgerSigner } from "@cosmjs/ledger-amino";
import { SigningStargateClient } from "@cosmjs/stargate";
import { assert } from "@cosmjs/utils";
Expand Down Expand Up @@ -155,6 +155,8 @@ const TransactionSigning = (props: Props) => {
chainId: state.chain.chainId,
};

console.log({ msgs: props.tx.msgs });

const { bodyBytes, signatures } = await signingClient.sign(
signerAddress,
props.tx.msgs,
Expand All @@ -163,6 +165,8 @@ const TransactionSigning = (props: Props) => {
signerData,
);

console.log({ bodyBytes: toHex(bodyBytes) });

// check existing signatures
const bases64EncodedSignature = toBase64(signatures[0]);
const bases64EncodedBodyBytes = toBase64(bodyBytes);
Expand Down
Loading