Skip to content
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
1 change: 1 addition & 0 deletions packages/synapse-core/src/mocks/jsonrpc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,7 @@ export const presets = {
},
sessionKeyRegistry: {
authorizationExpiry: () => [BigInt(0)],
login: () => [],
},
endorsements: {
getProviderIds: () => [[]],
Expand Down
11 changes: 11 additions & 0 deletions packages/synapse-core/src/mocks/jsonrpc/session-key-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import * as Abis from '../../abis/index.ts'
import type { AbiToType, JSONRPCOptions } from './types.ts'

type authorizationExpiry = ExtractAbiFunction<typeof Abis.sessionKeyRegistry, 'authorizationExpiry'>
type login = ExtractAbiFunction<typeof Abis.sessionKeyRegistry, 'login'>

export interface SessionKeyRegistryOptions {
authorizationExpiry?: (args: AbiToType<authorizationExpiry['inputs']>) => AbiToType<authorizationExpiry['outputs']>
login?: (args: AbiToType<login['inputs']>) => AbiToType<login['outputs']>
}

export function sessionKeyRegistryCallHandler(data: Hex, options: JSONRPCOptions): Hex {
Expand All @@ -31,6 +33,15 @@ export function sessionKeyRegistryCallHandler(data: Hex, options: JSONRPCOptions
options.sessionKeyRegistry.authorizationExpiry(args)
)
}
case 'login': {
if (!options.sessionKeyRegistry?.login) {
throw new Error('Session Key Registry: login is not defined')
}
return encodeAbiParameters(
Abis.sessionKeyRegistry.find((abi) => abi.type === 'function' && abi.name === 'login')!.outputs,
options.sessionKeyRegistry.login(args)
)
}
default: {
throw new Error(`SessionKeyRegistry: unknown function: ${functionName} with args: ${args}`)
}
Expand Down
10 changes: 7 additions & 3 deletions packages/synapse-core/src/session-key/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ import type {
WaitForTransactionReceiptErrorType,
WriteContractErrorType,
} from 'viem'
import { parseEventLogs } from 'viem'
import { parseEventLogs, zeroAddress } from 'viem'
import { simulateContract, writeContract } from 'viem/actions'
import type { sessionKeyRegistry as sessionKeyRegistryAbi } from '../abis/index.ts'
import * as Abis from '../abis/index.ts'
import { asChain } from '../chains.ts'
import { ValidationError } from '../errors/base.ts'
import type { ActionCallChain, ActionSyncCallback, ActionSyncOutput } from '../types.ts'
import { waitForTransactionReceipt } from '../utils/wait-for-transaction-receipt.ts'
import { DefaultFwssPermissions, type Permission } from './permissions.ts'
Expand All @@ -37,7 +38,7 @@ export namespace login {

export type OutputType = Hash

export type ErrorType = asChain.ErrorType | SimulateContractErrorType | WriteContractErrorType
export type ErrorType = loginCall.ErrorType | SimulateContractErrorType | WriteContractErrorType
}

/**
Expand Down Expand Up @@ -103,7 +104,7 @@ export async function loginSync(

export namespace loginCall {
export type OptionsType = Simplify<login.OptionsType & ActionCallChain>
export type ErrorType = asChain.ErrorType
export type ErrorType = asChain.ErrorType | ValidationError
export type OutputType = ContractFunctionParameters<typeof sessionKeyRegistryAbi, 'nonpayable', 'login'>
}

Expand All @@ -115,6 +116,9 @@ export namespace loginCall {
* @throws Errors {@link loginCall.ErrorType}
*/
export function loginCall(options: loginCall.OptionsType) {
if (options.address === zeroAddress) {
throw new ValidationError('Session key address cannot be the zero address')
}
const chain = asChain(options.chain)
const expiresAt = BigInt(Math.floor(Date.now() / 1000) + 3600)
const permissions = options.permissions ?? DefaultFwssPermissions
Expand Down
106 changes: 106 additions & 0 deletions packages/synapse-core/test/login.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import assert from 'assert'
import { setup } from 'iso-web/msw'
import { createWalletClient, custom, http, zeroAddress } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { calibration } from '../src/chains.ts'
import { ADDRESSES, JSONRPC, PRIVATE_KEYS, presets } from '../src/mocks/jsonrpc/index.ts'
import { login, loginCall, loginSync } from '../src/session-key/login.ts'

describe('login', () => {
const server = setup()
const account = privateKeyToAccount(PRIVATE_KEYS.key1)
const zeroAddressError = { name: 'ValidationError', message: /zero address/ }

before(async () => {
await server.start()
})

after(() => {
server.stop()
})

beforeEach(() => {
server.resetHandlers()
})

function createRecordingClient() {
const requests: string[] = []
const client = createWalletClient({
account,
chain: calibration,
transport: custom({
request: async ({ method }) => {
requests.push(method)
throw new Error(`unexpected request: ${method}`)
},
}),
})
return { client, requests }
}

describe('loginCall', () => {
it('should create call for a session key address', () => {
const call = loginCall({
chain: calibration,
address: ADDRESSES.client1,
expiresAt: 123n,
})

assert.equal(call.functionName, 'login')
assert.equal(call.address, calibration.contracts.sessionKeyRegistry.address)
assert.equal(call.args[0], ADDRESSES.client1)
assert.equal(call.args[1], 123n)
assert.equal(call.args[3], 'synapse')
})

it('should throw for the zero address', () => {
assert.throws(() => loginCall({ chain: calibration, address: zeroAddress }), zeroAddressError)
})

it('should not validate a malformed address', () => {
const call = loginCall({ chain: calibration, address: '0x123' })

assert.equal(call.args[0], '0x123')
})
})

describe('login (with mocked RPC)', () => {
it('should authorize a session key and return transaction hash', async () => {
let loginArgs: readonly unknown[] | undefined
server.use(
JSONRPC({
...presets.basic,
sessionKeyRegistry: {
...presets.basic.sessionKeyRegistry,
login: (args) => {
loginArgs = args
return []
},
},
})
)

const client = createWalletClient({ account, chain: calibration, transport: http() })
const hash = await login(client, { address: ADDRESSES.client1, expiresAt: 123n })

assert.equal(hash.length, 66)
assert.equal(loginArgs?.[0], ADDRESSES.client1)
})

it('should throw for the zero address without sending a request', async () => {
const { client, requests } = createRecordingClient()

await assert.rejects(login(client, { address: zeroAddress }), zeroAddressError)
assert.deepEqual(requests, [])
})
})

describe('loginSync', () => {
it('should throw for the zero address without sending a request', async () => {
const { client, requests } = createRecordingClient()

await assert.rejects(loginSync(client, { address: zeroAddress }), zeroAddressError)
assert.deepEqual(requests, [])
})
})
})
Loading