SDKs
Go SDK
The Go SDK covers what your backend does on its side: calling the API, turning your custody’s signatures into authorizations, verifying webhooks and checking delegates on chain. It depends on nothing but the standard library and go-ethereum.
go get portuna.io/sdk/goWhat is inside
Section titled “What is inside”| Area | API |
|---|---|
| API client | NewClient, with a method for each request of the API; errors are *portuna.Error |
| Authorizations | AuthorizationDigest, AuthorizationFromSignature, ParseSignature, NormalizeS, Authorization.Verify |
| Revocations | RevocationDigest, RevocationFromSignature, Authorization.VerifyRevocation |
| Lists | Sweeps, Revocations, Transactions, LedgerEntries, WebhookDeliveries a page at a time; AllSweeps and the like through every page |
| Webhooks | ParseWebhook, VerifyWebhook, SignWebhook for tests; Event.Transaction() for a transaction event, its Sweeps() and Revocations(), FinalStatus; Event.Sweep() and the other decoders |
| Delegate check | VerifyDeployment, FactoryAddress, BatcherAddress, DelegateAddress for a set of hot wallets, CanonicalHotWallets, and the cmd/verify-delegate command |
Client
Section titled “Client”client := portuna.NewClient("https://api-testnet.portuna.io", os.Getenv("PORTUNA_API_KEY"))client.HTTPClient = &http.Client{Timeout: 30 * time.Second} // optional; http.DefaultClient otherwiseEvery method takes a context.Context. Methods: Balance, Tariff, Settings, UpdateSettings, HotWallets,
CreateHotWallet, Delegates, CreateDelegate, Tokens, CheckToken, EnableToken, DisableToken,
CreateSweep, Sweep, Sweeps, CreateSweepList, SweepList, CreateRevocation, Revocation, Revocations, Transaction, Transactions,
LedgerEntries, Usage, MonthlyReport,
Webhook, SetWebhook, DeleteWebhook, WebhookDeliveries, SendTestWebhook, Health and OpenAPI.
CreateSweep, CreateSweepList and CreateRevocation also return created: false when the request repeats an
earlier one, by its ExternalID or, for a list, the set of them, and the existing object came back.
Tokens: CheckToken(ctx, chainID, address) returns a token’s card, a TokenCard.
EnableToken(ctx, chainID, address) turns a base token on again; with portuna.Confirmed() as a last argument it
adds a token of your own, once you compared its card, and returns the Token and created, true for a token
added for the first time.
DisableToken(ctx, chainID, address) turns a base token off or removes your own. In these three the zero address is
the native coin. See Tokens.
client := portuna.NewClient(os.Getenv("PORTUNA_API_URL"), os.Getenv("PORTUNA_API_KEY"))
balance, err := client.Balance(ctx)if err != nil { log.Fatal(err)}fmt.Println("gas wallet:", balance.GasWallet.Hex())for _, c := range balance.Chains { fmt.Printf("%s: %s wei available for gas\n", c.Name, c.Available)}Sweeps, Revocations, Transactions, LedgerEntries and WebhookDeliveries return one page, a Page with Items and
NextCursor, empty on the last page. Their filters, such as SweepFilter, leave out the fields left zero. The All
methods, AllSweeps and the like, go through every page as an iterator and stop at the first error:
for sweep, err := range client.AllSweeps(ctx, portuna.SweepFilter{Status: portuna.SweepFailed}) { if err != nil { return err } log.Printf("sweep %s failed: %s", sweep.ID, sweep.Reason)}Sweep lists
Section titled “Sweep lists”CreateSweepList sends sweeps in one transaction of their own and returns the list, with its Transaction when your
gas wallet was free. The request may wait up to its Wait, 10 seconds when nil: give the call 60 seconds, in ctx
and in the timeout of HTTPClient if you set one. SweepList(ctx, id) gives a list as it is now, and
SweepFilter.ListID and TransactionFilter.ListID its sweeps and transactions. See
Sweep lists.
items := make([]portuna.SweepListItemRequest, 0, len(deposits))for _, d := range deposits { items = append(items, portuna.SweepListItemRequest{ ExternalID: d.id, // required; repeating the request with the same ids returns this same list HotWallet: hotWallet, Account: d.account, Token: "USDT", // the whole balance: no Amount })}wait := 10list, created, err := client.CreateSweepList(ctx, portuna.SweepListRequest{ChainID: bscTestnet, Wait: &wait, Items: items})if !created { fmt.Println("a repeat: the list as it is now, nothing sent again")}switch {case list.Transaction != nil: // sent: the transaction it rides; done: every item has its outcome, and this is the last one it rode. Keep // the transaction's ID: a replacement at a higher fee changes its Hash. fmt.Println(list.Status, list.Transaction.ID, list.Transaction.Hash)case list.Status == portuna.ListDone: fmt.Println("every item was rejected before sending")default: // queued or processing: the transaction comes in transaction.sent, with this list's list_id. fmt.Println("on its way:", list.ID)}for _, it := range list.Items { if it.Status == portuna.SweepRejected { // Its external id is used up: to sweep the address again, use a new one. fmt.Println(it.ExternalID, "rejected:", it.Reason) }}Errors
Section titled “Errors”A response other than 2xx is a *portuna.Error with StatusCode, Code and Message; with a 429 or a 503,
RetryAfter is how long its Retry-After asks to wait. portuna.ErrorCode(err) returns the code, or "" when err
is not an API error, for example a network failure. Codes and what to do:
Errors and retries.
Authorizations
Section titled “Authorizations”AuthorizationDigest gives the 32 bytes your custody signs. AuthorizationFromSignature takes the raw signature, DER
or r‖s, with any s, normalizes it, finds y_parity and fails unless the deposit address signed. Chain 0 is refused.
func signAuthorization(ctx context.Context, sign Signer, keyID string, deposit common.Address, chainID int64, delegate common.Address, nonce uint64) (portuna.Authorization, error) { digest, err := portuna.AuthorizationDigest(chainID, delegate, nonce) // refuses chain 0 if err != nil { return portuna.Authorization{}, err } sig, err := sign(ctx, keyID, digest[:]) if err != nil { return portuna.Authorization{}, err } // Reads DER or r‖s, moves s to the lower half and finds y_parity. Fails unless the deposit address // signed this very digest, so a wrong key never reaches the API. return portuna.AuthorizationFromSignature(chainID, delegate, nonce, deposit, sig)}More in Signing authorizations.
Webhooks
Section titled “Webhooks”ParseWebhook(secret, header, body) verifies the Portuna-Signature header against the raw body, within five
minutes, and decodes the event. event.Transaction() decodes a transaction.* event into a TransactionEvent: the
Transaction as it was at the event, Part of Parts, Test in the sample SendTestWebhook asks for, and its
items, which Sweeps() decodes into []SweepItem in batch order, or Revocations() into []RevocationItem, as
Transaction.Kind says. FinalStatus(status) tells a status that never changes: swept, revoked, failed,
rejected. event.Sweep() and event.Revocation() decode sweep.* and revocation.*, for those no transaction
carried; event.HotWallet(), event.Delegate(), event.Token(), event.TariffChange(), event.BalanceLow() and
event.Payout() decode the others. The constants EventTransactionMined, EventSweepRejected,
EventTokenRefused and so on name the event types, SignatureHeader, EventHeader and DeliveryHeader the
headers. See Webhooks for what a receiver must do.
http.HandleFunc("POST /hooks/sweeps", func(w http.ResponseWriter, r *http.Request) { // Verify the body exactly as it arrived, before parsing it. Bodies go up to 256 KiB; this allows 1 MiB. body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { http.Error(w, "cannot read the body", http.StatusBadRequest) return } event, err := portuna.ParseWebhook(secret, r.Header.Get(portuna.SignatureHeader), body) if err != nil { http.Error(w, "bad signature", http.StatusUnauthorized) return } // Delivery is at least once: an event may come again, with the same id. if handled(event.ID) { w.WriteHeader(http.StatusNoContent) return } switch event.Type { case portuna.EventTransactionSent, portuna.EventTransactionMined, portuna.EventTransactionReverted, portuna.EventTransactionDropped: // One event per transaction, with every sweep it carries. tx, err := event.Transaction() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } if tx.Transaction.Kind != portuna.TransactionSweep { break // revocations: tx.Revocations() } sweeps, err := tx.Sweeps() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } for _, s := range sweeps { // processing in transaction.sent; swept or failed in transaction.mined; queued or failed in // transaction.reverted and transaction.dropped. apply(s.ID, s.Status) log.Printf("sweep %s (%s), transaction %d #%d: %s %s %s", s.ID, s.ExternalID, tx.Transaction.ID, s.BatchIndex, s.Status, s.SweptAmount, s.Reason) } case portuna.EventSweepRejected, portuna.EventSweepFailed: // A sweep that ended before any transaction carried it. sweep, err := event.Sweep() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } apply(sweep.ID, sweep.Status) log.Printf("sweep %s (%s): %s %s", sweep.ID, sweep.ExternalID, sweep.Status, sweep.Reason) case portuna.EventBalanceLow: alert, err := event.BalanceLow() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } log.Printf("top up the gas wallet on chain %d: %s wei left", alert.ChainID, alert.Balance) default: // Other and future event types: accept them. } markHandled(event.ID) w.WriteHeader(http.StatusNoContent)})Delegate check
Section titled “Delegate check”VerifyDeployment computes your batcher and the hot wallet’s delegate from the bytecode built into the SDK and checks
them on chain; cmd/verify-delegate does the same from the command line. See
Verifying the delegate.
eth, err := ethclient.DialContext(ctx, os.Getenv("RPC_URL"))if err != nil { log.Fatal(err)}var hotWallets []common.Addressfor _, h := range strings.Split(os.Getenv("HOT_WALLETS"), ",") { hotWallets = append(hotWallets, common.HexToAddress(strings.TrimSpace(h)))}report, err := portuna.VerifyDeployment(ctx, eth, portuna.Deployment{ GasWallet: common.HexToAddress(os.Getenv("GAS_WALLET")), HotWallets: hotWallets, ExpectDelegate: common.HexToAddress(os.Getenv("DELEGATE")),})if err != nil { log.Fatal(err)}for _, c := range report.Checks { fmt.Println(c.OK, c.Name, c.Detail)}if !report.OK() { log.Fatal("do not sign authorizations for this delegate")}