Search…
Swift API Reference
The source code is found on GitHub at https://github.com/icon-project/ICONKit
ICON supports SDK for 3rd party or user services development. You can integrate ICON SDK for your project and utilize the ICON’s functionality. This document provides you with information about API specification.

class ICONService

ICONService is a class which provides APIs to communicate with ICON nodes. It enables you to easily use ICON JSON-RPC APIs (version 3). All methods of IconService returns a Request<T, ICError> instance.

Query Execution

Request are executed as synchronized and asynchronized.
Synchronized execution
To execute the request synchronously, you need to run execute() function of Request.
1
public func execute() -> Result<T, ICError>
Copied!
Returns
Result<T, ICError>
Example
1
// Synchronized request execution
2
let response = iconService.getLastBlock().execute()
3
4
switch response {
5
case .success(let block):
6
print(block)
7
case .failure(let error):
8
print(error.errorDescription)
9
}
Copied!
Asynchronized execution
To execute the request asynchronously, you need to run async() function of Request.
1
public func async(_ completion: @escaping (Result<T, ICError>) -> Void)
Copied!
Returns
async() is a closure. Passing Result<T, ICError>.
Example
1
// Asynchronized request execution
2
iconService.getLastBlock().async { (result) in
3
switch result {
4
case .success(let block):
5
print(block)
6
case .failure(let error):
7
print(err.errorDescription)
8
}
9
}
Copied!

Transaction Execution

Transaction class is used to make a transaction instance. There are 3 types of Transaction class.
Class
Description
A class for Transaction instance which is for sending ICX.
A class for CallTransaction instance which is for SCORE function call. CallTransaction extends Transaction class.
A class for MessageTransaction instance which is for transfer message. Extends Transaction class.
Request is executed as Synchronized or Asynchronized like a querying request.
Example
1
// Synchronized request
2
let response = iconService.sendTransaction(signedTransaction: signed).execute()
3
4
switch response {
5
case .success(let result): // result == String
6
print(result)
7
case .error(let error):
8
print(error)
9
}
10
11
// Asynchronized request
12
let request = iconService.sendTransaction(signedTransaction: signed)
13
request.async { (result) in
14
switch result {
15
case .success(let result): // result == String
16
print(result)
17
case .failure(let error):
18
print(error)
19
}
20
}
Copied!

Initialize

1
init(provider: String, nid: String)
Copied!
Parameters
Parameter
Type
Description
provider
String
ICON node url.
nid
String
Network ID.
For more details of node URL and network id, see ICON Network document.
Example
1
// ICON Mainnet
2
let iconService = ICONService(provider: "https://ctz.solidwallet.io/api/v3", nid: "0x1")
Copied!

func getLastBlock

Get the last block information.
1
func getLastBlock() -> Request<Response.Block>
Copied!
Parameters
None
Returns
Request - Request instance for icx_getLastBlock JSON-RPC API request. If the execution is successful, returns Result<Response.Block, ICError>.
Example
1
// Returns last block
2
let response = iconService.getLastBlock().execute()
3
4
switch response {
5
case .success(let result): // result == Response.Block
6
print(result)
7
case .error(let error):
8
print(error)
9
}
Copied!

func getBlock

Get the block information.
1
// Get block information by height.
2
func getBlock(height: UInt64) -> Request<Response.Block>
3
4
// Get block information by hash.
5
func getBlock(hash: String) -> Request<Response.Block>
Copied!
Parameters
Parameter
Type
Description
height
UInt64
Height value of block
hash
String
Hash value of block
Returns
Request - Request instance for icx_getBlockByHeight | icx_getBlockByHash. If the execution is successful, returns Result<Response.Block, ICError>.
Example
1
// Returns block information by block height
2
let heightBlock = iconService.getBlock(height: 10532).execute()
3
4
// Returns block information by block hash
5
let hashBlock = iconService.getBlock(hash: "0xdb310dd653b2573fd673ccc7489477a0b697333f77b3cb34a940db67b994fd95").execute()
6
7
switch heightBlock {
8
case .success(let block): // result == Response.Block
9
print(block)
10
case .error(let error):
11
print(error)
12
}
Copied!

func call

Calls an external function of SCORE API.
1
func call<T>(_ call: Call<T>) -> Request<T>
Copied!
Parameters
Parameter
Type
Description
call
Call
an instance of Call class.
Returns
Request<T> - Request instance for icx_call JSON-RPC request. If the execution is successful, returns Result<T, ICError>.
Example
In Call generic value, input the type of function call. The generic value should follow Codable protocol.
For example, the type of SCORE function call is String, input String like this.
1
// Create Call instance
2
let call = Call<String>(from: wallet.address, to: "cxf9148db4f8ec78823a50cb06c4fed83660af38d0", method: "tokenOwner", params: nil)
3
4
let request: Request<String> = iconService.call(call)
5
let response: Result<String, ICError> = request.execute()
6
7
switch response {
8
case .success(let owner):
9
print(owner) // hx70b591822468415e86fb9ba1354214902ea76196
10
case .failure(let error):
11
print(error)
12
}
Copied!
If SCORE call result is hex String, you can choice return types String or BigUInt.
Using Call<String>, return an original hex String value.
Using Call<BigUInt> return converted BigUInt value.
1
let ownerAddress: String = "hx07abc7a5b8a4941fc0b6930c88b462995acf929b"
2
let scoreAddress: String = "cxf9148db4f8ec78823a50cb06c4fed83660af38d0"
3
4
// Using `String`. Return hex String.
5
let call = Call<String>(from: ownerAddress, to: scoreAddress, method: "balanceOf", params: ["_owner": ownerAddress])
6
let request: Request<String> = iconService.call(call)
7
let response: Result<String, ICError> = request.execute()
8
9
switch response {
10
case .success(let balance):
11
print("balance: \(balance)") // "balance: 0x11e468ef422cc60031ef"
12
case .failure(let error):
13
print(error)
14
}
15
16
17
// Using `BigUInt`. Return BigUInt.
18
let call = Call<BigUInt>(from: ownerAddress, to: scoreAddress, method: "balanceOf", params: ["_owner": ownerAddress])
19
let request: Request<BigUInt> = iconService.call(call)
20
let response: Result<BigUInt, ICError> = request.execute()
21
22
switch response {
23
case .success(let balance):
24
print("balance: \(balance)") // "balance: 84493649192649192649199"
25
case .failure(let error):
26
print(error)
27
}
Copied!

func getBalance

Get the balance of the address.
1
func getBalance(address: String) -> Request<BigUInt>
Copied!
Parameters
Parameter
Type
Description
address
String
An EOA Address
Returns
Request - Request instance for icx_getBalance JSON-RPC API request. If the execution is successful, returns Result<BigUInt, ICError>.
Example
1
// Returns the balance of specific address
2
let response = iconService.getBalance(address: "hx9d8a8376e7db9f00478feb9a46f44f0d051aab57").execute()
3
4
switch response {
5
case .success(let result): // result == BigUInt
6
print(result)
7
case .error(let error):
8
print(error)
9
}
Copied!

func getScoreAPI

Get the SCORE API list.
1
func getScoreAPI(scoreAddress: String) -> Request<[Response.ScoreAPI]>
Copied!
Parameters
Parameter
Type
Description
scoreAddress
String
A SCORE address
Returns
Request - Request instance for icx_getScoreApi JSON-RPC API request. If the execution is successful, returns Result<[Response.ScoreAPI], ICError>.
Example
1
// Returns the SCORE API list
2
let response = iconService.getScoreAPI(scoreAddress: "cx0000000000000000000000000000000000000001").execute()
3
4
switch response {
5
case .success(let result): // result == [Response.ScoreAPI]
6
print(result)
7
case .error(let error):
8
print(error)
9
}
Copied!

func getTotalSupply

get the total number of issued coins.
1
func getTotalSupply() -> Request<BigUInt>
Copied!
Parameters
None
Returns
Request - Request instance for icx_getTotalSupply JSON-RPC API request. If the execution is successful, returns Result<BigUInt, ICError>.
Example
1
// Returns total value of issued coins
2
let response = iconService.getTotalSupply().execute()
3
4
switch response {
5
case .success(let result): // result == BigUInt
6
print(result)
7
case .error(let error):
8
print(error)
9
}
Copied!

func getTransaction

Get the transaction information.
1
func getTransaction(hash: String) -> Request<Response.TransactionByHashResult>
Copied!
Parameters
Parameter
Type
Description
hash
String
Hash value of transaction
Returns
Request - Request instnace for icx_getTransactionByHash JSON-RPC API request. If the execution is successful, returns Result<Response.TransactionByHashResult, ICError>.
Example
1
// Returns transaction information
2
let response = iconService.getTransaction(hash: "0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238").execute()
3
4
switch response {
5
case .success(let result): // result == Response.TransactionByHashResult
6
print(result)
7
case .error(let error):
8
print(error)
9
}
Copied!

func getTransactionResult

Get the transaction result information.
1
func getTransactionResult(hash: String) -> Request<Response.TransactionResult>
Copied!
Parameters
Parameter
Type
Description
hash
String
A transaction hash.
Returns
Request - Request instance for icx_getTransactionResult JSON-RPC API request. If the execution is successful, returns Result<Response.TransactionResult, ICError>.
Example
1
// Returns transaction result information
2
let response = iconService.getTransactionResult(hash: "0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238").execute()
3
4
switch response {
5
case .success(let result): // result == Response.TransactionResult
6
print(result)
7
case .error(let error):
8
print(error)
9
}
Copied!

func sendTransaction

Send a transaction that changes the state of address. Request is executed as Synchronized or Asynchronized like a querying request.
1
func sendTransaction(signedTransaction: SignedTransaction) -> Request<String>
Copied!
Parameters
Parameter
Type
Description
signedTransaction
SignedTransaction
an instance of SignedTransaction class.
Returns
Request - Request instance for icx_sendTransaction JSON-RPC request. If the execution is successful, returns Result<String, ICError>.
Example
1
// Synchronized request
2
let response = iconService.sendTransaction(signedTransaction: signed).execute()
3
4
switch response {
5
case .success(let result): // result == String
6
print(result)
7
case .error(let error):
8
print(error)
9
}
10
11
// Asynchronized request
12
let request = iconService.sendTransaction(signedTransaction: signed)
13
request.async { (result) in
14
switch result {
15
case .success(let result): // result == String
16
print(result)
17
case .failure(let error):
18
print(error)
19
}
20
}
Copied!

class Wallet

1
class Wallet
Copied!
A class which provides EOA functions. It enables you to create, transform to Keystore or load wallet from Keystore.

Initialize

1
init(privateKey: PrivateKey?)
Copied!
Parameters
Parameter
Type
Description
privateKey
PrivateKey
If privateKey is null, it generates new private key while initializing.
Returns
Wallet - Wallet instance.
Example
1
// Create new wallet
2
let wallet = Wallet(prviateKey: nil) // will generate private key
3
4
// Imports from exist private key
5
let privateKey = PrivateKey(hexData: privateKeyData)
6
let wallet = Wallet(privateKey: privateKey)
Copied!
1
// Loading wallets and storing the Keystore
2
3
// Save wallet keystore.
4
let wallet = Wallet(privateKey: nil)
5
do {
6
try wallet.generateKeystore(password: "YOUR_WALLET_PASSWORD")
7
try wallet.save(filepath: "YOUR_STORAGE_PATH")
8
} catch {
9
// handle errors
10
}
11
12
// Load a wallet from the keystore.
13
do {
14
let jsonData: Data = try Data(contentsOf: "YOUR_KEYSTORE_PATH")
15
let decoder = JSONDecoder()
16
let keystore = try decoder.decoder(Keystore.self, from: jsonData)
17
let wallet = Wallet(keystore: keystore, password: "YOUR_WALLET_PASSWORD")
18
} catch {
19
// handle errors
20
}
Copied!

func getSignature

Generate signature string by signing transaction data.
1
func getSignature(data: Data) throws -> String
Copied!
Parameter
Parameter
Type
Description
data
Data
the serialized transaction data.
Returns
String - A signature string.(Base64 encoded)
Example
1
let wallet = Wallet(privateKey: nil)
2
do {
3
let signature = try wallet.getSignature(data: toBeSigned)
4
print("signature - \(signature)")
5
} catch {
6
// handle error
7
}
Copied!

Properties

Property
Type
Description
address
String
Return wallet's address (read-only)

class Transaction

1
class Transaction
Copied!
Transaction is a class representing a transaction data used for sending ICX.

Initialize

1
// Create empty transaction object
2
init()
3
// Create transaction with data
4
convenience init(from: String, to: String, stepLimit: BigUInt, nid: String, value: BigUInt, nonce: String, dataType: String? = nil, data: Any? = nil)
Copied!
Parameters
Parameter
Description
from
An EOA address that creates the transaction.
to
An EOA address to receive coins or SCORE address to execute the transaction.
stepLimit
Amounts of Step limit.
nid
A network ID.
value
Sending the amount of ICX in loop unit.
nonce
An arbitrary number used to prevent transaction hash collision.

func from

Setter for from property.
1
func from(_ from: String) -> Self
Copied!
Parameters
Parameter
Type
Description
from
String
An EOA address that creates the transaction.
Returns
Returns Transaction itself.
Example
1
// Set from property
2
let transaction = Transaction()
3
.from("hx9043346dbaa72bca42ecec6b6e22845a4047426d")
Copied!

func to

Setter for to property.
1
func to(_ to: String) -> Self
Copied!
Paramters
Paramter
Type
Description
to
String
An EOA or SCORE address.
Returns
Returns Transaction itself.
Example
1
let transaction = Transaction()
2
.to("hx2e26d96bd7f1f46aac030725d1e302cf91420458")
Copied!

func stepLimit

Setter for setpLimit property.
1
func stepLimit(_ limit: BigUInt) -> Self
Copied!
Parameters
Parameter
Type
Description
limit
BigUInt
Amounts of Step limit
Returns
Returns Transaction itself.
Example
1
let transaction = Transaction()
2
.stepLimit(BigUInt(1000000))
Copied!

func nid

Setter for nid property.
1
func nid(_ nid: String) -> Self
Copied!
Parameters
Parameter
Type
Description
nid
String
A network ID. (Mainnet = "0x1", Testnet = "0x2", etc)
Returns
Returns Transaction itself.
Example
1
let transaction = Transaction()
2
.nid("0x1")
Copied!

func value

Setter for value property.
1
func value(_ value: BigUInt) -> Self
Copied!
Parameters
Parameter
Type
Description
value
BigUInt
Sending amount of ICX in loop unit. (1 ICX = 1018 loop)
Returns
Returns Transaction itself.
Example
1
let transaction = Transaction()
2
.value(BigUInt(15000000))
Copied!

func nonce

Setter for nonce property.
1
func nonce(_ nonce: String) -> Self
Copied!
Parameters
Parameter
Type
Description
nonce
String
A nonce value.
Returns
Returns Transaction itself.
Example
1
let transaction = Transaction()
2
.nonce("0x1")
Copied!
1
// Creating transaction instance for Sending ICX.
2
let transaction = Transaction()
3
.from("hx9043346dbaa72bca42ecec6b6e22845a4047426d")
4
.to("hx2e26d96bd7f1f46aac030725d1e302cf91420458")
5
.value(BigUInt(15000000))
6
.stepLimit(BigUInt(1000000))
7
.nid("0x1")
8
.nonce("0x1")
Copied!

class CallTransaction

1
class CallTransaction: Transaction
Copied!
CallTransaction class is used for invoking a state-transition function of SCORE. It extends Transaction class, so instance parameters and methods of the class are mostly identical to Transaction class, except for the following:
Parameters
Parameters
Description
method
The method name of SCORE API.
params
The input params for method.
For details of extended parameters and methods, see Transaction section.

func method

Transaction for invoking a state-transition function of SCORE.
Transaction parameter dataType will be fixed with call
1
func method(_ method: String) -> Self
Copied!
Parameters
Parameter
Type
Description
method
String
the method name of SCORE API.
Returns
Returns CallTransaction itself.
params
The input parameters of the SCORE method that will be executed by call function.
1
func params(_ params: [String: Any]) -> Self
Copied!
Parameter
Parameter
Type
Description
params
Dictionary<String: Any>
Input parameters for call method.
Returns
Returns CallTransaction itself.
Example
1
// Creating transaction instance for SCORE function call
2
let call = CallTransaction()
3
.from(wallet.address)
4
.to("cx000...001")
5
.stepLimit(BigUInt(1000000))
6
.nid(self.iconService.nid)
7
.nonce("0x1")
8
.method("transfer")
9
.params(["_to": to, "_value": "0x1234"])
Copied!

class MessageTransaction

1
class MessageTransaction: Transaction
Copied!
MessageTransaction class is used for sending message data. It extends Transaction class, so instance parameters and methods of the class are mostly identical to Transaction class, except for the following:
Parameters
Parameters
Description
message
A message to send.
For details of extended parameters and methods, see Transaction section.

func message

Send messages.
Transaction parameter dataType will be fixed with message.
1
func message(_ message: String) -> Self
Copied!
Parameters
Parameter
Type
Description
message
String
A message String.
Returns
Returns MessageTransaction itself.
Example
1
// Creating transaction instance for transfering message.
2
let messageTransaction = MessageTransaction()
3
.from("hx9043346dbaa72bca42ecec6b6e22845a4047426d")
4
.to("hx2e26d96bd7f1f46aac030725d1e302cf91420458")
5
.value(BigUInt(15000000))
6
.stepLimit(BigUInt(1000000))
7
.nonce("0x1")
8
.nid("0x1")
9
.message("Hello, ICON!")
Copied!

class SignedTransaction

SignedTransaction is a class to make a signed transaction.

Initialize

1
init(transaction: Transaction, privateKey: PrivateKey)
Copied!
Parameters
Parameter
Type
Description
transaction
Transaction
A transaction that will be signed.
privateKey
PrivateKey
A privateKey.
Example
1
let signed = try SignedTransaction(transaction: transaction, privateKey: yourPrivateKey)
Copied!

ICError

There are 5 types of errors.
    emptyKeystore - Keystore is empty.
    invalid
      missing(parameter: JSONParameterKey) - Missing JSON parameter.
      malformedKeystore - Keystore data malformed.
      wrongPassword - Wrong password.
    fail
      sign - Failed to sign.
      parsing - Failed to parse.
      decrypt - Failed to decrypt.
      convert - Failed to convert to URL or data.
    error(error: Error)
    message(error: String) - JSON RPC Error Messages

Converter Functions

ICONKit supports converter functions.

convert()

Convert ICX or gLoop to loop.
1 ICX = 109 gLoop = 1018 loop
Paramters
Parameters
Type
Description
unit
Unit
The unit of value( .icx, .gLoop, .loop ). Default value is .icx.
Returns
BigUInt - The value that converted to loop.
Example
1
let balance: BigUInt = 100
2
3
// Convert ICX to loop.
4
let ICXToLoop: BigUInt = balance.convert() // 100000000000000000000
5
6
// Convert gLoop to loop
7
let gLoopToLoop: BigUInt = balance.convert(unit: .gLoop) // 100000000000
Copied!

toHexString()

Convert BigUInt value to hex String.
1
public func toHexString(unit: Unit = .loop) -> String
Copied!
Parameters
Parameters
Type
Description
unit
Unit
The unit of value( .icx, .gLoop, .loop ). Default value is .loop.
Returns
String - The value converted to a hex String.
Example
1
// Convert `BigUInt` value to hex `String`.
2
let ICXToLoop: BigUInt = 100000000000000000000
3
let hexString: String = ICXToLoop.toHexString() // 0x56bc75e2d63100000
Copied!

hexToBigUInt()

Convert hex String to BigUInt.
1
public func hexToBigUInt(unit: Unit = .loop) -> BigUInt?
Copied!
Parameters
Parameters
Type
Description
unit
Unit
The unit of value( .icx, .gLoop, .loop ). Default value is .loop.
Returns
BigUInt - The value that converted to hex String.
If the conversion is failed, return nil.
Example
1
// Convert hex `String` to `BigUInt`.
2
let hexString: String = "0x56bc75e2d63100000"
3
let hexBigUInt: BigUInt = hexString.hexToBigUInt()! // 100000000000000000000
Copied!

References

Last modified 4mo ago