Skip to content

Commit

Permalink
Provider -> Client
Browse files Browse the repository at this point in the history
  • Loading branch information
yuzhiyou1990 committed Aug 22, 2022
1 parent 6b4bcb5 commit def883b
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 61 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ debugPrint(keyPair.address.address)
import AptosSwift

let nodeUrl = URL(string: "https://fullnode.devnet.aptoslabs.com")!
let provider = AptosRPCProvider(nodeUrl: nodeUrl)
let provider = AptosClientProvider(nodeUrl: nodeUrl)

let healthy = try provider.healthy().wait()
debugPrint(healthy)
Expand All @@ -70,7 +70,7 @@ let resourceType = "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>"
let accountResource = try provider.getAccountResource(address: address, resourceType: resourceType).wait()
debugPrint(accountResource)

let coinStore = try accountResource.to(AptosRPC.AccountResourceData.CoinStore.self)
let coinStore = try accountResource.to(AptosClient.AccountResourceData.CoinStore.self)
debugPrint(coinStore)

let accountModules = try provider.getAccountModules(address: try AptosAddress("0x1")).wait()
Expand All @@ -87,7 +87,7 @@ debugPrint(block)
import AptosSwift

let nodeUrl = URL(string: "https://fullnode.devnet.aptoslabs.com")!
let provider = AptosRPCProvider(nodeUrl: nodeUrl)
let provider = AptosClientProvider(nodeUrl: nodeUrl)

let keyPair = try AptosKeyPairEd25519.randomKeyPair()
let sequenceNumber = try provider.getAccount(address: keyPair.address).wait().sequenceNumber
Expand Down Expand Up @@ -126,7 +126,7 @@ debugPrint(result)
import AptosSwift

let nodeUrl = URL(string: "https://fullnode.devnet.aptoslabs.com")!
let provider = AptosRPCProvider(nodeUrl: nodeUrl)
let provider = AptosClientProvider(nodeUrl: nodeUrl)

let keyPair = try AptosKeyPairEd25519.randomKeyPair()
let sequenceNumber = try provider.getAccount(address: keyPair.address).wait().sequenceNumber
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// AptosRPCModels.swift
// AptosClientModels.swift
//
//
// Created by Forrest on 2022/8/15.
Expand All @@ -8,7 +8,7 @@
import Foundation
import AnyCodable

public struct AptosRPC {
extension AptosClient {
public struct Error: Decodable {
public let code: Int
public let message: String
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// AptosRPCProvider+Methods.swift
// AptosClientProvider+Methods.swift
//
//
// Created by mathwallet on 2022/8/15.
Expand All @@ -8,13 +8,13 @@
import Foundation
import PromiseKit

extension AptosRPCProvider {
public class AptosClient: AptosClientBase {

/// Check basic node health
/// - Parameter durationSecs: If the duration_secs param is provided, this endpoint will return a 200 if the following condition is true:
/// server_latest_ledger_info_timestamp >= server_current_time_timestamp - duration_secs
/// - Returns: AptosRPC.Healthy
public func healthy(durationSecs: UInt32? = nil) -> Promise<AptosRPC.Healthy> {
/// - Returns: AptosClient.Healthy
public func healthy(durationSecs: UInt32? = nil) -> Promise<AptosClient.Healthy> {
var parameters: [String : Any]?
if let secs = durationSecs {
parameters = ["duration_secs": secs]
Expand All @@ -23,17 +23,17 @@ extension AptosRPCProvider {
}

/// Get the latest ledger information, including data such as chain ID, role type, ledger versions, epoch, etc.
/// - Returns: AptosRPC.LedgerInfo
public func getLedgerInfo() -> Promise<AptosRPC.LedgerInfo> {
/// - Returns: AptosClient.LedgerInfo
public func getLedgerInfo() -> Promise<AptosClient.LedgerInfo> {
return GET(path: "/v1")
}

/// Get blocks by height
/// - Parameters:
/// - blockHeight: Block Height
/// - withTransactions: true,false,nil
/// - Returns: AptosRPC.Block
public func getBlock(_ blockHeight: UInt64, withTransactions: Bool? = nil) -> Promise<AptosRPC.Block> {
/// - Returns: AptosClient.Block
public func getBlock(_ blockHeight: UInt64, withTransactions: Bool? = nil) -> Promise<AptosClient.Block> {
var parameters: [String : Any]?
if let wt = withTransactions {
parameters = ["with_transactions": wt]
Expand All @@ -44,14 +44,14 @@ extension AptosRPCProvider {
/// Get account
/// - Parameter address: Hex encoded 32 byte Aptos account address
/// - Returns: high level information about an account such as its sequence number
public func getAccount(address: AptosAddress) -> Promise<AptosRPC.AccountData> {
public func getAccount(address: AptosAddress) -> Promise<AptosClient.AccountData> {
return GET(path: "/v1/accounts/\(address.address)")
}

/// Get account resources
/// - Parameter address: Hex encoded 32 byte Aptos account address
/// - Returns: all account resources
public func getAccountResources(address: AptosAddress) -> Promise<[AptosRPC.AccountResource]> {
public func getAccountResources(address: AptosAddress) -> Promise<[AptosClient.AccountResource]> {
return GET(path: "/v1/accounts/\(address.address)/resources")
}

Expand All @@ -61,14 +61,14 @@ extension AptosRPCProvider {
/// - resourceType: String representation of a MoveStructTag (on-chain Move struct type).
/// This exists so you can specify MoveStructTags as path / query parameters, e.g. for get_events_by_event_handle.
/// - Returns: the resource of a specific type
public func getAccountResource(address: AptosAddress, resourceType: String) -> Promise<AptosRPC.AccountResource> {
public func getAccountResource(address: AptosAddress, resourceType: String) -> Promise<AptosClient.AccountResource> {
return GET(path: "/v1/accounts/\(address.address)/resource/\(resourceType)")
}

/// Get account modules
/// - Parameter address: Hex encoded 32 byte Aptos account address
/// - Returns: All account modules at a given address at a specific ledger version (AKA transaction version)
public func getAccountModules(address: AptosAddress) -> Promise<[AptosRPC.AccountModule]> {
public func getAccountModules(address: AptosAddress) -> Promise<[AptosClient.AccountModule]> {
return GET(path: "/v1/accounts/\(address.address)/modules")
}

Expand All @@ -77,14 +77,14 @@ extension AptosRPCProvider {
/// - address: Hex encoded 32 byte Aptos account address
/// - moduleName: Module name
/// - Returns: the module with a specific name residing at a given account at a specified ledger version (AKA transaction version)
public func getAccountModule(address: AptosAddress, moduleName: String) -> Promise<AptosRPC.AccountModule> {
public func getAccountModule(address: AptosAddress, moduleName: String) -> Promise<AptosClient.AccountModule> {
return GET(path: "/v1/accounts/\(address.address)/module/\(moduleName)")
}

/// Submits a signed transaction to the the endpoint that takes BCS payload
/// - Parameter signedTransaction: A BCS signed transaction
/// - Returns: Transaction that is accepted and submitted to mempool
public func submitSignedTransaction(_ signedTransaction: AptosSignedTransaction) -> Promise<AptosRPC.PendingTransaction> {
public func submitSignedTransaction(_ signedTransaction: AptosSignedTransaction) -> Promise<AptosClient.PendingTransaction> {
let headers: [String: String] = ["Content-Type": "application/x.aptos.signed_transaction+bcs"]
return POST(path: "/v1/transactions", body: try? BorshEncoder().encode(signedTransaction), headers: headers)
}
Expand All @@ -93,16 +93,16 @@ extension AptosRPCProvider {
/// - Parameter rawTransaction AptosRawTransaction
/// - Parameter publicKey AptosPublicKeyEd25519
/// - Returns: Simulation result in the form of UserTransaction
public func simulateTransaction(_ rawTransaction: AptosRawTransaction, publicKey: AptosPublicKeyEd25519) -> Promise<[AptosRPC.UserTransaction]> {
public func simulateTransaction(_ rawTransaction: AptosRawTransaction, publicKey: AptosPublicKeyEd25519) -> Promise<[AptosClient.UserTransaction]> {
let signedTransaction = rawTransaction.simulate(publicKey)
let headers: [String: String] = ["Content-Type": "application/x.aptos.signed_transaction+bcs"]
return POST(path: "/v1/transactions/simulate", body: try? BorshEncoder().encode(signedTransaction), headers: headers)
}

/// Get transaction by hash
/// - Parameter txnHash: Transaction Hash
/// - Returns: AptosRPC.Block
public func getTransactionByHash(_ txnHash: String) -> Promise<AptosRPC.Transaction> {
/// - Returns: AptosClient.Block
public func getTransactionByHash(_ txnHash: String) -> Promise<AptosClient.Transaction> {
return GET(path: "/v1/transactions/by_hash/\(txnHash)")
}
}
25 changes: 25 additions & 0 deletions Sources/AptosSwift/Clients/AptosFaucetClient.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//
// AptosFaucetClient.swift
//
//
// Created by mathwallet on 2022/8/22.
//

import Foundation
import PromiseKit

public class AptosFaucetClient: AptosClientBase {

/// This creates an account if it does not exist and mints the specified amount of coins into that account
/// - Parameters:
/// - address: Aptos account address
/// - amount: Amount of tokens to mint
/// - Returns: Hashes of submitted transactions
public func fundAccount(address: AptosAddress, amount: UInt64) -> Promise<[String]> {
let queryParameters: [String: Any] = [
"address": address.address,
"amount": amount
]
return POST(path: "/mint", queryParameters: queryParameters)
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// AptosRPCProvider.swift
// AptosClientProvider.swift
//
//
// Created by xgblin on 2022/8/2.
Expand All @@ -9,25 +9,21 @@ import Foundation
import PromiseKit
import AnyCodable

public struct AptosRPCProvider {
public var nodeUrl: URL
public class AptosClientBase {
public var url: URL
private var session: URLSession

public init(nodeUrl: URL) {
self.nodeUrl = nodeUrl

public init(url: URL) {
self.url = url
self.session = URLSession(configuration: .default)
}
}

extension AptosRPCProvider {

public func GET<T: Decodable>(path: String, parameters: [String: Any]? = nil) -> Promise<T> {
let rp = Promise<Data>.pending()
var task: URLSessionTask? = nil
let queue = DispatchQueue(label: "aptos.get")
queue.async {
let url = self.nodeUrl.appendPath(path).appendingQueryParameters(parameters)
let url = self.url.appendPath(path).appendingQueryParameters(parameters)
// debugPrint("GET \(url)")
var urlRequest = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData)
urlRequest.httpMethod = "GET"
Expand Down Expand Up @@ -57,7 +53,7 @@ extension AptosRPCProvider {
if let resp = try? decoder.decode(T.self, from: data) {
return resp
}
if let errorResult = try? decoder.decode(AptosRPC.Error.self, from: data) {
if let errorResult = try? decoder.decode(AptosClient.Error.self, from: data) {
throw AptosError.providerError(errorResult.message)
}
throw AptosError.providerError("Parameter error or received wrong message")
Expand All @@ -66,16 +62,16 @@ extension AptosRPCProvider {

public func POST<T: Decodable, K: Encodable>(path: String, parameters: K? = nil) -> Promise<T> {
let body: Data? = (parameters != nil ? try? JSONEncoder().encode(parameters!) : nil)
return POST(path: path, body: body, headers: [:])
return POST(path: path, queryParameters: nil, body: body, headers: [:])
}

public func POST<T: Decodable>(path: String, body: Data? = nil, headers: [String: String] = [:]) -> Promise<T> {
public func POST<T: Decodable>(path: String, queryParameters: [String : Any]? = nil, body: Data? = nil, headers: [String: String] = [:]) -> Promise<T> {
let rp = Promise<Data>.pending()
var task: URLSessionTask? = nil
let queue = DispatchQueue(label: "aptos.post")
queue.async {
let url = self.nodeUrl.appendPath(path)
// debugPrint("POST \(url)")
let url = self.url.appendPath(path).appendingQueryParameters(queryParameters)
debugPrint("POST \(url)")
var urlRequest = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData)
urlRequest.httpMethod = "POST"

Expand Down Expand Up @@ -107,14 +103,14 @@ extension AptosRPCProvider {
return rp.promise.ensure(on: queue) {
task = nil
}.map(on: queue){ (data: Data) throws -> T in
// debugPrint(String(data: data, encoding: .utf8) ?? "")
debugPrint(String(data: data, encoding: .utf8) ?? "")

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
if let resp = try? decoder.decode(T.self, from: data) {
return resp
}
if let errorResult = try? decoder.decode(AptosRPC.Error.self, from: data) {
if let errorResult = try? decoder.decode(AptosClient.Error.self, from: data) {
throw AptosError.providerError(errorResult.message)
}
throw AptosError.providerError("Parameter error or received wrong message")
Expand Down
Loading

0 comments on commit def883b

Please sign in to comment.