Skip to content

Commit

Permalink
Feature owen sdk session key (#747)
Browse files Browse the repository at this point in the history
* feat: rebase main

* feat: set rooch server start timeout 300s

* feat: rebase main

* feat: fix lint error

* feat: debug session key

* feat: ok for session account e2e

* feat: fmt code

* feat: add expirationTime and maxInactiveInterval of session account
  • Loading branch information
yubing744 authored Sep 3, 2023
1 parent febf25b commit 37463a9
Show file tree
Hide file tree
Showing 14 changed files with 368 additions and 38 deletions.
12 changes: 12 additions & 0 deletions crates/rooch/src/commands/abi/commands/export_rooch_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ use move_core_types::{
identifier::Identifier,
language_storage::{StructTag, TypeTag},
};
use moveos_types::move_string::{MoveAsciiString, MoveString};
use moveos_types::transaction::MoveAction;
use rooch_types::error::RoochResult;
use rooch_types::transaction::rooch::RoochTransaction;
use serde_reflection::{Samples, Tracer, TracerConfig};
use std::fmt::Debug;
use std::fs;
use std::path::Path;
use std::str::FromStr;

#[derive(Debug, Parser)]
pub struct ExportRoochTypesCommand {
Expand Down Expand Up @@ -86,6 +88,16 @@ fn export_rooch_types_yaml(file_path: &String) -> RoochResult<()> {
tracer.trace_type::<MoveAction>(&samples).unwrap();
tracer.trace_type::<RoochTransaction>(&samples).unwrap();

// More types
let example_ascii_string: MoveAsciiString = MoveAsciiString::from_str("test").unwrap();
tracer
.trace_value(&mut samples, &example_ascii_string)
.unwrap();
let example_move_string: MoveString = MoveString::from_str("test").unwrap();
tracer
.trace_value(&mut samples, &example_move_string)
.unwrap();

match tracer.registry() {
Ok(registry) => {
let data: String = serde_json::to_string_pretty(&registry).unwrap();
Expand Down
84 changes: 80 additions & 4 deletions sdk/typescript/src/account/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,23 @@
import { DEFAULT_MAX_GAS_AMOUNT } from '../constants'
import { IAccount, CallOption } from './interface'
import { IProvider } from '../provider'
import { IAuthorizer, IAuthorization } from '../auth'
import { IAuthorizer, IAuthorization, PrivateKeyAuth } from '../auth'
import { AccountAddress, FunctionId, TypeTag, Arg } from '../types'
import { BcsSerializer } from '../generated/runtime/bcs/mod'
import { BcsSerializer } from '../types/bcs'
import {
RoochTransaction,
RoochTransactionData,
AccountAddress as BCSAccountAddress,
Authenticator,
} from '../generated/runtime/rooch_types/mod'
import { encodeArgs, encodeFunctionCall, addressToListTuple, uint8Array2SeqNumber } from '../utils'
import {
encodeArg,
encodeFunctionCall,
addressToListTuple,
uint8Array2SeqNumber,
addressToSeqNumber,
} from '../utils'
import { Ed25519Keypair } from '../utils/keypairs'

export class Account implements IAccount {
private provider: IProvider
Expand All @@ -35,7 +42,7 @@ export class Account implements IAccount {
opts: CallOption,
): Promise<string> {
const number = await this.sequenceNumber()
const bcsArgs = args.map((arg) => encodeArgs(arg))
const bcsArgs = args.map((arg) => encodeArg(arg))
const scriptFunction = encodeFunctionCall(funcId, tyArgs, bcsArgs)
const txData = new RoochTransactionData(
new BCSAccountAddress(addressToListTuple(this.address)),
Expand Down Expand Up @@ -90,4 +97,73 @@ export class Account implements IAccount {

return 0
}

async createSessionAccount(
scope: string,
expirationTime: number,
maxInactiveInterval: number,
opts?: CallOption,
): Promise<IAccount> {
const kp = Ed25519Keypair.generate()
await this.registerSessionKey(
kp.getPublicKey().toRoochAddress(),
scope,
expirationTime,
maxInactiveInterval,
opts,
)
const auth = new PrivateKeyAuth(kp)
return new Account(this.provider, this.address, auth)
}

async registerSessionKey(
authKey: AccountAddress,
scope: string,
expirationTime: number,
maxInactiveInterval: number,
opts?: CallOption,
): Promise<void> {
const parts = scope.split('::')
if (parts.length !== 3) {
throw new Error('invalid scope')
}

const scopeModuleAddress = parts[0]
const scopeModuleName = parts[1]
const scopeFunctionName = parts[2]

await this.runFunction(
'0x3::session_key::create_session_key_entry',
[],
[
{
type: { Vector: 'U8' },
value: addressToSeqNumber(authKey),
},
{
type: 'Address',
value: scopeModuleAddress,
},
{
type: 'Ascii',
value: scopeModuleName,
},
{
type: 'Ascii',
value: scopeFunctionName,
},
{
type: 'U64',
value: BigInt(expirationTime),
},
{
type: 'U64',
value: BigInt(maxInactiveInterval),
},
],
opts || {
maxGasAmount: 100000000,
},
)
}
}
23 changes: 23 additions & 0 deletions sdk/typescript/src/account/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,33 @@ export interface CallOption {
}

export interface IAccount {
/**
* Run move function by current account
*
* @param funcId FunctionId the function like '0x3::empty::empty'
* @param tyArgs Generic parameter list
* @param args parameter list
* @param opts Call option
*/
runFunction(
funcId: FunctionId,
tyArgs?: TypeTag[],
args?: Arg[],
opts?: CallOption,
): Promise<string>

/**
* Create session account with scope
*
* @param scope string the scope of created account
* @param expirationTime number The expiration time of created account
* @param maxInactiveInterval number The max inactive interval
* @param opts CallOption
*/
createSessionAccount(
scope: string,
expirationTime: number,
maxInactiveInterval: number,
opts?: CallOption,
): Promise<IAccount>
}
2 changes: 1 addition & 1 deletion sdk/typescript/src/auth/private-key-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Bytes } from '../types'
import { Keypair } from '../utils/crypto'
import { IAuthorization, IAuthorizer } from './interface'

export const SCHEME_ED25519: number = 0
const SCHEME_ED25519: number = 0

export class PrivateKeyAuth implements IAuthorizer {
private pk: Keypair
Expand Down
4 changes: 2 additions & 2 deletions sdk/typescript/src/provider/json-rpc-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { JsonRpcClient } from '../generated/client'
import { Connection, LocalnetConnection } from './connection'
import { bytes } from '../types/bcs'
import { FunctionId, TypeTag, Arg, AnnotatedFunctionResultView } from '../types'
import { functionIdToStirng, typeTagToString, encodeArgs, toHexString } from '../utils'
import { functionIdToStirng, typeTagToString, encodeArg, toHexString } from '../utils'

import { ROOCH_DEV_CHIAN_ID } from '../constants'

Expand Down Expand Up @@ -90,7 +90,7 @@ export class JsonRpcProvider {
args?: Arg[],
): Promise<AnnotatedFunctionResultView> {
const tyStrArgs = tyArgs?.map((v) => typeTagToString(v))
const bcsArgs = args?.map((arg) => toHexString(encodeArgs(arg))) as any
const bcsArgs = args?.map((arg) => toHexString(encodeArg(arg))) as any

return this.client.rooch_executeViewFunction({
function_id: functionIdToStirng(funcId),
Expand Down
3 changes: 3 additions & 0 deletions sdk/typescript/src/types/bcs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ export * from '../../utils/b64'

export * from '../../generated/runtime/bcs/mod'
export * from '../../generated/runtime/serde/mod'
export * from '../../generated/runtime/rooch_types/mod'
export * from './move_string'
export * from './move_ascii_string'
23 changes: 23 additions & 0 deletions sdk/typescript/src/types/bcs/move_ascii_string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

import { Serializer, Deserializer } from '../../generated/runtime/serde/mod'
import { Seq, uint8 } from '../../generated/runtime/serde/mod'
import { Helpers } from '../../generated/runtime/rooch_types/mod'

export class MoveAsciiString {
private bytes: Seq<uint8>

constructor(bytes: Seq<uint8>) {
this.bytes = bytes
}

public serialize(serializer: Serializer): void {
Helpers.serializeVectorU8(this.bytes, serializer)
}

static deserialize(deserializer: Deserializer): MoveAsciiString {
const bytes = Helpers.deserializeVectorU8(deserializer)
return new MoveAsciiString(bytes)
}
}
23 changes: 23 additions & 0 deletions sdk/typescript/src/types/bcs/move_string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

import { Serializer, Deserializer } from '../../generated/runtime/serde/mod'
import { Seq, uint8 } from '../../generated/runtime/serde/mod'
import { Helpers } from '../../generated/runtime/rooch_types/mod'

export class MoveString {
private bytes: Seq<uint8>

constructor(bytes: Seq<uint8>) {
this.bytes = bytes
}

public serialize(serializer: Serializer): void {
Helpers.serializeVectorU8(this.bytes, serializer)
}

static deserialize(deserializer: Deserializer): MoveString {
const bytes = Helpers.deserializeVectorU8(deserializer)
return new MoveString(bytes)
}
}
2 changes: 1 addition & 1 deletion sdk/typescript/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
export * from './hex'
export * from './rooch'
export * from './bcs'
export * from './rpc'
export * from './bytes'
export * as bcsTypes from './bcs'
9 changes: 5 additions & 4 deletions sdk/typescript/src/types/rooch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ export type Bool = boolean
export type U8 = number
export type U16 = number
export type U64 = bigint
export type U128 = number
export type U256 = string
export type I64 = number
export type U128 = bigint
export type U256 = bigint
export type BlockNumber = number
export type AuthenticationKey = string
export type MultiEd25519PublicKey = string
Expand All @@ -36,10 +35,12 @@ export type TypeTag =
| 'U128'
| 'Address'
| 'Signer'
| 'Ascii'
| 'String'
| { Vector: TypeTag }
| { Struct: StructTag }

export type ArgType = Bool | U8 | U64 | U128 | AccountAddress
export type ArgType = Bool | U8 | U64 | U128 | string | AccountAddress | ArgType[]
export type Arg = {
type: TypeTag
value: ArgType
Expand Down
17 changes: 16 additions & 1 deletion sdk/typescript/src/utils/tx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import {
structTagToSCS,
addressToSCS,
encodeStructTypeTags,
encodeArg,
} from './tx'
import { TypeTag, StructTag, AccountAddress } from '../types'
import { toHexString } from './hex'
import { TypeTag, StructTag, AccountAddress, Arg } from '../types'
import * as rooch_types from '../generated/runtime/rooch_types/mod'
import { bytes } from '../generated/runtime/serde/mod'

Expand Down Expand Up @@ -76,3 +78,16 @@ describe('encodeStructTypeTags', () => {
// Add more assertions to check the properties of the result object.
})
})

describe('encodeArg', () => {
it('should encode Vector TypeTag', () => {
const arg = {
type: { Vector: 'U8' },
value: [100],
} as Arg

const result = encodeArg(arg)

expect(toHexString(result)).toBe('0x0164')
})
})
Loading

0 comments on commit 37463a9

Please sign in to comment.