Skip to content

Commit

Permalink
Refactor keychain to use window.controller
Browse files Browse the repository at this point in the history
  • Loading branch information
tarrencev committed Oct 9, 2024
1 parent 76cace2 commit dfa4bad
Show file tree
Hide file tree
Showing 45 changed files with 281 additions and 413 deletions.
2 changes: 1 addition & 1 deletion docs/docs/controller/examples/svelte.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ Use the `connect` method to establish a connection:
try {
const res = await controller.connect();
if (res) {
account.set(controller.account);
account.set(controller);
username.set(await controller.username());
}
} catch (e) {
Expand Down
2 changes: 1 addition & 1 deletion examples/get-starknet/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const Main = () => {

const onConnect = useCallback(async () => {
const controller = await connect();
setAccount(controller.account);
setAccount(controller);
}, []);

const onIncrement = useCallback(() => {
Expand Down
2 changes: 1 addition & 1 deletion examples/svelte/src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
try {
const res = await controller.connect();
if (res) {
account.set(controller.account);
account.set(controller);
username.set(await controller.username());
}
} catch (e) {
Expand Down
27 changes: 27 additions & 0 deletions packages/account-wasm/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,33 @@ impl CartridgeAccount {
}
}

#[wasm_bindgen(js_name = username)]
pub fn username(&self) -> String {
self.controller.username.clone()
}

#[wasm_bindgen(js_name = address)]
pub fn address(&self) -> String {
self.controller.address.to_hex_string()
}

#[wasm_bindgen(js_name = rpcUrl)]
pub fn rpc_url(&self) -> String {
self.controller.rpc_url.to_string()
}

#[wasm_bindgen(js_name = chainId)]
pub fn chain_id(&self) -> String {
self.controller.chain_id.to_string()
}

#[wasm_bindgen(js_name = disconnect)]
pub fn disconnect(&mut self) -> std::result::Result<(), JsControllerError> {
self.controller
.disconnect()
.map_err(JsControllerError::from)
}

#[wasm_bindgen(js_name = ownerGuid)]
pub fn owner_guid(&self) -> JsFelt {
JsFelt(self.controller.owner_guid())
Expand Down
12 changes: 8 additions & 4 deletions packages/account_sdk/src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,17 @@ mod controller_test;
#[derive(Clone)]
pub struct Controller {
pub(crate) app_id: String,
pub(crate) address: Felt,
pub(crate) chain_id: Felt,
pub address: Felt,
pub chain_id: Felt,
pub(crate) class_hash: Felt,
pub(crate) rpc_url: Url,
pub rpc_url: Url,
pub username: String,
pub(crate) salt: Felt,
provider: CartridgeJsonRpcProvider,
pub(crate) owner: Signer,
contract: Option<Box<abigen::controller::Controller<Self>>>,
pub factory: ControllerFactory,
pub(crate) storage: Storage,
pub storage: Storage,
nonce: Felt,
}

Expand Down Expand Up @@ -130,6 +130,10 @@ impl Controller {
self.factory.deploy_v1(self.salt)
}

pub fn disconnect(&mut self) -> Result<(), ControllerError> {
self.storage.clear().map_err(ControllerError::from)
}

pub fn contract(&self) -> &abigen::controller::Controller<Self> {
self.contract.as_ref().unwrap()
}
Expand Down
3 changes: 2 additions & 1 deletion packages/controller/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export default class Controller {
this.iframes.keychain,
) as AccountInterface;
} catch (e) {
console.log(e);
console.error(new NotReadyToConnect().message);
return;
}
Expand Down Expand Up @@ -245,7 +246,7 @@ export default class Controller {
}

private waitForKeychain({
timeout = 3000,
timeout = 5000,
interval = 100,
}:
| {
Expand Down
2 changes: 1 addition & 1 deletion packages/controller/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ type CartridgeID = string;
export type ControllerAccounts = Record<ContractAddress, CartridgeID>;

export interface Keychain {
probe(rpcUrl?: string): Promise<ProbeReply | ConnectError>;
probe(rpcUrl: string): Promise<ProbeReply | ConnectError>;
connect(
policies: Policy[],
rpcUrl: string,
Expand Down
36 changes: 0 additions & 36 deletions packages/keychain/__tests__/utils/migrations.test.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/keychain/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Controller } from "utils/controller";

declare global {
interface Window {
controller: Controller;
controller: Controller?;
}
}

Expand Down
12 changes: 5 additions & 7 deletions packages/keychain/src/components/ConfirmTransaction.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ const meta = {
parameters: {
connection: {
controller: {
account: {
estimateInvokeFee: () => ({
suggestedMaxFee: "100",
}),
hasSession: () => true,
session: () => true,
},
estimateInvokeFee: () => ({
suggestedMaxFee: "100",
}),
hasSession: () => true,
session: () => true,
},
context: {
origin: "http://localhost:3002",
Expand Down
2 changes: 1 addition & 1 deletion packages/keychain/src/components/ConfirmTransaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function ConfirmTransaction() {
const { controller, context, origin, policies, setContext } = useConnection();
const [policiesUpdated, setIsPoliciesUpdated] = useState<boolean>(false);
const ctx = context as ExecuteCtx;
const account = controller.account;
const account = controller;

const onSubmit = async (maxFee: bigint) => {
let { transaction_hash } = await account.execute(ctx.transactions, {
Expand Down
10 changes: 4 additions & 6 deletions packages/keychain/src/components/DeployController.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@ const meta = {
parameters: {
connection: {
controller: {
account: {
chainId: constants.StarknetChainId.SN_SEPOLIA as string,
callContract: () =>
Promise.resolve([num.toHex("2000000000000000000"), "0x0"]),
rpc: new RpcProvider({ nodeUrl: "https://api.cartridge/x/sepolia" }),
},
chainId: () => constants.StarknetChainId.SN_SEPOLIA as string,
callContract: () =>
Promise.resolve([num.toHex("2000000000000000000"), "0x0"]),
rpc: new RpcProvider({ nodeUrl: "https://api.cartridge/x/sepolia" }),
},
},
},
Expand Down
29 changes: 16 additions & 13 deletions packages/keychain/src/components/DeployController.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,7 @@ export function DeployController({
onClose: () => void;
ctrlError?: ControllerError;
}) {
const {
controller: { account },
chainName,
hasPrefundRequest,
} = useConnection();
const { controller, chainName, hasPrefundRequest } = useConnection();
const { deploySelf, isDeploying } = useDeploy();
const [deployHash, setDeployHash] = useState<string>();
const [error, setError] = useState<Error>();
Expand All @@ -39,19 +35,19 @@ export function DeployController({

useEffect(() => {
if (
account.chainId !== constants.StarknetChainId.SN_MAIN ||
controller.chainId() !== constants.StarknetChainId.SN_MAIN ||
!hasPrefundRequest ||
!feeEstimate
) {
return;
}

setAccountState("deploy");
}, [account.chainId, account.username, hasPrefundRequest, feeEstimate]);
}, [controller, hasPrefundRequest, feeEstimate]);

useEffect(() => {
if (deployHash) {
account
controller
.waitForTransaction(deployHash, {
retryInterval: 1000,
successStates: [
Expand All @@ -62,9 +58,9 @@ export function DeployController({
.then(() => setAccountState("deployed"))
.catch((e) => setError(e));
}
}, [deployHash, account]);
}, [deployHash, controller]);

const { balance, isLoading } = useBalance({ address: account.address });
const { balance, isLoading } = useBalance({ address: controller.address });
useEffect(() => {
if (!feeEstimate || accountState != "fund") return;

Expand Down Expand Up @@ -104,7 +100,8 @@ export function DeployController({
<Funding
title={
<>
Fund <b style={{ color: "brand.primary" }}>{account.username}</b>{" "}
Fund{" "}
<b style={{ color: "brand.primary" }}>{controller.username()}</b>{" "}
for deployment
</>
}
Expand Down Expand Up @@ -163,7 +160,10 @@ export function DeployController({
>
<Content alignItems="center">
{deployHash && (
<ExplorerLink chainId={account.chainId} txHash={deployHash} />
<ExplorerLink
chainId={controller.chainId()}
txHash={deployHash}
/>
)}
</Content>
<Footer>
Expand Down Expand Up @@ -195,7 +195,10 @@ export function DeployController({
>
<Content alignItems="center">
{deployHash && (
<ExplorerLink chainId={account.chainId} txHash={deployHash} />
<ExplorerLink
chainId={controller.chainId()}
txHash={deployHash}
/>
)}
</Content>
<Footer>
Expand Down
2 changes: 1 addition & 1 deletion packages/keychain/src/components/ExecutionContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function ExecutionContainer({
return;
}
try {
const est = await controller.account.estimateInvokeFee(
const est = await controller.estimateInvokeFee(
transactions,
transactionsDetail,
);
Expand Down
8 changes: 3 additions & 5 deletions packages/keychain/src/components/Funding.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@ const meta = {
controller: {
address:
"0x0000000000000000000000000000000000000000000000000000000000000000",
account: {
rpc: new RpcProvider({ nodeUrl: "https://api.cartridge/x/sepolia" }),
callContract: () =>
Promise.resolve([num.toHex("2000000000000000000"), "0x0"]),
},
rpc: new RpcProvider({ nodeUrl: "https://api.cartridge/x/sepolia" }),
callContract: () =>
Promise.resolve([num.toHex("2000000000000000000"), "0x0"]),
},
},
},
Expand Down
11 changes: 6 additions & 5 deletions packages/keychain/src/components/Funding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,15 @@ function FundingInner({ onComplete, title }: FundingInnerProps) {
contractAddress: ETH_CONTRACT_ADDRESS,
entrypoint: "approve",
calldata: CallData.compile({
recipient: controller.account.address,
recipient: controller.address,
amount: cairo.uint256(parseEther(ethAmount)),
}),
},
{
contractAddress: ETH_CONTRACT_ADDRESS,
entrypoint: "transfer",
calldata: CallData.compile({
recipient: controller.account.address,
recipient: controller.address,
amount: cairo.uint256(parseEther(ethAmount)),
}),
},
Expand Down Expand Up @@ -175,7 +175,8 @@ function FundingInner({ onComplete, title }: FundingInnerProps) {
title={
title || (
<>
Fund <b style={{ color: "brand.primary" }}>{controller.username}</b>
Fund{" "}
<b style={{ color: "brand.primary" }}>{controller.username()}</b>
</>
)
}
Expand Down Expand Up @@ -306,7 +307,7 @@ function ExternalWalletProvider({ children }: PropsWithChildren) {
return (
<StarknetConfig
chains={[sepolia, mainnet]}
provider={() => controller.account.rpc}
provider={() => controller}
connectors={connectors}
explorer={voyager}
>
Expand Down Expand Up @@ -408,7 +409,7 @@ function AmountSelection({

// useEffect(() => {
// fetchTokenInfo(prefunds).then(setTokens);
// }, [prefunds, controller.account.address]);
// }, [prefunds, controller.address]);

// const checkFunds = useCallback(async () => {
// setIsFetching(true);
Expand Down
6 changes: 3 additions & 3 deletions packages/keychain/src/components/Settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ export function Settings({ onLogout }: { onLogout: () => void }) {
<Content>
<VStack gap="30px" w="full">
{/* <VStack>
{controller.account.cartridge.hasSession(
controller.account.cartridge.session(),
{controller.cartridge.hasSession(
controller.cartridge.session(),
) ? (
<Text>Session active</Text>
) : (
Expand All @@ -96,7 +96,7 @@ export function Settings({ onLogout }: { onLogout: () => void }) {
<Button
onClick={() => {
// zzz not implemented
controller.account.cartridge.revokeSession();
controller.cartridge.revokeSession();
}}
>
Clear Session
Expand Down
2 changes: 1 addition & 1 deletion packages/keychain/src/components/SignMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function SignMessage({
const hostname = useMemo(() => new URL(origin).hostname, [origin]);

const onConfirm = useCallback(async () => {
const account = controller.account;
const account = controller;
const sig = await account.signMessage(typedData);
onSign(sig);
}, [controller, onSign, typedData]);
Expand Down
Loading

0 comments on commit dfa4bad

Please sign in to comment.