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

Expose iframe close method from controller side #332

Merged
merged 2 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Move connector logic to utils
  • Loading branch information
JunichiSugiura committed Jun 3, 2024
commit 01afd372917a05217a664d416fd772ad1f4e7545
2 changes: 1 addition & 1 deletion packages/keychain/src/components/Auth/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { constants } from "starknet";
import Controller from "utils/controller";
import { ConnectCtx } from "hooks/connection";
import { ConnectCtx } from "utils/connection";

export type FormValues = {
username: string;
Expand Down
247 changes: 3 additions & 244 deletions packages/keychain/src/hooks/connection.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
AsyncMethodReturns,
connectToParent,
} from "@cartridge/penpal";
import {
useContext,
Expand All @@ -10,74 +9,12 @@ import {
PropsWithChildren,
useCallback,
} from "react";
import Controller from "utils/controller";
import {
ConnectReply,
ExecuteReply,
Policy,
ProbeReply,
ResponseCodes,
Session,
ConnectError,
} from "@cartridge/controller";
import Controller, { diff } from "utils/controller";
import {
Abi,
Call,
InvocationsDetails,
Signature,
TypedData,
addAddressPadding,
constants,
} from "starknet";
import { normalize, validate } from "../methods";
import { estimateDeclareFee, estimateInvokeFee } from "../methods/estimate";
import logout from "../methods/logout";
import { revoke, session, sessions } from "../methods/sessions";
import { username } from "../methods/username";
import { connectToController, ConnectionCtx } from "utils/connection";
import { useController } from "./controller";
import { Status } from "utils/account";

export type ConnectionCtx =
| ConnectCtx
| LogoutCtx
| ExecuteCtx
| SignMessageCtx;

export type ConnectCtx = {
origin: string;
type: "connect";
policies: Policy[];
resolve: (res: ConnectReply | ConnectError) => void;
reject: (reason?: unknown) => void;
};

export type LogoutCtx = {
origin: string;
type: "logout";
resolve: (res: ConnectError) => void;
reject: (reason?: unknown) => void;
};

export type ExecuteCtx = {
origin: string;
type: "execute";
transactions: Call | Call[];
abis?: Abi[];
transactionsDetail?: InvocationsDetails & {
chainId?: constants.StarknetChainId;
};
resolve: (res: ExecuteReply | ConnectError) => void;
reject: (reason?: unknown) => void;
};

export type SignMessageCtx = {
origin: string;
type: "sign-message";
typedData: TypedData;
account: string;
resolve: (signature: Signature | ConnectError) => void;
reject: (reason?: unknown) => void;
};

const ConnectionContext = createContext<ConnectionContextValue>(undefined);

Expand All @@ -103,185 +40,7 @@ export function ConnectionProvider({ children }: PropsWithChildren) {
return;
}

const connection = connectToParent({
methods: {
connect: normalize(
(origin: string) =>
async (
policies: Policy[],
chainId?: constants.StarknetChainId,
): Promise<ConnectReply> => {
return await new Promise((resolve, reject) => {
if (chainId) {
setChainId(chainId);
}
setContext({
type: "connect",
origin,
policies,
resolve,
reject,
} as ConnectCtx);
});
},
),
disconnect: normalize(
validate((controller: Controller, _origin: string) => () => {
controller.delete();
setController(undefined);
}),
),
execute: normalize(
validate(
(controller: Controller, origin: string) =>
async (
transactions: Call | Call[],
abis?: Abi[],
transactionsDetail?: InvocationsDetails & {
chainId?: constants.StarknetChainId;
},
sync?: boolean,
): Promise<ExecuteReply | ConnectError> => {
const cId = transactionsDetail?.chainId
? transactionsDetail.chainId
: chainId;
if (sync) {
return await new Promise((resolve, reject) => {
setContext({
type: "execute",
origin,
transactions,
abis,
transactionsDetail,
resolve,
reject,
} as ExecuteCtx);
});
}
const account = controller.account(cId);
if (account.status === Status.DEPLOYING) {
return Promise.resolve({
code: ResponseCodes.NOT_ALLOWED,
message: "Account is deploying.",
});
}

const calls = Array.isArray(transactions)
? transactions
: [transactions];
const policies = calls.map(
(txn) =>
({
target: addAddressPadding(txn.contractAddress),
method: txn.entrypoint,
} as Policy),
);

const session = controller.session(origin, cId);
if (!session) {
return Promise.resolve({
code: ResponseCodes.NOT_ALLOWED,
message: `No session`,
});
}

const missing = diff(policies, session.policies);
if (missing.length > 0) {
return Promise.resolve({
code: ResponseCodes.NOT_ALLOWED,
message: `Missing policies: ${JSON.stringify(missing)}`,
});
}

if (!transactionsDetail.maxFee) {
try {
const estFee = await account.estimateInvokeFee(calls, {
nonce: transactionsDetail.nonce,
});

transactionsDetail.maxFee = estFee.suggestedMaxFee;
} catch (e) {
return Promise.resolve({
code: ResponseCodes.NOT_ALLOWED,
message: e.message,
});
}
}

if (
session.maxFee &&
transactionsDetail &&
BigInt(transactionsDetail.maxFee) > BigInt(session.maxFee)
) {
return Promise.resolve({
code: ResponseCodes.NOT_ALLOWED,
message: `Max fee exceeded: ${transactionsDetail.maxFee.toString()} > ${session.maxFee.toString()}`,
});
}

try {
const res = await account.execute(
calls,
session,
transactionsDetail,
);

return {
code: ResponseCodes.SUCCESS,
...res,
};
} catch (e) {
return {
code: ResponseCodes.NOT_ALLOWED,
message: e.message,
};
}
},
),
),
estimateDeclareFee: normalize(validate(estimateDeclareFee)),
estimateInvokeFee: normalize(validate(estimateInvokeFee)),
logout: normalize(logout),
probe: normalize(
validate(
(controller: Controller, origin: string) => (): ProbeReply => {
const session = controller.session(origin, chainId);
return {
code: ResponseCodes.SUCCESS,
address: controller.address,
policies: session?.policies || [],
};
},
),
),
revoke: normalize(revoke),
signMessage: normalize(
validate(
(_: Controller, origin: string) =>
async (typedData: TypedData, account: string) => {
return await new Promise((resolve, reject) => {
setContext({
type: "sign-message",
origin,
typedData,
account,
resolve,
reject,
} as SignMessageCtx);
});
},
),
),
session: normalize(
(origin: string) => async (): Promise<Session> =>
await new Promise(() => session(origin, chainId)),
),
sessions: normalize(sessions),
reset: normalize(() => () => setContext(undefined)),
username: normalize(username),
},
});

const connection = connectToController({ chainId, setChainId, setContext, setController });
connection.promise.then(parent => setParent(parent as unknown as ParentMethods))

return () => {
Expand Down
26 changes: 0 additions & 26 deletions packages/keychain/src/methods/index.ts

This file was deleted.

18 changes: 0 additions & 18 deletions packages/keychain/src/methods/logout.ts

This file was deleted.

42 changes: 0 additions & 42 deletions packages/keychain/src/methods/sessions.ts

This file was deleted.

12 changes: 6 additions & 6 deletions packages/keychain/src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { NextPage } from "next";
import dynamic from "next/dynamic";
import { diff } from "utils/controller";
import { ResponseCodes, ExecuteReply } from "@cartridge/controller";
import { useState } from "react";
import { Signature } from "starknet";
import { ResponseCodes, ExecuteReply } from "@cartridge/controller";
import {
Connect,
DeploymentRequired,
Expand All @@ -12,16 +12,16 @@ import {
SignMessage,
Signup,
} from "components";
import { useConnection, } from 'hooks/connection'
import {
ConnectionCtx,
ConnectCtx,
ExecuteCtx,
LogoutCtx,
SignMessageCtx,
useConnection,
} from "hooks/connection";
import { useState } from "react";
import logout from "methods/logout";
} from "utils/connection";
import { diff } from "utils/controller";
import { logout } from "utils/connection/logout";

const Index: NextPage = () => {
const [showSignup, setShowSignup] = useState(false);
Expand Down
Loading
Loading