Skip to content

Commit

Permalink
preview
Browse files Browse the repository at this point in the history
  • Loading branch information
wow-sven committed Feb 3, 2025
1 parent 61af80f commit e01e636
Show file tree
Hide file tree
Showing 11 changed files with 171 additions and 38 deletions.
8 changes: 7 additions & 1 deletion sdk/typescript/rooch-sdk-kit/src/components/DropdownMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,13 @@ export function ActionDropdownMenu() {
<DropdownMenu.Item
className={clsx(styles.menuItem, styles.switchMenuItem)}
onSelect={() => {
window.localStorage.clear()
const prefix = 'rooch-sdk-kit'

Object.keys(localStorage).forEach((key) => {
if (key.startsWith(prefix)) {
localStorage.removeItem(key)
}
})
window.location.reload()
}}
>
Expand Down
2 changes: 1 addition & 1 deletion sdk/typescript/rooch-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ const client = new RoochClient({
const tx = new Transaction()
tx.callFunction({
target: '0x3::empty::empty_with_signer',
maxGas: 100000000 // 1RGas, DEFAULT_GAS 50000000 = 0.5RGas
maxGas: 100000000, // 1RGas, DEFAULT_GAS 50000000 = 0.5RGas
})

const result = await client.signAndExecuteTransaction({
Expand Down
8 changes: 8 additions & 0 deletions sdk/typescript/rooch-sdk/scripts/gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ const options: {
// },
// flattenParams: ['function_call']
// },
rooch_getObjectStates: {
params: {
object_ids: {
alias: 'ids',
typeAlias: 'string[]',
},
},
},
rooch_getBalance: {
params: {
account_addr: {
Expand Down
13 changes: 8 additions & 5 deletions sdk/typescript/rooch-sdk/src/address/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,16 @@ export function decodeToRoochAddressStr(input: address): string {
}

export function decodeToPackageAddressStr(input: address): string {
const packageAddressStr = decodeToRoochAddressStr(input);
if (packageAddressStr.length === ROOCH_ADDRESS_LENGTH * 2){
return packageAddressStr;
const packageAddressStr = decodeToRoochAddressStr(input)
if (packageAddressStr.length === ROOCH_ADDRESS_LENGTH * 2) {
return packageAddressStr
}

if (packageAddressStr.length === ROOCH_ADDRESS_LENGTH * 2 + 2 && packageAddressStr.startsWith('0x')){
return packageAddressStr.slice(2);
if (
packageAddressStr.length === ROOCH_ADDRESS_LENGTH * 2 + 2 &&
packageAddressStr.startsWith('0x')
) {
return packageAddressStr.slice(2)
}

throw Error('Invalid Address')
Expand Down
137 changes: 119 additions & 18 deletions sdk/typescript/rooch-sdk/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,22 @@ import {
ModuleABIView,
GetModuleABIParams,
BroadcastTXParams,
GetObjectStatesParams,
GetFieldStatesParams,
ListFieldStatesParams,
GetTransactionsByHashParams,
TransactionWithInfoView,
GetTransactionsByOrderParams,
RepairIndexerParams,
SyncStatesParams,
PaginatedStateChangeSetWithTxOrderViews,
DryRunRawTransactionParams,
DryRunTransactionResponseView,
} from './types/index.js'
import { fixedBalance } from '../utils/balance.js'

const DEFAULT_GAS = 10000000

/**
* Configuration options for the RoochClient
* You must provide either a `url` or a `transport`
Expand Down Expand Up @@ -132,6 +145,13 @@ export class RoochClient {
})
}

async dryrun(input: DryRunRawTransactionParams): Promise<DryRunTransactionResponseView> {
return await this.transport.request({
method: 'rooch_dryRunRawTransaction',
params: [input.txBcsHex],
})
}

async signAndExecuteTransaction({
transaction,
signer,
Expand All @@ -153,6 +173,20 @@ export class RoochClient {
transaction.setSeqNumber(await this.getSequenceNumber(sender))
transaction.setSender(sender)

// need dry_run
if (!transaction.getMaxGas()) {
transaction.setMaxGas(DEFAULT_GAS)
// const s = transaction.encodeData().toHex()
// const result = await this.dryrun({ txBcsHex: s })
//
// if (result.raw_output.status.type === 'executed') {
// transaction.setMaxGas(Math.ceil(Number(result.raw_output.gas_used) * 100))
// } else {
// // TODO: abort?
// throw Error(result.raw_output.status.type)
// }
}

const auth = await signer.signTransaction(transaction)

transaction.setAuth(auth)
Expand All @@ -166,6 +200,24 @@ export class RoochClient {
})
}

async repairIndexer(input: RepairIndexerParams) {
await this.transport.request({
method: 'rooch_repairIndexer',
params: [input.repairType, input.repairParams],
})
}

async syncStates(input: SyncStatesParams): Promise<PaginatedStateChangeSetWithTxOrderViews> {
const opt = input.queryOption || {
decode: true,
showDisplay: true,
}
return await this.transport.request({
method: 'rooch_repairIndexer',
params: [input.filter, input.cursor, input.limit, opt],
})
}

// Get the states by access_path
async getStates(input: GetStatesParams): Promise<ObjectStateView[]> {
const opt = input.stateOption || {
Expand Down Expand Up @@ -198,6 +250,7 @@ export class RoochClient {
params: [input.moduleAddr, input.moduleName],
})
}

async getEvents(input: GetEventsByEventHandleParams): Promise<PaginatedEventViews> {
const opt = input.eventOptions || {
decode: true,
Expand All @@ -207,7 +260,7 @@ export class RoochClient {
params: [input.eventHandleType, input.cursor, input.limit, input.descendingOrder, opt],
})
}
// curl -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"rooch_getEventsByEventHandle","params":["0x488e11bd0086861e110586909fd72c8142506f6fc636982051271a694bf5b0ed::event_test::WithdrawEvent", null, "1", null, {"decode":true}],"id":1}' http://127.0.0.1:6767 | jq

async queryEvents(input: QueryEventsParams): Promise<PaginatedIndexerEventViews> {
if ('sender' in input.filter) {
if (input.filter.sender === '') {
Expand All @@ -231,7 +284,6 @@ export class RoochClient {
})
}

// Query the Inscription via global index by Inscription filter
async queryInscriptions(input: QueryInscriptionsParams): Promise<PaginatedInscriptionStateViews> {
if (typeof input.filter !== 'string' && 'owner' in input.filter) {
if (input.filter.owner === '') {
Expand Down Expand Up @@ -263,6 +315,42 @@ export class RoochClient {
})
}

async getObjectStates(input: GetObjectStatesParams): Promise<ObjectStateView[]> {
const idsStr = input.ids.join(',')
const opt = input.stateOption || {
decode: true,
showDisplay: true,
}
return this.transport.request({
method: 'rooch_getObjectStates',
params: [idsStr, opt],
})
}

async getFieldStates(input: GetFieldStatesParams): Promise<ObjectStateView[]> {
const opt = input.stateOption || {
decode: true,
showDisplay: true,
}

return this.transport.request({
method: 'rooch_getFieldStates',
params: [input.objectId, input.fieldKey, opt],
})
}

async listFieldStates(input: ListFieldStatesParams): Promise<PaginatedStateKVViews> {
const opt = input.stateOption || {
decode: true,
showDisplay: true,
}

return this.transport.request({
method: 'rooch_getFieldStates',
params: [input.objectId, input.cursor, input.limit, opt],
})
}

async queryObjectStates(
input: QueryObjectStatesParams,
): Promise<PaginatedIndexerObjectStateViews> {
Expand All @@ -288,6 +376,24 @@ export class RoochClient {
})
}

async getTransactionsByHash(
input: GetTransactionsByHashParams,
): Promise<TransactionWithInfoView> {
return this.transport.request({
method: 'rooch_getTransactionsByHash',
params: [input.txHashes],
})
}

async getTransactionsByOrder(
input: GetTransactionsByOrderParams,
): Promise<PaginatedTransactionWithInfoViews> {
return this.transport.request({
method: 'rooch_queryTransactions',
params: [input.cursor, input.limit, input.descendingOrder],
})
}

async queryTransactions(
input: QueryTransactionsParams,
): Promise<PaginatedTransactionWithInfoViews> {
Expand Down Expand Up @@ -463,41 +569,36 @@ export class RoochClient {
package_address,
limit,
cursor,
}:{
}: {
package_address: address
} & PaginationArguments<string>): Promise<Map<string, string>> {
const packageObjectID = `0x14481947570f6c2f50d190f9a13bf549ab2f0c9debc41296cd4d506002379659${decodeToPackageAddressStr(package_address)}`;
const packageObjectID = `0x14481947570f6c2f50d190f9a13bf549ab2f0c9debc41296cd4d506002379659${decodeToPackageAddressStr(package_address)}`
const result = await this.transport.request({
method: 'rooch_listFieldStates',
params: [
packageObjectID,
cursor,
limit,
{ decode: true },
],
});
params: [packageObjectID, cursor, limit, { decode: true }],
})

const moduleInfo = result as unknown as ObjectStateView[]
const moduleMap = new Map<string, string>();
const moduleMap = new Map<string, string>()

if (moduleInfo && typeof moduleInfo === 'object' && 'data' in moduleInfo) {
const { data } = moduleInfo;
const { data } = moduleInfo
if (Array.isArray(data)) {
for (const item of data) {
const decodedValue = item?.state?.decoded_value;
const decodedValue = item?.state?.decoded_value

if (decodedValue) {
const name = decodedValue?.value?.name;
const byte_codes = decodedValue?.value?.value?.value?.byte_codes;
const name = decodedValue?.value?.name
const byte_codes = decodedValue?.value?.value?.value?.byte_codes
if (name && byte_codes) {
moduleMap.set(name, byte_codes);
moduleMap.set(name, byte_codes)
}
}
}
}
}

return moduleMap;
return moduleMap
}

async getSessionKeys({
Expand Down
1 change: 1 addition & 0 deletions sdk/typescript/rooch-sdk/src/client/types/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export interface BlockHeightHashView {
block_height: string
}
export interface DAInfoView {
avail_backends: [string, string][]
last_avail_block_number?: string | null
last_avail_block_update_time?: string | null
last_avail_tx_order?: string | null
Expand Down
2 changes: 1 addition & 1 deletion sdk/typescript/rooch-sdk/src/client/types/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export interface GetModuleABIParams {
}
/** Get object states by object id */
export interface GetObjectStatesParams {
objectIds: string
ids: string[]
stateOption?: RpcTypes.StateOptions | null | undefined
}
/**
Expand Down
11 changes: 10 additions & 1 deletion sdk/typescript/rooch-sdk/src/transactions/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,14 @@ export class Transaction {
return this.info
}

getMaxGas() {
return this.getData().maxGas
}

setMaxGas(input: number) {
this.getData().maxGas = BigInt(input)
}

setSender(input: address) {
this.getData().sender = input
}
Expand All @@ -52,9 +57,13 @@ export class Transaction {
return this.getData().hash()
}

encodeData() {
return this.data!.encode()
}

encode() {
return bcs.RoochTransaction.serialize({
data: this.data!.encode(),
data: this.data!.encode().toBytes(),
auth: this.auth!.encode(),
})
}
Expand Down
14 changes: 6 additions & 8 deletions sdk/typescript/rooch-sdk/src/transactions/transactionData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import { Args, bcs, Serializer } from '../bcs/index.js'
import { address, Bytes, identifier, u8, u64 } from '../types/index.js'
import { CallFunctionArgs, CallScript } from './types.js'

const DEFAULT_GAS = BigInt(50000000)

export class CallFunction {
address: string
module: identifier
Expand Down Expand Up @@ -69,7 +67,7 @@ export class TransactionData {
sender?: address
sequenceNumber?: u64
chainId?: u64
maxGas: u64
maxGas?: u64
action: MoveAction

constructor(
Expand All @@ -83,17 +81,17 @@ export class TransactionData {
this.sequenceNumber = sequenceNumber
this.chainId = chainId
this.action = action
this.maxGas = maxGas || DEFAULT_GAS
this.maxGas = maxGas
}

encode(): Bytes {
encode() {
const call = this.action.val as CallFunction

return bcs.RoochTransactionData.serialize({
sender: this.sender!,
sequenceNumber: this.sequenceNumber!,
chainId: this.chainId!,
maxGas: this.maxGas,
maxGas: this.maxGas!,
action: {
kind: 'CallFunction',
functionId: {
Expand All @@ -106,10 +104,10 @@ export class TransactionData {
args: Array.from(call.encodeArgsToByteArrays()),
typeArgs: call.typeArgs,
},
}).toBytes()
})
}

hash(): Bytes {
return sha3_256(this.encode())
return sha3_256(this.encode().toBytes())
}
}
2 changes: 1 addition & 1 deletion sdk/typescript/rooch-sdk/test-e2e/case/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe('Events API', () => {
expect(await testBox.signAndExecuteTransaction(tx)).toBeTruthy()

const result1 = await testBox.getClient().getEvents({
eventHandleType: `${await testBox.defaultCmdAddress()}::event_test::WithdrawEvent`
eventHandleType: `${await testBox.defaultCmdAddress()}::event_test::WithdrawEvent`,
})

expect(result1.next_cursor).eq('0')
Expand Down
Loading

0 comments on commit e01e636

Please sign in to comment.