mirror of
https://github.com/luxfi/broker.git
synced 2026-09-24 00:25:18 +00:00
Pass 2 — every endpoint method is fully wired against the TransactAPI
public REST surface; the encrypted-webhook consumer is fully
implemented per the documented AES-256-CBC envelope; the conformance
suite drives every endpoint against httptest.Server fixtures with no
production HTTP traffic.
Endpoints (all fully implemented, no stubs):
Party / Entity
CreateParty, CreateEntity, GetParty, ListParties (paginated)
KYC / AML / Accredited / Suitability
PerformKYC, PerformAML
PerformAccredited (income, net_worth, third_party_letter,
professional_license) + PerformAccreditedFull
Suitability
Offerings
CreateOffering, GetOffering, ListOfferings (paginated)
Trades
CreateTrade, GetTrade, BulkUploadTrades (multipart),
CancelTrade, RefundTrade,
SendSubscriptionDocs, GetTradeDocuments
Custody
OpenCustodyAccount, GetCustodyAccount
ATS / Secondary
PublishATSEvent (uses EventID as the natural idem-key),
GetSecondaryTrades
Admin
UpdateWebhookAuthKey
Webhook
ConsumeWebhook — full AES-256-CBC decryption per the documented
TransactAPI scheme: URL-safe Base64 decode, undo "plusencr" → "+"
substitution, split 16-byte IV, AES-256-CBC decrypt, PKCS#7 unpad
(constant-time), parse "k=v, k=v, …" plaintext into the broker-wide
WebhookEvent shape. HMAC-SHA256 signature gate runs when
WebhookAuthKey is configured, with comma-separated key rotation
overlap support.
Cross-cutting:
- Uniform pagination: list endpoints iterate offset/limit internally
until a short page or MaxRecords cap; callers receive complete
result sets without writing pagination logic.
- Rate-limiting + retry: exponential backoff with full jitter on 429
and 5xx, honoring Retry-After (delta-seconds and HTTP-date); after
the retry budget surfaces wrapped ErrRateLimited.
- Idempotency: deriveIdempotencyKey(orgID, endpoint, canonicalBody)
SHA-256 fallback on every mutating call; caller-supplied
IdempotencyKey always wins. ATS PublishATSEvent uses EventID
directly so duplicate events collapse upstream.
- Authentication: clientID + developerAPIKey injected as form fields
on every legacy v1 request; Bearer + X-Client-Id on the modern v3
transport.
- APIError carries StatusCode, Endpoint, Body, RetryAfter for
errors.As recovery; envelope-level TransactAPI failures
(statusCode != "101") are surfaced through the same shape.
Conformance suite (broker/pkg/provider/northcapital/conformance_test.go):
- Every endpoint's happy path with form-field + idempotency-header
assertions
- All four accredited methods exercised independently
- Bulk upload exercises the multipart/form-data path
- Pagination iteration across multiple pages
- 4xx mapping → *APIError; envelope-level errors mapped identically
- 429 retry-then-succeed; 429 budget exhausted → ErrRateLimited
- Retry-After parsing
- Webhook signature: missing, bad, valid, rotation overlap
- Webhook decryption: valid envelope, wrong key, invalid base64,
plusencr substitution path, missing config
- PKCS#7 unpadder unit tests (positive + 4 negative cases)
Build green: go build ./..., go vet ./..., go test -race ./pkg/provider/
northcapital/... all pass. 40 test cases pass, 0 failures.
Assumptions pinned for the NCPS sandbox handshake:
1. Legacy v1 endpoints use form-encoded bodies with clientID +
developerAPIKey carried as form fields on every call. Confirmed
against the public reference; pinned if the sandbox key issuance
diverges.
2. The webhook HMAC ordering is decrypt-then-MAC over the raw
envelope bytes. The public encrypted-webhooks guide is silent on
this point; if the sandbox reveals MAC-then-decrypt, swap the
ordering in ConsumeWebhook.
3. The X-TransactAPI-Signature header name is the Lux-side
convention pinned in the integration brief §7; remap if the
sandbox uses a different upstream name.
4. WebhookDecryptionKey is required to be exactly 32 bytes; the
public guide says NCPS pads server-side to 32, but the adapter
enforces 32 on the inbound to fail closed.
Source-of-design: Public-Spec
Source-ref: https://transactapi.readme.io/reference
Clean-Team-Member: dev-agent (pass 2 — full implementation)
Signed-off-by: dev <[email protected]>
137 lines
4.0 KiB
Go
137 lines
4.0 KiB
Go
// ATS / Secondary trades — TransactAPI Workstream 7.
|
|
//
|
|
// Endpoints / channels:
|
|
// POST /tapiv3/index.php/v1/publishAtsEvent — Lux-originated ATS event
|
|
// POST /tapiv3/index.php/v1/getSecondaryTrades — Secondary Trades Directory
|
|
//
|
|
// The ATS webhook channel is the inbound complement, handled by the
|
|
// Provider.ConsumeWebhook entry point (see webhook.go). Events flow
|
|
// outbound (Lux → TransactAPI) on order placement / cancellation /
|
|
// match / clear / settle so the NCPS-side ATS record stays in lockstep
|
|
// with the Lux on-chain compliance-module state.
|
|
//
|
|
// Source-of-design: Public-Spec
|
|
// Source-ref: https://transactapi.readme.io/reference
|
|
|
|
package northcapital
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
)
|
|
|
|
type wireSecondaryTrade struct {
|
|
TradeID string `json:"tradeId"`
|
|
OfferingID string `json:"offeringId"`
|
|
BuyerID string `json:"buyerPartyId"`
|
|
SellerID string `json:"sellerPartyId"`
|
|
Units string `json:"transactionUnits"`
|
|
UnitPrice string `json:"unitPrice"`
|
|
Currency string `json:"currency"`
|
|
Status string `json:"status"`
|
|
TradedAt string `json:"tradedAt"`
|
|
SettledAt string `json:"settledAt"`
|
|
}
|
|
|
|
// PublishATSEvent posts an ATS lifecycle event to TransactAPI's ATS
|
|
// channel. The EventID is the idempotency-key input so retries of the
|
|
// same logical event collapse on the NCPS side.
|
|
func (p *Provider) PublishATSEvent(ctx context.Context, evt *ATSEvent) error {
|
|
if evt == nil {
|
|
return errors.New("northcapital: ATSEvent is required")
|
|
}
|
|
if evt.EventID == "" {
|
|
return errors.New("northcapital: ATSEvent.EventID is required for idempotency")
|
|
}
|
|
form := url.Values{}
|
|
form.Set("eventId", evt.EventID)
|
|
form.Set("eventType", evt.EventType)
|
|
form.Set("offeringId", evt.OfferingID)
|
|
if evt.TradeID != "" {
|
|
form.Set("tradeId", evt.TradeID)
|
|
}
|
|
if evt.PartyID != "" {
|
|
form.Set("partyId", evt.PartyID)
|
|
}
|
|
if evt.EntityID != "" {
|
|
form.Set("entityId", evt.EntityID)
|
|
}
|
|
if evt.Side != "" {
|
|
form.Set("transactionType", evt.Side)
|
|
}
|
|
if evt.Units != "" {
|
|
form.Set("transactionUnits", evt.Units)
|
|
}
|
|
if evt.UnitPrice != "" {
|
|
form.Set("unitPrice", evt.UnitPrice)
|
|
}
|
|
if !evt.Timestamp.IsZero() {
|
|
form.Set("timestamp", evt.Timestamp.UTC().Format("2006-01-02T15:04:05Z"))
|
|
}
|
|
|
|
const path = "/tapiv3/index.php/v1/publishAtsEvent"
|
|
// EventID is the natural idempotency key — same event sent twice
|
|
// must collapse, regardless of caller-supplied IdempotencyKey.
|
|
raw, err := p.doForm(ctx, "POST", path, form, evt.EventID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := decodeEnvelope(path, raw); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetSecondaryTrades reads the Secondary Trades Directory for an Offering.
|
|
func (p *Provider) GetSecondaryTrades(ctx context.Context, offeringID string) ([]*SecondaryTrade, error) {
|
|
if offeringID == "" {
|
|
return nil, errors.New("northcapital: offeringID required")
|
|
}
|
|
form := url.Values{}
|
|
form.Set("offeringId", offeringID)
|
|
const path = "/tapiv3/index.php/v1/getSecondaryTrades"
|
|
raw, err := p.doForm(ctx, "POST", path, form, "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
env, err := decodeEnvelope(path, raw)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(env.Secondary) == 0 {
|
|
return nil, nil
|
|
}
|
|
var arr []wireSecondaryTrade
|
|
if err := json.Unmarshal(env.Secondary, &arr); err != nil {
|
|
var one wireSecondaryTrade
|
|
if err2 := json.Unmarshal(env.Secondary, &one); err2 == nil {
|
|
arr = []wireSecondaryTrade{one}
|
|
} else {
|
|
return nil, fmt.Errorf("northcapital: getSecondaryTrades decode: %w", err)
|
|
}
|
|
}
|
|
out := make([]*SecondaryTrade, 0, len(arr))
|
|
for i := range arr {
|
|
st := &SecondaryTrade{
|
|
ID: arr[i].TradeID,
|
|
OfferingID: arr[i].OfferingID,
|
|
BuyerID: arr[i].BuyerID,
|
|
SellerID: arr[i].SellerID,
|
|
Units: arr[i].Units,
|
|
UnitPrice: arr[i].UnitPrice,
|
|
Currency: arr[i].Currency,
|
|
Status: arr[i].Status,
|
|
TradedAt: parseDate(arr[i].TradedAt),
|
|
}
|
|
if arr[i].SettledAt != "" {
|
|
t := parseDate(arr[i].SettledAt)
|
|
st.SettledAt = &t
|
|
}
|
|
out = append(out, st)
|
|
}
|
|
return out, nil
|
|
}
|