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

[ECO-2167] Rename all instances of _PK to _PRIVATE_KEY in favor of being more explicit about the key type #235

Merged
merged 4 commits into from
Sep 9, 2024
Merged
Changes from 3 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
2 changes: 1 addition & 1 deletion .github/workflows/ts-run-tests.yaml
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@
env:
NEXT_PUBLIC_MODULE_ADDRESS: |-
4bab58978ec1b1bef032eeb285ad47a6a9b997d646c19b598c35f46b26ff9ece
PUBLISHER_PK: |-
PUBLISHER_PRIVATE_KEY: |-
29479e9e5fe47ba9a8af509dd6da1f907510bcf8917bfb19b7079d8c63c0b720
START_LOCAL_NODE_FOR_TEST: 'true'
TS_DIR: 'src/typescript'
4 changes: 2 additions & 2 deletions src/docker/aptos-node/initialize-contract.sh
Original file line number Diff line number Diff line change
@@ -12,15 +12,15 @@ export BIG_MONEY_GUY="big_money_guy"
aptos init --profile $PUBLISHER \
--rest-url http://host.docker.internal:8080/v1 \
--faucet-url http://host.docker.internal:8081 \
--private-key $PUBLISHER_PK \
--private-key $PUBLISHER_PRIVATE_KEY \
--encoding hex \
--assume-yes \
--network custom

aptos init --profile $BIG_MONEY_GUY \
--rest-url http://host.docker.internal:8080/v1 \
--faucet-url http://host.docker.internal:8081 \
--private-key $BIG_MONEY_GUY_PK \
--private-key $BIG_MONEY_GUY_PRIVATE_KEY \
--encoding hex \
--assume-yes \
--network custom
4 changes: 2 additions & 2 deletions src/docker/compose.local.yaml
Original file line number Diff line number Diff line change
@@ -36,8 +36,8 @@ services:
context: '../../'
dockerfile: 'src/docker/aptos-node/Dockerfile'
environment:
PUBLISHER_PK: '${PUBLISHER_PK}'
BIG_MONEY_GUY_PK: '${BIG_MONEY_GUY_PK}'
PUBLISHER_PRIVATE_KEY: '${PUBLISHER_PRIVATE_KEY}'
BIG_MONEY_GUY_PRIVATE_KEY: '${BIG_MONEY_GUY_PRIVATE_KEY}'
EMOJICOIN_MODULE_ADDRESS: '${EMOJICOIN_MODULE_ADDRESS}'
depends_on:
aptos-node:
4 changes: 2 additions & 2 deletions src/docker/example.local.env
Original file line number Diff line number Diff line change
@@ -67,7 +67,7 @@ BROKER_PORT="3009"
# production or for any real value transactions.
# If you change this, local tests will fail unless you also change the
# corresponding `*_ADDRESS` values that are derived from this key.
PUBLISHER_PK="0xeaa964d1353b075ac63b0c5a0c1e92aa93355be1402f6077581e37e2a846105e"
PUBLISHER_PRIVATE_KEY="0xeaa964d1353b075ac63b0c5a0c1e92aa93355be1402f6077581e37e2a846105e"

# The caching time for server-side requests for the NextJS web application.
REVALIDATION_TIME="1"
@@ -81,4 +81,4 @@ HASH_SEED="some random string that is not public"
# The private key for the "big money guy", who sends transactions in tests.
# Corresponds to the address:
# 0xb168d5a1137a3254a9443459ae5b4959e8f5c835858f04e5a01fe133d237d00d
BIG_MONEY_GUY_PK="0xa5e11183d0c23b8c49b40dd71bba7fa0992aed9b89c42934a1bb8f6e4ccc4ec4"
BIG_MONEY_GUY_PRIVATE_KEY="0xa5e11183d0c23b8c49b40dd71bba7fa0992aed9b89c42934a1bb8f6e4ccc4ec4"
2 changes: 1 addition & 1 deletion src/typescript/.env.test
Original file line number Diff line number Diff line change
@@ -7,6 +7,6 @@ NEXT_PUBLIC_MODULE_ADDRESS="0x4bab58978ec1b1bef032eeb285ad47a6a9b997d646c19b598c
NEXT_PUBLIC_REWARDS_MODULE_ADDRESS="0x76044a237dcc3f71af75fb314f016e8032633587f7d70df4e70777f2b0221e75"

# Randomly generated private key for tests. This is only used in e2e tests and for script data generation.
PUBLISHER_PK="29479e9e5fe47ba9a8af509dd6da1f907510bcf8917bfb19b7079d8c63c0b720"
PUBLISHER_PRIVATE_KEY="29479e9e5fe47ba9a8af509dd6da1f907510bcf8917bfb19b7079d8c63c0b720"

INBOX_URL="http://localhost:3000"
2 changes: 1 addition & 1 deletion src/typescript/frontend/src/app/test/route.ts
Original file line number Diff line number Diff line change
@@ -10,6 +10,6 @@ export async function GET() {
const version = await aptos.getLedgerInfo().then((res) => res.ledger_version);
return new NextResponse(version.toString());
} catch {
return new NextResponse("", {status: 500});
return new NextResponse("", { status: 500 });
}
}
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@ export const PrettyHex = ({
text: prettifyHex(hex),
overdrive: false,
overflow: true,
speed: typeof scramble === "undefined" ? 0 : (scrambleProps.speed ?? 0.6),
speed: typeof scramble === "undefined" ? 0 : scrambleProps.speed ?? 0.6,
playOnMount: true,
...scrambleProps,
});
Original file line number Diff line number Diff line change
@@ -188,9 +188,7 @@ const Liquidity: React.FC<LiquidityProps> = ({ market, geoblocked }) => {
type={direction === "add" ? "number" : "text"}
disabled={direction === "remove"}
value={
direction === "add"
? liquidity
: (fmtCoin(removeLiquidityResult?.quote_amount) ?? "...")
direction === "add" ? liquidity : fmtCoin(removeLiquidityResult?.quote_amount) ?? "..."
}
></input>
</Column>
@@ -216,8 +214,8 @@ const Liquidity: React.FC<LiquidityProps> = ({ market, geoblocked }) => {
}}
value={
direction === "add"
? (fmtCoin(provideLiquidityResult?.base_amount) ?? "...")
: (fmtCoin(removeLiquidityResult?.base_amount) ?? "...")
? fmtCoin(provideLiquidityResult?.base_amount) ?? "..."
: fmtCoin(removeLiquidityResult?.base_amount) ?? "..."
}
type="text"
disabled
@@ -244,7 +242,7 @@ const Liquidity: React.FC<LiquidityProps> = ({ market, geoblocked }) => {
color: direction === "add" ? theme.colors.lightGray + "99" : "white",
}}
value={
direction === "add" ? (fmtCoin(provideLiquidityResult?.lp_coin_amount) ?? "...") : lp
direction === "add" ? fmtCoin(provideLiquidityResult?.lp_coin_amount) ?? "..." : lp
}
type={direction === "add" ? "text" : "number"}
onChange={(e) => setLP(e.target.value === "" ? "" : Number(e.target.value))}
@@ -354,7 +352,7 @@ const Liquidity: React.FC<LiquidityProps> = ({ market, geoblocked }) => {
<AptosInputLabel />

<Text textScale={{ _: "bodySmall", tablet: "bodyLarge" }} textTransform="uppercase">
{market ? (fmtCoin(market.cpammRealReservesQuote) ?? loadingComponent) : "-"}
{market ? fmtCoin(market.cpammRealReservesQuote) ?? loadingComponent : "-"}
</Text>
</Flex>

@@ -366,7 +364,7 @@ const Liquidity: React.FC<LiquidityProps> = ({ market, geoblocked }) => {
<EmojiInputLabel emoji={market ? market.symbol : "-"} />

<Text textScale={{ _: "bodySmall", tablet: "bodyLarge" }} textTransform="uppercase">
{market ? (fmtCoin(market.cpammRealReservesBase) ?? loadingComponent) : "-"}
{market ? fmtCoin(market.cpammRealReservesBase) ?? loadingComponent : "-"}
</Text>
</Flex>
</StyledAddLiquidityWrapper>
102 changes: 52 additions & 50 deletions src/typescript/frontend/src/components/pages/verify/VerifyPage.tsx
Original file line number Diff line number Diff line change
@@ -64,58 +64,60 @@ export const ClientVerifyPage: React.FC<{ geoblocked: boolean }> = ({ geoblocked

return (
<>
<div className="absolute top-0 left-0 w-[100dvw] h-[100dvh] bg-black z-50 overflow-hidden grid"
<div
className="absolute top-0 left-0 w-[100dvw] h-[100dvh] bg-black z-50 overflow-hidden grid"
style={{
gridTemplateRows: "19fr 1fr"
}}>
<div className="flex items-center justify-center w-full h-full">
<div className="flex flex-col justify-begin uppercase text-ec-blue gap-4 text-2xl">
{connected && verified === false && (
<motion.div
onMouseEnter={replayBack}
animate={{ x: 0, y: -60 }}
initial={{ x: 2000, y: -60 }}
className="absolute flex flex-row px-2.5 hover:cursor-pointer min-w-[12ch] top-[50%]"
onClick={() => {
setVerified(null);
disconnect();
}}
transition={{
type: "just",
duration: 0.3,
}}
>
<span>{"<<"}&nbsp;</span>
<span ref={backRef}>Back</span>
</motion.div>
)}
<ButtonWithConnectWalletFallback geoblocked={geoblocked} arrow={false}>
<div className="flex flex-row uppercase">
<span className="px-2.5">{"{"}</span>
<a
ref={ref}
href={process.env.NEXT_PUBLIC_GALXE_CAMPAIGN_REDIRECT}
onMouseEnter={replay}
{...EXTERNAL_LINK_PROPS}
/>
<span className="px-2.5">{"}"}</span>
</div>
</ButtonWithConnectWalletFallback>
</div>
</div>
<Flex justifyContent="center" className="w-[100dvw]">
<Link href={LINKS?.tos ?? ROUTES.notFound}>
<Text
textScale="display6"
$fontWeight="bold"
fontSize={{ _: "8px", tablet: "15px" }}
textTransform="uppercase"
py={{ _: "16px", tablet: "24px" }}
gridTemplateRows: "19fr 1fr",
}}
>
<div className="flex items-center justify-center w-full h-full">
<div className="flex flex-col justify-begin uppercase text-ec-blue gap-4 text-2xl">
{connected && verified === false && (
<motion.div
onMouseEnter={replayBack}
animate={{ x: 0, y: -60 }}
initial={{ x: 2000, y: -60 }}
className="absolute flex flex-row px-2.5 hover:cursor-pointer min-w-[12ch] top-[50%]"
onClick={() => {
setVerified(null);
disconnect();
}}
transition={{
type: "just",
duration: 0.3,
}}
>
TERMS OF USE
</Text>
</Link>
</Flex>
<span>{"<<"}&nbsp;</span>
<span ref={backRef}>Back</span>
</motion.div>
)}
<ButtonWithConnectWalletFallback geoblocked={geoblocked} arrow={false}>
<div className="flex flex-row uppercase">
<span className="px-2.5">{"{"}</span>
<a
ref={ref}
href={process.env.NEXT_PUBLIC_GALXE_CAMPAIGN_REDIRECT}
onMouseEnter={replay}
{...EXTERNAL_LINK_PROPS}
/>
<span className="px-2.5">{"}"}</span>
</div>
</ButtonWithConnectWalletFallback>
</div>
</div>
<Flex justifyContent="center" className="w-[100dvw]">
<Link href={LINKS?.tos ?? ROUTES.notFound}>
<Text
textScale="display6"
$fontWeight="bold"
fontSize={{ _: "8px", tablet: "15px" }}
textTransform="uppercase"
py={{ _: "16px", tablet: "24px" }}
>
TERMS OF USE
</Text>
</Link>
</Flex>
</div>
</>
);
Original file line number Diff line number Diff line change
@@ -77,9 +77,7 @@ const getMyPools = async ({
};

export const fetchFeaturedMarket = async () => {
const keys = [
"featured-market",
].map(String);
const keys = ["featured-market"].map(String);

const res = await cached(
() =>
6 changes: 3 additions & 3 deletions src/typescript/sdk/src/utils/misc.ts
Original file line number Diff line number Diff line change
@@ -186,14 +186,14 @@ export const truncateANSName = (input: string, numChars: number = 4): string =>
};

/**
* Takes an address or a name and formats it accordingly.
*/
* Takes an address or a name and formats it accordingly.
*/
export const formatDisplayName = (input: string) => {
if (AccountAddress.isValid({ input, strict: false }).valid) {
return `0x${truncateAddress(input).substring(2).toUpperCase()}`;
}
return truncateANSName(input);
}
};

export class Lazy<T> {
generator: () => T;
2 changes: 1 addition & 1 deletion src/typescript/sdk/src/utils/mock-data.ts
Original file line number Diff line number Diff line change
@@ -60,7 +60,7 @@ const { aptos, publisher } = getTestHelpers();

// const PUBLISHER = publisher;
const PUBLISHER = Account.fromPrivateKey({
privateKey: new Ed25519PrivateKey(process.env.PUBLISHER_PK!),
privateKey: new Ed25519PrivateKey(process.env.PUBLISHER_PRIVATE_KEY!),
});

if (!(NUM_TRADERS % CHUNK_SIZE === 0)) {
2 changes: 1 addition & 1 deletion src/typescript/sdk/tests/e2e/publish.test.ts
Original file line number Diff line number Diff line change
@@ -17,7 +17,7 @@ describe("tests publishing modules to a local network", () => {
const moduleName = "main";
const packageName = "template";
const publishResult = await publishPackage({
pk: publisher.privateKey,
privateKey: publisher.privateKey,
includedArtifacts: "none",
namedAddresses: {
[packageName]: publisher.accountAddress,
16 changes: 8 additions & 8 deletions src/typescript/sdk/tests/pre-test.js
Original file line number Diff line number Diff line change
@@ -5,8 +5,8 @@ const {
Inbox,
LocalNode,
publishForTest,
getPublisherPKForTest,
PK_PATH,
getTestPublisherPrivateKey,
PUBLISHER_PRIVATE_KEY_PATH,
PUBLISH_RES_PATH,
} = require("./utils");

@@ -20,14 +20,14 @@ module.exports = async function setup() {
const inbox = new Inbox();
await inbox.run();
}
fs.mkdirSync(path.dirname(PK_PATH), { recursive: true });
fs.mkdirSync(path.dirname(PUBLISHER_PRIVATE_KEY_PATH), { recursive: true });
fs.mkdirSync(path.dirname(PUBLISH_RES_PATH), { recursive: true });

const pk = await getPublisherPKForTest();
if (!pk) {
const privateKeyString = await getTestPublisherPrivateKey();
if (!privateKeyString) {
throw new Error("Please provide a private key for testing");
};
fs.writeFileSync(PK_PATH, pk);
const publishResult = JSON.stringify(await publishForTest(pk), null, 2);
}
fs.writeFileSync(PUBLISHER_PRIVATE_KEY_PATH, privateKeyString);
const publishResult = JSON.stringify(await publishForTest(privateKeyString), null, 2);
fs.writeFileSync(PUBLISH_RES_PATH, publishResult);
};
8 changes: 5 additions & 3 deletions src/typescript/sdk/tests/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -6,7 +6,9 @@ import { getAptosClient } from "./aptos-client";
import { type TestHelpers } from "./types";

export const TS_UNIT_TEST_DIR = path.join(getGitRoot(), "src/typescript/sdk/tests");
export const PK_PATH = path.resolve(path.join(TS_UNIT_TEST_DIR, ".tmp", ".pk"));
export const PUBLISHER_PRIVATE_KEY_PATH = path.resolve(
path.join(TS_UNIT_TEST_DIR, ".tmp", ".publisher_private_key")
);
export const PUBLISH_RES_PATH = path.resolve(
path.join(TS_UNIT_TEST_DIR, ".tmp", ".publish_result")
);
@@ -24,9 +26,9 @@ export const PUBLISH_RES_PATH = path.resolve(
export function getTestHelpers(): TestHelpers {
const { aptos } = getAptosClient();

const pk = fs.readFileSync(PK_PATH).toString();
const privateKeyString = fs.readFileSync(PUBLISHER_PRIVATE_KEY_PATH).toString();
const publisher = Account.fromPrivateKey({
privateKey: new Ed25519PrivateKey(Hex.fromHexString(pk).toUint8Array()),
privateKey: new Ed25519PrivateKey(Hex.fromHexString(privateKeyString).toUint8Array()),
});
const publishPackageResult = JSON.parse(fs.readFileSync(PUBLISH_RES_PATH).toString());

17 changes: 10 additions & 7 deletions src/typescript/sdk/tests/utils/load-priv-key.ts
Original file line number Diff line number Diff line change
@@ -2,26 +2,29 @@
import { Account, AccountAddress, Ed25519PrivateKey } from "@aptos-labs/ts-sdk";
import { VERCEL } from "../../src/const";

export const getPublisherPKForTest = async () => {
export const getTestPublisherPrivateKey = async () => {
if (VERCEL) {
throw new Error("This function should not be called in a Vercel deployment.");
}
// If the publisher private key is not set by now, throw an error.
if (!process.env.PUBLISHER_PK) {
console.warn("Missing PUBLISHER_PK environment variable for test, using the default value.");
process.env.PUBLISHER_PK = "29479e9e5fe47ba9a8af509dd6da1f907510bcf8917bfb19b7079d8c63c0b720";
if (!process.env.PUBLISHER_PRIVATE_KEY) {
console.warn(
"Missing PUBLISHER_PRIVATE_KEY environment variable for test, using the default value."
);
process.env.PUBLISHER_PRIVATE_KEY =
"29479e9e5fe47ba9a8af509dd6da1f907510bcf8917bfb19b7079d8c63c0b720";
}

const derivedAccount = Account.fromPrivateKey({
privateKey: new Ed25519PrivateKey(process.env.PUBLISHER_PK),
privateKey: new Ed25519PrivateKey(process.env.PUBLISHER_PRIVATE_KEY),
});
const derivedAddress = derivedAccount.accountAddress.toString();
const normalizedEnvAddress = AccountAddress.from(process.env.NEXT_PUBLIC_MODULE_ADDRESS!);

if (derivedAddress !== normalizedEnvAddress.toString()) {
const msg = `${derivedAddress} !== ${process.env.NEXT_PUBLIC_MODULE_ADDRESS}`;
throw new Error(`PUBLISHER_PK does not match NEXT_PUBLIC_MODULE_ADDRESS: ${msg}`);
throw new Error(`PUBLISHER_PRIVATE_KEY does not match NEXT_PUBLIC_MODULE_ADDRESS: ${msg}`);
}

return process.env.PUBLISHER_PK;
return process.env.PUBLISHER_PRIVATE_KEY;
};
19 changes: 12 additions & 7 deletions src/typescript/sdk/tests/utils/publish.ts
Original file line number Diff line number Diff line change
@@ -15,13 +15,18 @@ import { MAX_GAS_FOR_PUBLISH, ONE_APT, EMOJICOIN_DOT_FUN_MODULE_NAME } from "../
import { getGitRoot } from "./helpers";

export async function publishPackage(args: {
pk: PrivateKey;
privateKey: PrivateKey;
network: Network;
includedArtifacts: string | undefined;
namedAddresses: Record<string, AccountAddressInput>;
packageDirRelativeToRoot: string;
}): Promise<PublishPackageResult> {
const { pk, network, namedAddresses, packageDirRelativeToRoot: packageDirRelative } = args;
const {
privateKey,
network,
namedAddresses,
packageDirRelativeToRoot: packageDirRelative,
} = args;
const includedArtifacts = args.includedArtifacts || "none";

let aptosExecutableAvailable = true;
@@ -39,7 +44,7 @@ export async function publishPackage(args: {
.map(([name, address]) => `${name}=${address.toString()}`)
.join(",");

const pkString = new Hex(pk.toUint8Array()).toStringWithoutPrefix();
const privateKeyString = new Hex(privateKey.toUint8Array()).toStringWithoutPrefix();

const shellArgs = [
aptosExecutableAvailable ? "npx @aptos-labs/aptos-cli" : "aptos",
@@ -50,7 +55,7 @@ export async function publishPackage(args: {
...["--url", NetworkToNodeAPI[network]],
...["--package-dir", packageDir],
...["--included-artifacts", includedArtifacts],
...["--private-key", pkString],
...["--private-key", privateKeyString],
...["--encoding", "hex"],
"--assume-yes",
"--override-size-check",
@@ -106,10 +111,10 @@ function extractJsonFromText(originalCommand: string, text: string): ResultJSON
return null;
}

export async function publishForTest(pk: string): Promise<PublishPackageResult> {
export async function publishForTest(privateKeyString: string): Promise<PublishPackageResult> {
const { aptos } = getAptosClient();
const publisher = Account.fromPrivateKey({
privateKey: new Ed25519PrivateKey(Hex.fromHexString(pk).toUint8Array()),
privateKey: new Ed25519PrivateKey(Hex.fromHexString(privateKeyString).toUint8Array()),
});

let publisherBalance = await aptos.account
@@ -130,7 +135,7 @@ export async function publishForTest(pk: string): Promise<PublishPackageResult>
const moduleName = EMOJICOIN_DOT_FUN_MODULE_NAME;
const packageName = moduleName;
return publishPackage({
pk: publisher.privateKey,
privateKey: publisher.privateKey,
includedArtifacts: "none",
namedAddresses: {
[packageName]: publisher.accountAddress,