Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

General Improvements #24

Merged
merged 10 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 46 additions & 22 deletions agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,37 @@ func effectiveCanisterID(canisterID principal.Principal, args []any) principal.P
}

v := reflect.ValueOf(args[0])
if v.Kind() == reflect.Struct {
switch v.Kind() {
case reflect.Map:
if ecid, ok := args[0].(map[string]any)["canister_id"]; ok {
switch ecidp := ecid.(type) {
case principal.Principal:
return ecidp
default:
// If the field is not a principal, return the original canisterId.
return canisterID
}
}
return canisterID
case reflect.Struct:
t := v.Type()
// Get the field with the ic tag "canister_id".
for idx := range t.NumField() {
if tag := t.Field(idx).Tag.Get("ic"); tag == "canister_id" {
ecid := v.Field(idx).Interface()
switch ecid := ecid.(type) {
switch ecidp := ecid.(type) {
case principal.Principal:
return ecid
return ecidp
default:
// If the field is not a principal, return the original canisterId.
return canisterID
}
}
}
return canisterID
default:
return canisterID
}
return canisterID
}

func newNonce() ([]byte, error) {
Expand Down Expand Up @@ -144,7 +158,12 @@ func (a Agent) Call(canisterID principal.Principal, methodName string, args []an
return call.CallAndWait(values...)
}

// CreateCall creates a new call to the given canister and method.
// Client returns the underlying Client of the Agent.
func (a Agent) Client() *Client {
return &a.client
}

// CreateCall creates a new Call to the given canister and method.
func (a *Agent) CreateCall(canisterID principal.Principal, methodName string, args ...any) (*Call, error) {
rawArgs, err := idl.Marshal(args)
if err != nil {
Expand Down Expand Up @@ -179,7 +198,7 @@ func (a *Agent) CreateCall(canisterID principal.Principal, methodName string, ar
}, nil
}

// CreateQuery creates a new query to the given canister and method.
// CreateQuery creates a new Query to the given canister and method.
func (a *Agent) CreateQuery(canisterID principal.Principal, methodName string, args ...any) (*Query, error) {
rawArgs, err := idl.Marshal(args)
if err != nil {
Expand Down Expand Up @@ -233,15 +252,7 @@ func (a Agent) GetCanisterControllers(canisterID principal.Principal) ([]princip
// GetCanisterInfo returns the raw certificate for the given canister based on the given sub-path.
func (a Agent) GetCanisterInfo(canisterID principal.Principal, subPath string) ([]byte, error) {
path := []hashtree.Label{hashtree.Label("canister"), canisterID.Raw, hashtree.Label(subPath)}
c, err := a.readStateCertificate(canisterID, [][]hashtree.Label{path})
if err != nil {
return nil, err
}
var state map[string]any
if err := cbor.Unmarshal(c, &state); err != nil {
return nil, err
}
node, err := hashtree.DeserializeNode(state["tree"].([]any))
node, err := a.ReadStateCertificate(canisterID, [][]hashtree.Label{path})
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -298,6 +309,19 @@ func (a Agent) Query(canisterID principal.Principal, methodName string, args []a
return query.Query(values...)
}

// ReadStateCertificate reads the certificate state of the given canister at the given path.
func (a Agent) ReadStateCertificate(canisterID principal.Principal, path [][]hashtree.Label) (hashtree.Node, error) {
c, err := a.readStateCertificate(canisterID, path)
if err != nil {
return nil, err
}
var state map[string]any
if err := cbor.Unmarshal(c, &state); err != nil {
return nil, err
}
return hashtree.DeserializeNode(state["tree"].([]any))
}

// RequestStatus returns the status of the request with the given ID.
func (a Agent) RequestStatus(ecID principal.Principal, requestID RequestID) ([]byte, hashtree.Node, error) {
a.logger.Printf("[AGENT] REQUEST STATUS %s %x", ecID, requestID)
Expand Down Expand Up @@ -339,7 +363,7 @@ func (a Agent) Sender() principal.Principal {
}

func (a Agent) call(ecID principal.Principal, data []byte) ([]byte, error) {
return a.client.call(ecID, data)
return a.client.Call(ecID, data)
}

func (a Agent) expiryDate() uint64 {
Expand Down Expand Up @@ -386,7 +410,7 @@ func (a Agent) poll(ecID principal.Principal, requestID RequestID) ([]byte, erro
}

func (a Agent) query(canisterID principal.Principal, data []byte) (*Response, error) {
resp, err := a.client.query(canisterID, data)
resp, err := a.client.Query(canisterID, data)
if err != nil {
return nil, err
}
Expand All @@ -395,7 +419,7 @@ func (a Agent) query(canisterID principal.Principal, data []byte) (*Response, er
}

func (a Agent) readState(ecID principal.Principal, data []byte) (map[string][]byte, error) {
resp, err := a.client.readState(ecID, data)
resp, err := a.client.ReadState(ecID, data)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -434,7 +458,7 @@ func (a Agent) sign(request Request) (*RequestID, []byte, error) {
return &requestID, data, nil
}

// Call is an intermediate representation of a call to a canister.
// Call is an intermediate representation of a Call to a canister.
type Call struct {
a *Agent
methodName string
Expand All @@ -458,7 +482,7 @@ func (c Call) CallAndWait(values ...any) error {
return c.Wait(values...)
}

// Wait waits for the result of the call and unmarshals it into the given values.
// Wait waits for the result of the Call and unmarshals it into the given values.
func (c Call) Wait(values ...any) error {
raw, err := c.a.poll(c.effectiveCanisterID, c.requestID)
if err != nil {
Expand All @@ -467,7 +491,7 @@ func (c Call) Wait(values ...any) error {
return idl.Unmarshal(raw, values)
}

// WithEffectiveCanisterID sets the effective canister ID for the call.
// WithEffectiveCanisterID sets the effective canister ID for the Call.
func (c *Call) WithEffectiveCanisterID(canisterID principal.Principal) *Call {
c.effectiveCanisterID = canisterID
return c
Expand All @@ -491,7 +515,7 @@ type Config struct {
PollTimeout time.Duration
}

// Query is an intermediate representation of a query to a canister.
// Query is an intermediate representation of a Query to a canister.
type Query struct {
a *Agent
methodName string
Expand Down
33 changes: 26 additions & 7 deletions agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ package agent_test
import (
"encoding/json"
"fmt"
"testing"

"github.com/aviate-labs/agent-go"
"github.com/aviate-labs/agent-go/candid/idl"
"github.com/aviate-labs/agent-go/certification/hashtree"
"github.com/aviate-labs/agent-go/ic"
mgmt "github.com/aviate-labs/agent-go/ic/ic"
ic0 "github.com/aviate-labs/agent-go/ic/ic"
"github.com/aviate-labs/agent-go/ic/icpledger"
"github.com/aviate-labs/agent-go/identity"
"github.com/aviate-labs/agent-go/principal"
"testing"
)

var _ = new(testLogger)
Expand Down Expand Up @@ -98,14 +100,31 @@ func Example_query_secp256k1() {
// 0
}

func TestAgent_Call(t *testing.T) {
a, err := agent.New(agent.DefaultConfig)
if err != nil {
t.Fatal(err)
}
n, err := a.ReadStateCertificate(ic.REGISTRY_PRINCIPAL, [][]hashtree.Label{{hashtree.Label("subnet")}})
if err != nil {
t.Fatal(err)
}
for _, path := range hashtree.ListPaths(n, nil) {
if len(path) == 3 && string(path[0]) == "subnet" && string(path[2]) == "public_key" {
subnetID := principal.Principal{Raw: []byte(path[1])}
_ = subnetID
}
}
}

func TestAgent_Call_bitcoinGetBalanceQuery(t *testing.T) {
a, err := mgmt.NewAgent(ic.MANAGEMENT_CANISTER_PRINCIPAL, agent.DefaultConfig)
a, err := ic0.NewAgent(ic.MANAGEMENT_CANISTER_PRINCIPAL, agent.DefaultConfig)
if err != nil {
t.Fatal(err)
}
r, err := a.BitcoinGetBalanceQuery(mgmt.BitcoinGetBalanceQueryArgs{
r, err := a.BitcoinGetBalanceQuery(ic0.BitcoinGetBalanceQueryArgs{
Address: "bc1qruu3xmfrt4nzkxax3lpxfmjega87jr3vqcwjn9",
Network: mgmt.BitcoinNetwork{
Network: ic0.BitcoinNetwork{
Mainnet: new(idl.Null),
},
})
Expand All @@ -118,11 +137,11 @@ func TestAgent_Call_bitcoinGetBalanceQuery(t *testing.T) {
}

func TestAgent_Call_provisionalTopUpCanister(t *testing.T) {
a, err := mgmt.NewAgent(ic.MANAGEMENT_CANISTER_PRINCIPAL, agent.DefaultConfig)
a, err := ic0.NewAgent(ic.MANAGEMENT_CANISTER_PRINCIPAL, agent.DefaultConfig)
if err != nil {
t.Fatal(err)
}
if err := a.ProvisionalTopUpCanister(mgmt.ProvisionalTopUpCanisterArgs{
if err := a.ProvisionalTopUpCanister(ic0.ProvisionalTopUpCanisterArgs{
CanisterId: ic.LEDGER_PRINCIPAL,
}); err == nil {
t.Fatal()
Expand Down
16 changes: 16 additions & 0 deletions certification/hashtree/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ func DomainSeparator(t string) []byte {
)
}

// ListPaths returns all paths from the root to a leaf node.
func ListPaths(n Node, path []Label) [][]Label {
switch n := n.(type) {
case Fork:
l := ListPaths(n.LeftTree, path)
r := ListPaths(n.RightTree, path)
return append(l, r...)
case Labeled:
return ListPaths(n.Tree, append(path, n.Label))
case Leaf:
return [][]Label{path}
default: // Empty, Pruned
return nil
}
}

func Serialize(node Node) ([]byte, error) {
return cbor.Marshal(serialize(node))
}
Expand Down
38 changes: 19 additions & 19 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,7 @@ func NewClientWithLogger(cfg ClientConfig, logger Logger) Client {
}
}

// Status returns the status of the IC.
func (c Client) Status() (*Status, error) {
raw, err := c.get("/api/v2/status")
if err != nil {
return nil, err
}
var status Status
return &status, cbor.Unmarshal(raw, &status)
}

func (c Client) call(canisterID principal.Principal, data []byte) ([]byte, error) {
func (c Client) Call(canisterID principal.Principal, data []byte) ([]byte, error) {
u := c.url(fmt.Sprintf("/api/v2/canister/%s/call", canisterID.Encode()))
c.logger.Printf("[CLIENT] CALL %s", u)
resp, err := c.client.Post(u, "application/cbor", bytes.NewBuffer(data))
Expand All @@ -73,6 +63,24 @@ func (c Client) call(canisterID principal.Principal, data []byte) ([]byte, error
}
}

func (c Client) Query(canisterID principal.Principal, data []byte) ([]byte, error) {
return c.post("query", canisterID, data)
}

func (c Client) ReadState(canisterID principal.Principal, data []byte) ([]byte, error) {
return c.post("read_state", canisterID, data)
}

// Status returns the status of the IC.
func (c Client) Status() (*Status, error) {
raw, err := c.get("/api/v2/status")
if err != nil {
return nil, err
}
var status Status
return &status, cbor.Unmarshal(raw, &status)
}

func (c Client) get(path string) ([]byte, error) {
c.logger.Printf("[CLIENT] GET %s", c.url(path))
resp, err := c.client.Get(c.url(path))
Expand All @@ -98,14 +106,6 @@ func (c Client) post(path string, canisterID principal.Principal, data []byte) (
}
}

func (c Client) query(canisterID principal.Principal, data []byte) ([]byte, error) {
return c.post("query", canisterID, data)
}

func (c Client) readState(canisterID principal.Principal, data []byte) ([]byte, error) {
return c.post("read_state", canisterID, data)
}

func (c Client) url(p string) string {
u := *c.config.Host
u.Path = path.Join(u.Path, p)
Expand Down
12 changes: 6 additions & 6 deletions gen/templates/agent.gotmpl
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ type {{ .Name }} {{ if .Eq }}= {{end}}{{ .Type }}

// {{ .AgentName }}Agent is a client for the "{{ .CanisterName }}" canister.
type {{ .AgentName }}Agent struct {
a *agent.Agent
canisterId principal.Principal
*agent.Agent
CanisterId principal.Principal
}

// New{{ .AgentName }}Agent creates a new agent for the "{{ .CanisterName }}" canister.
Expand All @@ -26,8 +26,8 @@ func New{{ .AgentName }}Agent(canisterId principal.Principal, config agent.Confi
return nil, err
}
return &{{ .AgentName }}Agent{
a: a,
canisterId: canisterId,
Agent: a,
CanisterId: canisterId,
}, nil
}
{{- range .Methods }}
Expand All @@ -37,8 +37,8 @@ func (a {{ $.AgentName }}Agent) {{ .Name }}({{ range $i, $e := .ArgumentTypes }}
{{ range $i, $e := .ReturnTypes -}}
var r{{ $i }} {{ $e }}
{{ end -}}
if err := a.a.{{ .Type }}(
a.canisterId,
if err := a.Agent.{{ .Type }}(
a.CanisterId,
"{{ .RawName }}",
[]any{{ "{" }}{{ range $i, $e := .ArgumentTypes }}{{ if $i }}, {{ end }}{{ $e.Name }}{{ end }}{{ "}" }},
[]any{{ "{" }}{{ range $i, $e := .ReturnTypes }}{{ if $i }}, {{ end }}&r{{ $i }}{{ end }}{{ "}"}},
Expand Down
16 changes: 8 additions & 8 deletions gen/templates/agent_indirect.gotmpl
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ type {{ .Name }} {{ if .Eq }}= {{end}}{{ .Type }}

// {{ .AgentName }}Agent is a client for the "{{ .CanisterName }}" canister.
type {{ .AgentName }}Agent struct {
a *agent.Agent
canisterId principal.Principal
*agent.Agent
CanisterId principal.Principal
}

// New{{ .AgentName }}Agent creates a new agent for the "{{ .CanisterName }}" canister.
Expand All @@ -26,8 +26,8 @@ func New{{ .AgentName }}Agent(canisterId principal.Principal, config agent.Confi
return nil, err
}
return &{{ .AgentName }}Agent{
a: a,
canisterId: canisterId,
Agent: a,
CanisterId: canisterId,
}, nil
}
{{- range .Methods }}
Expand All @@ -37,8 +37,8 @@ func (a {{ $.AgentName }}Agent) {{ .Name }}({{ range $i, $e := .ArgumentTypes }}
{{ range $i, $e := .ReturnTypes -}}
var r{{ $i }} {{ $e }}
{{ end -}}
if err := a.a.{{ .Type }}(
a.canisterId,
if err := a.Agent.{{ .Type }}(
a.CanisterId,
"{{ .RawName }}",
[]any{{ "{" }}{{ range $i, $e := .ArgumentTypes }}{{ if $i }}, {{ end }}{{ $e.Name }}{{ end }}{{ "}" }},
[]any{{ "{" }}{{ range $i, $e := .ReturnTypes }}{{ if $i }}, {{ end }}&r{{ $i }}{{ end }}{{ "}"}},
Expand All @@ -50,8 +50,8 @@ func (a {{ $.AgentName }}Agent) {{ .Name }}({{ range $i, $e := .ArgumentTypes }}

// {{ .Name }}{{ .Type }} creates an indirect representation of the "{{ .RawName }}" method on the "{{ $.CanisterName }}" canister.
func (a {{ $.AgentName }}Agent) {{ .Name }}{{ .Type }}({{ range $i, $e := .ArgumentTypes }}{{ if $i }}, {{ end }}{{ $e.Name }} {{ $e.Type }}{{ end }}) (*agent.{{ .Type }},error) {
return a.a.Create{{ .Type }}(
a.canisterId,
return a.Agent.Create{{ .Type }}(
a.CanisterId,
"{{ .RawName }}",{{ range $i, $e := .ArgumentTypes }}
{{ $e.Name }},{{ end }}
)
Expand Down
Loading
Loading