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

feat: integrate zkLogin #7

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions .changeset/swift-bottles-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"porto": minor
---

feat: add zkLogin backup method
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
[submodule "contracts/lib/solady"]
path = contracts/lib/solady
url = https://github.com/Vectorized/solady
[submodule "contracts/lib/zklogin"]
path = contracts/lib/zklogin
url = https://github.com/shield-labs-xyz/zklogin
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"typescript.enablePromptUseWorkspaceTsdk": true,
"javascript.preferences.autoImportFileExcludePatterns": ["**/index.js"],
"typescript.preferences.autoImportFileExcludePatterns": ["**/index.js"],
"solidity.formatter": "forge",
"[json]": {
"editor.defaultFormatter": "biomejs.biome"
},
Expand Down
3 changes: 2 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"src/generated.ts",
"tsconfig.json",
"tsconfig.*.json"
]
],
"maxSize": 99999999
},
"organizeImports": {
"enabled": true
Expand Down
3 changes: 2 additions & 1 deletion contracts/foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ libs = ["lib"]
remappings = [
"forge-std/=lib/forge-std/src",
"solady/=lib/solady/src",
"zklogin/=lib/zklogin/packages/contracts/contracts",
]
via_ir = true
# via_ir = true # disabled due to Noir solidity verifier failing to compile
evm_version = "prague"
alphanet = true

Expand Down
1 change: 1 addition & 0 deletions contracts/lib/zklogin
Submodule zklogin added at a506d7
31 changes: 30 additions & 1 deletion contracts/src/account/ExperimentalDelegation.sol
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pragma solidity ^0.8.23;

import {Receiver} from "solady/accounts/Receiver.sol";
import {UUPSUpgradeable} from "solady/utils/UUPSUpgradeable.sol";
import {ZkLogin} from "zklogin/ZkLogin.sol";

import {MultiSendCallOnly} from "../utils/MultiSend.sol";
import {ECDSA} from "../utils/ECDSA.sol";
Expand Down Expand Up @@ -79,6 +80,8 @@ contract ExperimentalDelegation is Receiver, MultiSendCallOnly {
/// @notice Authorization nonce used for replay protection.
uint256 public nonce;

ZkLogin.AccountData public zkLoginAccount;

/// @notice Initializes the EOA with a public key to authorize.
/// @param label_ - The label to associate with the EOA.
/// @param keys_ - The keys to authorize.
Expand Down Expand Up @@ -151,6 +154,32 @@ contract ExperimentalDelegation is Receiver, MultiSendCallOnly {
keys[keyIndex].expiry = 1;
}

function zkLoginAddBackup(ZkLogin.AccountData calldata data) public onlyOwner {
zkLoginAccount = data;
}

function zkLoginRecover(bytes calldata proof, bytes32 publicKeyHash, uint256 jwtIat, Key calldata newKey)
external
{
require(
ZkLogin.verifyProof(
zkLoginAccount,
ZkLogin.VerificationData({
proof: proof,
publicKeyHash: publicKeyHash,
jwtNonce: keccak256(abi.encode(newKey)),
// TODO: check expiration?
jwtIat: jwtIat
})
),
"invalid zklogin proof"
);

Key[] memory newKeys = new Key[](1);
newKeys[0] = newKey;
_authorize(newKeys);
}

/// @notice Executes a set of calls.
/// @param calls - The calls to execute.
function execute(bytes memory calls) public onlyOwner {
Expand Down Expand Up @@ -233,7 +262,7 @@ contract ExperimentalDelegation is Receiver, MultiSendCallOnly {

/// @notice Authorizes a new public key.
/// @param keys_ - The keys to authorize.
function _authorize(Key[] calldata keys_) internal {
function _authorize(Key[] memory keys_) internal {
for (uint32 i = 0; i < keys_.length; i++) {
keys.push(keys_[i]);
}
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
"preinstall": "pnpx only-allow pnpm",
"prepare": "pnpm simple-git-hooks"
},
"dependencies": {
"@shield-labs/zklogin": "^0.6.1"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.17.1",
"@biomejs/biome": "^1.8.3",
Expand Down
4 changes: 3 additions & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
"dev": "vite"
},
"dependencies": {
"porto": "workspace:*",
"@noir-lang/acvm_js": "1.0.0-beta.0",
"@noir-lang/noirc_abi": "1.0.0-beta.0",
"ox": "^0.2.2",
"porto": "workspace:*",
"react": "catalog:",
"react-dom": "catalog:",
"viem": "catalog:"
Expand Down
176 changes: 175 additions & 1 deletion playground/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
import { AbiFunction, Hex, Json, PublicKey, TypedData, Value } from 'ox'
import {
AbiFunction,
AbiParameters,
Address,
Hash,
Hex,
Json,
PublicKey,
TypedData,
Value,
} from 'ox'
import { Porto } from 'porto'
import { useEffect, useState, useSyncExternalStore } from 'react'
import { createClient, custom } from 'viem'
Expand All @@ -9,15 +19,32 @@ import {
} from 'viem/accounts'
import { verifyMessage, verifyTypedData } from 'viem/actions'

import { zklogin } from '@shield-labs/zklogin'
import { serializeKeys } from '../../src/internal/accountDelegation'
import { ExperimentERC20 } from './contracts'

const porto = Porto.create()

const client = createClient({
transport: custom(porto.provider),
})
const zkLogin = new zklogin.ZkLogin()
const authProvider = new zklogin.GoogleProvider(
import.meta.env.VITE_GOOGLE_CLIENT_ID,
)

export function App() {
useEffect(() => {
;(async () => {
if (window.location.pathname.startsWith('/auth')) {
try {
await authProvider.handleRedirect()
} finally {
window.location.href = '/'
}
}
})()
})
return (
<div>
<State />
Expand All @@ -27,6 +54,8 @@ export function App() {
<ImportAccount />
<Login />
<Disconnect />
<AddBackup />
<Recover />
<Accounts />
<GetCapabilities />
<GrantSession />
Expand Down Expand Up @@ -236,6 +265,151 @@ function Disconnect() {
)
}

function AddBackup() {
const [result, setResult] = useState<string | undefined>()
const [jwt, setJwt] = useState<string | undefined>() // TODO: use tanstack query
const [updateCounter, setUpdateCounter] = useState(0)
useEffect(() => {
updateCounter // trigger re-fetch
;(async () => {
const jwt = await authProvider.getJwt()
setJwt(jwt)
})()
}, [updateCounter])

return (
<div>
<h3>experimental_addBackup</h3>
<p>Logged in: {String(!!jwt)}</p>
{!jwt ? (
<button
type="button"
onClick={async () => {
await authProvider.signInWithRedirect({ nonce: 'anything' })
}}
>
Sign in with Google
</button>
) : (
<>
<button
type="button"
onClick={async () => {
await authProvider.signOut()
setUpdateCounter((x) => x + 1)
}}
>
Sign out of Google
</button>
<button
onClick={async () => {
const jwt = await authProvider.getJwt()
if (!jwt) {
await authProvider.signInWithRedirect({ nonce: 'anything' })
return
}
const [account] = await porto.provider.request({
method: 'eth_accounts',
})
return porto.provider
.request({
method: 'experimental_addBackup',
params: [
{
address: account!,
backupOptions: [
{
type: 'zkLogin',
provider: 'google',
jwt,
},
],
},
],
})
.then(setResult)
}}
type="button"
>
Add Backup
</button>
<pre>{result}</pre>
</>
)}
</div>
)
}

function Recover() {
const state = useSyncExternalStore(
porto._internal.store.subscribe,
() => porto._internal.store.getState(),
() => porto._internal.store.getState(),
)
const [result, setResult] = useState<string | undefined>()
return (
<div>
<h3>experimental_recover</h3>
<button
onClick={async () => {
const [account] = await porto.provider.request({
method: 'eth_accounts',
})
const newKey = state.accounts.find((acc) =>
Address.isEqual(acc.address, account),
)?.keys[0]
if (!newKey) {
throw new Error('key not found')
}
const expectedNonce = Hash.keccak256(
AbiParameters.encode(
AbiParameters.from([
'struct PublicKey { uint256 x; uint256 y; }',
'struct Key { uint256 expiry; uint8 keyType; PublicKey publicKey; }',
'Key key',
]),
[serializeKeys([newKey])[0]!],
),
).slice('0x'.length)
const jwt = await authProvider.getJwt()
if (!jwt) {
await authProvider.signInWithRedirect({ nonce: expectedNonce })
return
}
const proof = await zkLogin.proveJwt(jwt, expectedNonce)
if (!proof) {
console.error('jwt invalid or expired')
await authProvider.signInWithRedirect({ nonce: expectedNonce })
return
}
return porto.provider
.request({
method: 'experimental_recover',
params: [
{
address: account!,
backupOption: {
type: 'zkLogin',
provider: 'google',
proof,
},
newAuthentication: {
key: { publicKey: PublicKey.toHex(newKey.publicKey) },
},
},
],
})
.then(setResult)
}}
type="button"
>
Recover
</button>
<pre>{result}</pre>
</div>
)
}

function GetCapabilities() {
const [result, setResult] = useState<Record<string, unknown> | null>(null)
return (
Expand Down
16 changes: 16 additions & 0 deletions playground/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,20 @@ import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
headers: {
// headers to enable multithreaded proving
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin',
},
},
build: {
target: 'esnext', // https://github.com/AztecProtocol/aztec-packages/issues/10184
},
optimizeDeps: {
exclude: ['@noir-lang/noirc_abi', '@noir-lang/acvm_js'],
esbuildOptions: {
target: 'esnext', // https://github.com/AztecProtocol/aztec-packages/issues/10184
},
},
})
Loading