Class: IcAgent::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/ic_agent/client.rb

Constant Summary collapse

DEFAULT_TIMEOUT =
120
DEFAULT_TIMEOUT_QUERY =
30

Instance Method Summary collapse

Constructor Details

#initialize(url = 'https://ic0.app') ⇒ Client

Initializes a new instance of the Client class.

Parameters:

  • url: The URL of the IC agent. Defaults to ‘ic0.app’.



12
13
14
15
16
17
18
19
20
21
# File 'lib/ic_agent/client.rb', line 12

def initialize(url = 'https://ic0.app')
  @url = url
  @conn = Faraday.new(url: url) do |faraday|
    faraday.request :url_encoded
    faraday.adapter Faraday.default_adapter
    faraday.headers['Content-Type'] = 'application/cbor'
    faraday.options.timeout = DEFAULT_TIMEOUT
    faraday.options.open_timeout = DEFAULT_TIMEOUT_QUERY
  end
end

Instance Method Details

#call(canister_id, req_id, data) ⇒ Object

Calls a function on a canister.

Parameters:

  • canister_id: The ID of the canister to call.

  • req_id: The request ID.

  • data: The data to send with the call.

Returns: The request ID.



45
46
47
48
49
50
# File 'lib/ic_agent/client.rb', line 45

def call(canister_id, req_id, data)
  endpoint = "/api/v2/canister/#{canister_id}/call"
  ret = @conn.post(endpoint, data)
  ret.body.force_encoding('ISO-8859-1').encode('UTF-8')
  req_id
end

#query(canister_id, data) ⇒ Object

Sends a query to a canister.

Parameters:

  • canister_id: The ID of the canister to query.

  • data: The data to send with the query.

Returns: The response from the canister as a UTF-8 encoded string.



30
31
32
33
34
35
# File 'lib/ic_agent/client.rb', line 30

def query(canister_id, data)
  endpoint = "/api/v2/canister/#{canister_id}/query"
  ret = @conn.post(endpoint, data)
  ret.body.force_encoding('ISO-8859-1').encode('UTF-8')
  ret.body
end

#read_state(canister_id, data) ⇒ Object

Reads the state of a canister.

Parameters:

  • canister_id: The ID of the canister to read the state from.

  • data: The data to send with the read_state request.

Returns: The response from the canister as a UTF-8 encoded string.



59
60
61
62
63
64
# File 'lib/ic_agent/client.rb', line 59

def read_state(canister_id, data)
  endpoint = "/api/v2/canister/#{canister_id}/read_state"
  ret = @conn.post(endpoint, data)
  ret.body.force_encoding('ISO-8859-1').encode('UTF-8')
  ret.body
end

#status(timeout: DEFAULT_TIMEOUT_QUERY) ⇒ Object

Retrieves the status of the IC agent.

Parameters:

  • timeout: The timeout for the status request. Defaults to DEFAULT_TIMEOUT_QUERY.

Returns: The response from the status endpoint as a UTF-8 encoded string.



72
73
74
75
76
77
# File 'lib/ic_agent/client.rb', line 72

def status(timeout: DEFAULT_TIMEOUT_QUERY)
  endpoint = '/api/v2/status'
  ret = @conn.get(endpoint, timeout: timeout)
  puts "client.status: #{ret.body.force_encoding('ISO-8859-1').encode('UTF-8')}"
  ret.body
end