Skip to content

Commit

Permalink
Register Session connector
Browse files Browse the repository at this point in the history
  • Loading branch information
tarrencev committed Jan 14, 2025
1 parent cec808a commit 9e4e20d
Show file tree
Hide file tree
Showing 17 changed files with 182 additions and 133 deletions.
14 changes: 13 additions & 1 deletion examples/next/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,21 @@ const nextConfig = {
: "static/wasm/[modulehash].wasm";

// Since Webpack 5 doesn't enable WebAssembly by default, we should do it manually
config.experiments = { ...config.experiments, asyncWebAssembly: true };
config.experiments = {
...config.experiments,
asyncWebAssembly: true,
layers: true,
};

// Add WASM file handling
config.module.rules.push({
test: /\.wasm$/,
type: "webassembly/async",
});

return config;
},
output: "standalone",
};

module.exports = nextConfig;
8 changes: 4 additions & 4 deletions examples/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"version": "0.5.8",
"scripts": {
"dev": "next dev -p 3002",
"build": "next build",
"build": "NEXT_TELEMETRY_DISABLED=1 next build",
"e2e": "playwright test",
"e2e:ui": "playwright test --ui",
"start": "next start -p 3002",
Expand All @@ -18,7 +18,7 @@
"@cartridge/ui-next": "workspace:*",
"@starknet-react/chains": "^0.1.3",
"@starknet-react/core": "^3.0.2",
"next": "^14.2.5",
"next": "^14.2.15",
"next-themes": "^0.3.0",
"prettier": "^2.7.1",
"react": "^18.3.1",
Expand All @@ -33,10 +33,10 @@
"@types/react-dom": "^18.3.1",
"autoprefixer": "^10.4.18",
"eslint": "^8.23.0",
"eslint-config-next": "^12.2.5",
"eslint-config-next": "^14.2.15",
"postcss": "^8.4.35",
"postcss-import": "^16.1.0",
"tailwindcss": "^3.4.3",
"typescript": "^5.4.5"
}
}
}
142 changes: 71 additions & 71 deletions examples/next/src/app/token/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
import {
useAccount,
useReadContract,
useSendTransaction,
// useSendTransaction,
} from "@starknet-react/core";
import { useCallback, useMemo, useState } from "react";
import { useMemo } from "react";
import { cairo, uint256 } from "starknet";
import { ConnectWallet } from "components/ConnectWallet";
import { useTokenContract } from "hooks/token";
// import { useTokenContract } from "hooks/token";
import { Abi } from "starknet";
import Erc20Abi from "abi/erc20.json";
import { Button, Input } from "@cartridge/ui-next";
// import { Button, Input } from "@cartridge/ui-next";

function UserBalance() {
const { account } = useAccount();
Expand Down Expand Up @@ -46,72 +46,72 @@ function UserBalance() {
);
}

function MintToken() {
const { account, address } = useAccount();
const [amount, setAmount] = useState("");
const [amountError, setAmountError] = useState<string | undefined>();

const { contract } = useTokenContract();

const calls = useMemo(() => {
if (!address || !contract) return [];

const amountBn = cairo.uint256(amount);
return contract.populateTransaction["mint"]!(address, [address, amountBn]);
}, [address, contract, amount]);

const { sendAsync, isPending, error, reset } = useSendTransaction({
calls,
});

const updateAmount = useCallback(
(newAmount: string) => {
// soft-validate amount
setAmount(newAmount);
try {
BigInt(newAmount);
setAmountError(undefined);
} catch (err) {
console.error(err);
setAmountError("Please input a valid number");
}
},
[setAmount],
);

const onMint = useCallback(() => {
reset();
if (account && !amountError) {
sendAsync();
}
}, [account, amountError, reset, sendAsync]);

const mintButtonDisabled = useMemo(() => {
if (isPending) return true;
return !account || !!amountError;
}, [isPending, account, amountError]);

return (
<div>
<h2>Mint token</h2>
<p>
<span>Amount: </span>
<Input
type="number"
onChange={(evt) => updateAmount(evt.target.value)}
/>
</p>
<Button disabled={mintButtonDisabled} onClick={onMint}>
{isPending ? "Submitting" : "Mint"}
</Button>
{error && (
<p>
<>Error: {error}</>
</p>
)}
</div>
);
}
// function MintToken() {
// const { account, address } = useAccount();
// const [amount, setAmount] = useState("");
// const [amountError, setAmountError] = useState<string | undefined>();

// const { contract } = useTokenContract();

// const calls = useMemo(() => {
// if (!address || !contract) return [];

// const amountBn = cairo.uint256(amount);
// return [contract.populateTransaction["mint"](address, [address, amountBn])];
// }, [address, contract, amount]);

// const { sendAsync, isPending, error, reset } = useSendTransaction({
// calls,
// });

// const updateAmount = useCallback(
// (newAmount: string) => {
// // soft-validate amount
// setAmount(newAmount);
// try {
// BigInt(newAmount);
// setAmountError(undefined);
// } catch (err) {
// console.error(err);
// setAmountError("Please input a valid number");
// }
// },
// [setAmount],
// );

// const onMint = useCallback(() => {
// reset();
// if (account && !amountError) {
// sendAsync();
// }
// }, [account, amountError, reset, sendAsync]);

// const mintButtonDisabled = useMemo(() => {
// if (isPending) return true;
// return !account || !!amountError;
// }, [isPending, account, amountError]);

// return (
// <div>
// <h2>Mint token</h2>
// <p>
// <span>Amount: </span>
// <Input
// type="number"
// onChange={(evt) => updateAmount(evt.target.value)}
// />
// </p>
// <Button disabled={mintButtonDisabled} onClick={onMint}>
// {isPending ? "Submitting" : "Mint"}
// </Button>
// {error && (
// <p>
// <>Error: {error}</>
// </p>
// )}
// </div>
// );
// }

export default function TokenPage() {
const { address } = useAccount();
Expand All @@ -128,7 +128,7 @@ export default function TokenPage() {
<div>
<p>Connected: {address}</p>
<UserBalance />
<MintToken />
{/* <MintToken /> */}
</div>
);
}
11 changes: 0 additions & 11 deletions examples/next/src/components/ConnectWallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,6 @@ export function ConnectWallet() {
dragRef.current = undefined;
};

const registerSessionUrl =
"http://localhost:3001/session?public_key=0x2cb057c18198ae4555a144bfdace051433b9a545dc88224de58fa04e323f269&redirect_uri=http://localhost:3002&policies=%5B%7B%22target%22:%220x03661Ea5946211b312e8eC71B94550928e8Fd3D3806e43c6d60F41a6c5203645%22,%22method%22:%22attack%22,%22description%22:%22Attack%20the%20beast%22%7D,%7B%22target%22:%220x03661Ea5946211b312e8eC71B94550928e8Fd3D3806e43c6d60F41a6c5203645%22,%22method%22:%22claim%22,%22description%22:%22Claim%20your%20tokens%22%7D%5D&rpc_url=http://localhost:8001/x/starknet/sepolia";

const openRegisterSessionUrl = () => {
window.open(registerSessionUrl, "_blank", "noopener,noreferrer");
};

return (
<div
style={{ position: "relative" }}
Expand All @@ -77,10 +70,6 @@ export function ConnectWallet() {
<Button onClick={() => connect({ connector: controller })}>
Connect
</Button>
{/* <Button onClick={() => connect({ connector: session })}>
Create Session
</Button> */}
<Button onClick={openRegisterSessionUrl}>Register Session</Button>
</div>
)}

Expand Down
25 changes: 18 additions & 7 deletions examples/next/src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ const Header = () => {
const networkRef = useRef<HTMLDivElement>(null);
const profileRef = useRef<HTMLDivElement>(null);

const sessionConnector = connectors.find(
(c) => c.id === "controller_session",
);

useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
Expand Down Expand Up @@ -132,13 +136,20 @@ const Header = () => {
)}
</div>
) : (
<Button
onClick={() => {
connect({ connector: connectors[0] });
}}
>
Connect
</Button>
<div className="flex gap-2">
<Button
onClick={() => {
connect({ connector: connectors[0] });
}}
>
Connect
</Button>
{sessionConnector && (
<Button onClick={() => connect({ connector: sessionConnector })}>
Register Session
</Button>
)}
</div>
)}
</div>
);
Expand Down
10 changes: 9 additions & 1 deletion examples/next/src/components/providers/StarknetProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { PropsWithChildren } from "react";
import ControllerConnector from "@cartridge/connector/controller";
import { SessionPolicies } from "@cartridge/controller";
import { constants } from "starknet";
import SessionConnector from "@cartridge/connector/session";

export const ETH_CONTRACT_ADDRESS =
"0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7";
Expand Down Expand Up @@ -103,7 +104,7 @@ export function StarknetProvider({ children }: PropsWithChildren) {
<StarknetConfig
autoConnect
chains={[mainnet, sepolia]}
connectors={[controller]}
connectors={[controller, session]}
explorer={starkscan}
provider={provider}
>
Expand Down Expand Up @@ -137,3 +138,10 @@ const controller = new ControllerConnector({
],
},
});

const session = new SessionConnector({
policies,
rpc: process.env.NEXT_PUBLIC_RPC_SEPOLIA!,
chainId: constants.StarknetChainId.SN_SEPOLIA,
redirectUrl: typeof window !== "undefined" ? window.location.origin : "",
});
28 changes: 13 additions & 15 deletions examples/next/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,21 @@
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@cartridge/tsconfig/react.json",
"compilerOptions": {
"plugins": [{ "name": "next" }],
"paths": {
"@/*": ["./src/*"]
},
"baseUrl": "./src",
"allowJs": true,
"strict": true,
"noEmit": true,
"plugins": [
{
"name": "next"
}
],
"incremental": true,
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules",
"tests"
]
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"tsup": "^8.0.1",
"turbo": "^2.0.12",
"vercel": "^37.4.2",
"@types/react": "^18.3.12"
"@types/react": "^18.3.12",
"typescript": "^5.4.5"
}
}
2 changes: 1 addition & 1 deletion packages/account_sdk/src/signers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub enum SignError {
#[error("No allowed session methods error")]
NoAllowedSessionMethods,

#[error("Session policy not allowed error{0}")]
#[error("Session policy not allowed error: {0}")]
SessionPolicyNotAllowed(SessionPolicyError),

#[error("Invalid message provided: {0}")]
Expand Down
3 changes: 2 additions & 1 deletion packages/connector/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"tsup": {
"entry": [
"src/controller.ts",
"src/session.ts",
"src/index.ts"
],
"format": [
Expand All @@ -53,4 +54,4 @@
"@cartridge/tsconfig": "workspace:*",
"typescript": "^5.4.5"
}
}
}
Loading

0 comments on commit 9e4e20d

Please sign in to comment.