Skip to content

Commit

Permalink
feat(aptos): use new aptos-ts-sdk (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
zfy0701 authored Dec 24, 2023
1 parent 02571eb commit 730fc85
Show file tree
Hide file tree
Showing 22 changed files with 2,861 additions and 273 deletions.
4 changes: 2 additions & 2 deletions examples/aptos/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
"test": "NODE_OPTIONS=--experimental-vm-modules pnpm jest"
},
"dependencies": {
"@aptos-labs/ts-sdk": "*",
"@typemove/aptos": "workspace:*",
"@typemove/move": "workspace:*",
"aptos": "*"
"@typemove/move": "workspace:*"
},
"url": "https://github.com/sentioxyz/typemove"
}
8 changes: 4 additions & 4 deletions examples/aptos/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { stable_pool } from './types/0x48271d39d0b05bd6efca2278f22277d6fcc375504f9839fd73f74ace240861af'
import { AptosClient } from 'aptos'
import { Aptos, AptosConfig } from '@aptos-labs/ts-sdk'

const client = new AptosClient('https://fullnode.mainnet.aptoslabs.com')
const client = new Aptos(new AptosConfig({ fullnode: 'https://fullnode.mainnet.aptoslabs.com' }))

const [lpName] = await stable_pool.view.lpNameById(client, { arguments: [3n] })
const [lpName] = await stable_pool.view.lpNameById(client, { functionArguments: [3n] })
console.log(lpName)

const [poolBalances, weights, supply] = await stable_pool.view.poolInfo(client, {
arguments: [lpName],
functionArguments: [lpName]
})

console.log(poolBalances, weights, supply)
2 changes: 1 addition & 1 deletion packages/aptos/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
},
"types": "./dist/cjs/index.d.ts",
"dependencies": {
"@aptos-labs/ts-sdk": "~1.2.0",
"@typemove/move": "workspace:*",
"aptos": "~1.20.0",
"chalk": "^5.3.0",
"commander": "^11.1.0",
"prettier": "^3.0.3",
Expand Down
163 changes: 159 additions & 4 deletions packages/aptos/src/abis/0x1.json

Large diffs are not rendered by default.

19 changes: 18 additions & 1 deletion packages/aptos/src/abis/0x4.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions packages/aptos/src/account-resource-client.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { AptosClient } from 'aptos'
import { expect } from 'chai'
import { jest } from '@jest/globals'
import { AccountResourceClient } from './account-resource-client.js'
import { amm, vault } from './tests/types/0xbd35135844473187163ca197ca93b2ab014370587bb0ed3befff9e902d6bb541.js'
import { aptos_coin } from './builtin/0x1.js'
import { ANY_TYPE } from '@typemove/move'
import { Aptos, AptosConfig } from '@aptos-labs/ts-sdk'

describe('account resource client', () => {
const client = new AptosClient('https://mainnet.aptoslabs.com/')
const client = new Aptos(new AptosConfig({ fullnode: 'https://mainnet.aptoslabs.com/v1' }))
const accountResourceClient = new AccountResourceClient(client)
const ACCOUNT_ADDRESS = '0xbd35135844473187163ca197ca93b2ab014370587bb0ed3befff9e902d6bb541'

Expand Down
49 changes: 30 additions & 19 deletions packages/aptos/src/account-resource-client.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import { AptosClient, MaybeHexString } from 'aptos'
import {
AccountAddressInput,
Aptos,
MoveStructId,
LedgerVersionArg,
PaginationArgs,
MoveResource
} from '@aptos-labs/ts-sdk'
import { TypeDescriptor } from '@typemove/move'
import { defaultMoveCoder } from './move-coder.js'
import { TypedMoveResource } from './models.js'

type ResourceQuery = {
ledgerVersion?: bigint | number
}
// type ResourceQuery = {
// ledgerVersion?: bigint | number
// }

export class AccountResourceClient {
client: AptosClient
constructor(client: AptosClient) {
client: Aptos
constructor(client: Aptos) {
this.client = client
}

Expand All @@ -18,41 +25,45 @@ export class AccountResourceClient {
* @param accountAddress
* @param query
*/
async getAll(accountAddress: MaybeHexString, query?: ResourceQuery) {
return this.client.getAccountResources(accountAddress, query)
async getAll(accountAddress: AccountAddressInput, options?: PaginationArgs & LedgerVersionArg) {
return this.client.getAccountResources({ accountAddress, options })
}

/**
* Match a single resource with exact type, resource type should not contain any type
* @param accountAddress
* @param resourceType
* @param query
* @param options
*/
async matchExact<T>(
accountAddress: MaybeHexString,
accountAddress: AccountAddressInput,
resourceType: TypeDescriptor<T>,
query?: ResourceQuery
options?: LedgerVersionArg
): Promise<TypedMoveResource<T> | undefined> {
if (resourceType.existAnyType()) {
throw new Error('resource type for match call should not contain any type')
}
const typeStr = resourceType.getSignature()
const result = await this.client.getAccountResource(accountAddress, typeStr, query)
return defaultMoveCoder(this.client.nodeUrl).decodeResource<T>(result)
const typeStr = resourceType.getSignature() as MoveStructId
const result = await this.client.getAccountResource({ accountAddress, resourceType: typeStr, options })
const resource: MoveResource = {
type: typeStr,
data: result
}
return defaultMoveCoder(this.client.config.fullnode).decodeResource<T>(resource)
}

/**
* Match all resources with type pattern, it could be a partial type like `amm.Pool<aptos_coin.AptosCoin.type(), ANY_TYPE>`
* @param accountAddress
* @param resourceType
* @param query
* @param options
*/
async matchAll<T>(
accountAddress: MaybeHexString,
accountAddress: AccountAddressInput,
resourceType: TypeDescriptor<T>,
query?: ResourceQuery
options?: PaginationArgs & LedgerVersionArg
): Promise<TypedMoveResource<T>[]> {
const result = await this.client.getAccountResources(accountAddress, query)
return defaultMoveCoder(this.client.nodeUrl).filterAndDecodeResources<T>(resourceType, result)
const result = await this.client.getAccountResources({ accountAddress, options })
return defaultMoveCoder(this.client.config.fullnode).filterAndDecodeResources<T>(resourceType, result)
}
}
16 changes: 10 additions & 6 deletions packages/aptos/src/aptos-chain-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,29 @@ import {
InternalMoveModule,
InternalMoveStruct
} from '@typemove/move'
import { AptosClient } from 'aptos'

import { Event, MoveModuleBytecode, MoveResource } from './move-types.js'
import { Aptos, Event, MoveModuleBytecode, MoveResource } from '@aptos-labs/ts-sdk'
import { toInternalModule } from './to-internal.js'

export class AptosChainAdapter extends ChainAdapter<MoveModuleBytecode, Event | MoveResource> {
// static INSTANCE = new AptosChainAdapter()
client: AptosClient
constructor(client: AptosClient) {
client: Aptos
constructor(client: Aptos) {
super()
this.client = client
}

async fetchModules(account: string): Promise<MoveModuleBytecode[]> {
return await this.client.getAccountModules(account)
return await this.client.getAccountModules({
accountAddress: account
})
}

async fetchModule(account: string, module: string): Promise<MoveModuleBytecode> {
return await this.client.getAccountModule(account, module)
return await this.client.getAccountModule({
accountAddress: account,
moduleName: module
})
}

toInternalModules(modules: MoveModuleBytecode[]): InternalMoveModule[] {
Expand Down
33 changes: 21 additions & 12 deletions packages/aptos/src/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,39 @@
import { AptosClient, Types, AptosAccount } from 'aptos'
import { _0x1 } from '@typemove/aptos/builtin'
import { expect } from 'chai'
import { jest } from '@jest/globals'
import { Account, Aptos, AptosConfig, ViewRequest } from '@aptos-labs/ts-sdk'

describe('client call of entry or view', () => {
const client = new AptosClient('https://mainnet.aptoslabs.com/')
const client = new Aptos(
new AptosConfig({
fullnode: 'https://mainnet.aptoslabs.com/v1'
})
)
jest.setTimeout(100000)

test('call balance', async () => {
const data: Types.ViewRequest = {
type_arguments: [
const data: ViewRequest = {
typeArguments: [
'0x84d7aeef42d38a5ffc3ccef853e1b82e4958659d16a7de736a29c55fbbeb0114::staked_aptos_coin::StakedAptosCoin'
],
arguments: ['0x5967ebb35647e8a664ea8d2d96276f28cc88e7bfeff46e625c8900d8b541506a'],
functionArguments: ['0x5967ebb35647e8a664ea8d2d96276f28cc88e7bfeff46e625c8900d8b541506a'],
function: '0x1::coin::balance'
}
const res1 = await client.view(data, '193435152')
const res1 = await client.view({
payload: data,
options: {
ledgerVersion: 193435152n
}
})
expect(res1).eql(['99680593'])

const res2 = await _0x1.coin.view.balance(
client,
{
type_arguments: [
typeArguments: [
'0x84d7aeef42d38a5ffc3ccef853e1b82e4958659d16a7de736a29c55fbbeb0114::staked_aptos_coin::StakedAptosCoin'
],
arguments: ['0x5967ebb35647e8a664ea8d2d96276f28cc88e7bfeff46e625c8900d8b541506a']
functionArguments: ['0x5967ebb35647e8a664ea8d2d96276f28cc88e7bfeff46e625c8900d8b541506a']
},
193435152n
)
Expand All @@ -33,16 +42,16 @@ describe('client call of entry or view', () => {

test('call get_validator_config', async () => {
const res = await _0x1.stake.view.getValidatorConfig(client, {
arguments: ['0xee49776eff9fd395eb90d601449542080645e63704f518b31c6f72b6a95d7868']
functionArguments: ['0xee49776eff9fd395eb90d601449542080645e63704f518b31c6f72b6a95d7868']
})
expect(res.length).eql(3)
})

test.skip('build transaction', async () => {
const account = new AptosAccount(undefined, '0x5967ebb35647e8a664ea8d2d96276f28cc88e7bfeff46e625c8900d8b541506a')
const account = Account.generate()
const res = await _0x1.coin.entry.transfer(client, account, {
type_arguments: ['0x1::aptos_coin::AptosCoin'],
arguments: ['0x1', 1n]
typeArguments: ['0x1::aptos_coin::AptosCoin'],
functionArguments: ['0x1', 1n]
})
})
})
55 changes: 29 additions & 26 deletions packages/aptos/src/codegen/codegen.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import * as fs from 'fs'
import { Event, MoveModuleBytecode, MoveResource } from '../move-types.js'
import chalk from 'chalk'
import { join } from 'path'
import { AptosChainAdapter } from '../aptos-chain-adapter.js'
import { AbstractCodegen, camel, InternalMoveFunction, InternalMoveModule, normalizeToJSName } from '@typemove/move'
import { AptosClient } from 'aptos'
import { Aptos, AptosConfig, Event, MoveModuleBytecode, MoveResource } from '@aptos-labs/ts-sdk'

export async function codegen(
abisDir: string,
Expand Down Expand Up @@ -34,18 +33,18 @@ export async function codegen(
}

export class AptosCodegen extends AbstractCodegen<MoveModuleBytecode, Event | MoveResource> {
ADDRESS_TYPE = 'Address'
ADDRESS_TYPE = 'MoveAddressType'
PREFIX = 'Aptos'
SYSTEM_PACKAGE = '@typemove/aptos'

constructor(endpoint: string) {
super(new AptosChainAdapter(new AptosClient(endpoint)))
super(new AptosChainAdapter(new Aptos(new AptosConfig({ fullnode: endpoint }))))
}

generateImports(): string {
return `
${super.generateImports()}
import { AptosClient, AptosAccount, TransactionBuilderRemoteABI, Types, TxnBuilderTypes, OptionalTransactionArgs } from 'aptos'
import { Aptos, Account as AptosAccount, MoveAddressType, PendingTransactionResponse, InputGenerateTransactionOptions, MoveStructId, InputViewRequestData } from '@aptos-labs/ts-sdk'
`
}
protected generateExtra(module: InternalMoveModule) {
Expand Down Expand Up @@ -87,20 +86,20 @@ export class AptosCodegen extends AbstractCodegen<MoveModuleBytecode, Event | Mo
const requestArg = allEmpty
? ''
: `request: {
${func.typeParams.length > 0 ? `type_arguments: [${func.typeParams.map((_) => 'string').join(', ')}],` : ''}
${func.params.length > 0 ? `arguments: [${fields.join(',')}]` : ''}},`
${func.typeParams.length > 0 ? `typeArguments: [${func.typeParams.map((_) => 'MoveStructId').join(', ')}],` : ''}
${func.params.length > 0 ? `functionArguments: [${fields.join(',')}]` : ''}},`

return `export async function ${camel(normalizeToJSName(func.name))}${genericString}(
client: AptosClient,
client: Aptos,
${requestArg}
version?: bigint): Promise<[${returns.join(',')}]> {
const coder = defaultMoveCoder(client.nodeUrl)
const data = {
type_arguments: ${func.typeParams.length > 0 ? 'request.type_arguments' : '[]'},
arguments: ${func.params.length > 0 ? 'coder.encodeArray(request.arguments)' : '[]'},
function: "${module.address}::${module.name}::${func.name}"
const coder = defaultMoveCoder(client.config.fullnode)
const data: InputViewRequestData = {
function: "${module.address}::${module.name}::${func.name}",
functionArguments: ${func.params.length > 0 ? 'coder.encodeArray(request.functionArguments)' : '[]'},
typeArguments: ${func.typeParams.length > 0 ? 'request.typeArguments' : '[]'},
}
const res = await client.view(data, version?.toString())
const res = await client.view({payload: data, options: { ledgerVersion: version } });
const type = await coder.getMoveFunction("${module.address}::${module.name}::${func.name}")
return await coder.decodeArray(res, type.return) as any
}`
Expand All @@ -124,21 +123,25 @@ export class AptosCodegen extends AbstractCodegen<MoveModuleBytecode, Event | Mo
// const args = this.generateArgs(module, func)

return `export async function ${camel(normalizeToJSName(func.name))}${genericString}(
client: AptosClient,
client: Aptos,
account: AptosAccount,
request: {
type_arguments: [${func.typeParams.map((_) => 'string').join(', ')}],
arguments: [${fields.join(',')}]
typeArguments: [${func.typeParams.map((_) => 'MoveStructId').join(', ')}],
functionArguments: [${fields.join(',')}]
},
extraArgs?: OptionalTransactionArgs
): Promise<Types.PendingTransaction> {
const coder = defaultMoveCoder(client.nodeUrl)
const builder = new TransactionBuilderRemoteABI(client, { sender: account.address(), ...extraArgs });
const txn = await builder.build("${module.address}::${module.name}::${
func.name
}", request.type_arguments, coder.encodeArray(request.arguments))
const bcsTxn = AptosClient.generateBCSTransaction(account, txn)
return await client.submitSignedBCSTransaction(bcsTxn)
options?: InputGenerateTransactionOptions
): Promise<PendingTransactionResponse> {
const coder = defaultMoveCoder(client.config.fullnode)
const transaction = await client.build.simple({
sender: account.accountAddress,
data: {
function: "${module.address}::${module.name}::${func.name}",
functionArguments: ${func.params.length > 0 ? 'coder.encodeArray(request.functionArguments)' : '[]'},
typeArguments: ${func.typeParams.length > 0 ? 'request.typeArguments' : '[]'},
},
options
})
return await client.signAndSubmitTransaction({ signer: account, transaction });
}`
}
}
10 changes: 5 additions & 5 deletions packages/aptos/src/codegen/run.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env node

import { codegen } from './codegen.js'
import { AptosClient } from 'aptos'
import { Aptos, AptosConfig } from '@aptos-labs/ts-sdk'
import * as path from 'path'
import * as fs from 'fs'
import { Command } from 'commander'
Expand Down Expand Up @@ -32,17 +32,17 @@ program
.action(async (location, options) => {
let endpoint = options.network
if (endpoint == 'mainnet') {
endpoint = 'https://mainnet.aptoslabs.com/'
endpoint = 'https://mainnet.aptoslabs.com/v1'
}
if (endpoint == 'testnet') {
endpoint = 'https://testnet.aptoslabs.com/'
endpoint = 'https://testnet.aptoslabs.com/v1'
}
const aptosClient = new AptosClient(endpoint)
const aptosClient = new Aptos(new AptosConfig({ fullnode: endpoint }))

let abisDir = location
if (location.startsWith('0x')) {
const abiAddress = abisDir
const abi = await aptosClient.getAccountModules(abiAddress)
const abi = await aptosClient.getAccountModules({ accountAddress: abiAddress })
abisDir = options.abiDir
if (!fs.existsSync(abisDir)) {
fs.mkdirSync(abisDir, { recursive: true })
Expand Down
Loading

0 comments on commit 730fc85

Please sign in to comment.