SPB Git

Repository Public

DerivativesGMXAPI.swift 19.8 KB 263 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Derivatives/DerivativesGMXAPI.swift3// Description: GMX v2 on Arbitrum — every route of `gmxRoutes` (services/api/src/derivatives/gmx-routes.ts, gmx-exec.ts). GMX has4//              no venue account: the account is the wallet's own address and an order is a wallet transaction (a wallet intent5//              with a `gmx` section) that a GMX keeper executes or cancels later. Off unless the server settings and a venue6//              policy approved by passkey allow it; the web interface does not offer GMX today (apps/web/src/venues.ts).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112public struct GmxAuthorizationPreparation: Sendable {13    public let approval: VerifiedApproval<GmxAuthorization>14    /** The text to DISPLAY before the passkey is asked. */15    public let acknowledgement: JurisdictionAck16    /** The execution-fee ceiling the server put in the policy, in ETH (it is part of what is approved). */17    public let maxExecutionFeeEth: String18    public var authorization: GmxAuthorization { approval.object }19}2021/** A verified GMX intent, ready for the passkey. Built only by the prepare functions. */22public struct GmxOrderApproval: Sendable {23    public let operationId: String24    public let approval: VerifiedApproval<Intent>25    public var intent: Intent { approval.object }26}2728public struct GmxOrderPreparation: Sendable {29    public let operation: GmxOperation30    /** Every figure an estimate, as served. */31    public let estimate: JSONValue?32    /** The server's own labelled reading of what the passkey signs, and of what the signer fixes itself (receiver = the wallet, no callback…). */33    public let fields: [GmxField]34    public let fixed: [GmxField]35    /** Nil when there is nothing (left) to approve (a key that was already used and is past approval). */36    public let approvable: GmxOrderApproval?37}3839public struct GmxRiskApproval: Sendable {40    public let approval: VerifiedApproval<GmxRiskIntent>41    public var intent: GmxRiskIntent { approval.object }42}4344public enum GmxRiskPreparation: Sendable {45    case notNeeded46    case approval(GmxRiskApproval)47}4849public struct DerivativesGMXAPI: Sendable {50    let client: APIClient51    public init(_ client: APIClient) { self.client = client }5253    private static let base = "/derivatives/gmx"54    /** `GMX_POLICY_BOUNDS.maxExecutionFeeWei`: 0.002 ETH whatever the authorization says. */55    static let maxExecutionFeeWei = BaseUnits(2_000_000_000_000_000)56    private var rpId: String { client.configuration.rpId }57    private func q(_ locale: String?) -> [String: String?] { ["locale": locale] }5859    // MARK: reads6061    /** Works with every lock closed: the two server settings, the blockers with their sentences, pins, wallet, authorization, markets, positions read on-chain, operations. */62    public func status(locale: String? = nil) async throws -> GmxStatus { try await client.get("\(Self.base)/status", query: q(locale)) }6364    public func jurisdiction() async throws -> GmxJurisdictionAnswer { try await client.get("\(Self.base)/jurisdiction") }6566    public func operation(_ operationId: String) async throws -> GmxOperation {67        try await client.get("\(Self.base)/operations/\(APIClient.segment(operationId))", as: GmxOperationAnswer.self).operation68    }6970    // MARK: venue policy7172    /**73     Step 1 of enabling GMX: the venue policy with exactly the limits asked, for the wallet's own address and the contract set the74     status lists, committing to the acknowledgement text that will be displayed.75     - Parameter ownAddress: the wallet's own Arbitrum address as the app knows it from the wallet.76     */77    public func prepareAuthorization(_ request: GmxAuthorizationRequest, status: GmxStatus, ownAddress: String, now: Date = Date()) async throws -> GmxAuthorizationPreparation {78        struct Answer: Decodable, Sendable { let authorization: GmxAuthorization; let hash: String?; let ack: JurisdictionAck; let options: PasskeyRequestOptions; let maxExecutionFeeEth: String }79        let a: Answer = try await client.post("\(Self.base)/authorization/prepare", body: request)80        try Self.check(authorization: a.authorization, request: request, status: status, ownAddress: ownAddress, maxExecutionFeeEth: a.maxExecutionFeeEth, now: now)81        try DerivApproval.requireAck(a.ack, sha: a.authorization.ackSha256, venue: "gmx", locale: request.locale)82        try DerivApproval.requireHash(a.hash, of: a.authorization)83        return GmxAuthorizationPreparation(approval: try ApprovalBinding.verify(a.authorization, options: a.options, rpId: rpId), acknowledgement: a.ack, maxExecutionFeeEth: a.maxExecutionFeeEth)84    }8586    public static func check(authorization x: GmxAuthorization, request r: GmxAuthorizationRequest, status s: GmxStatus, ownAddress: String, maxExecutionFeeEth: String, now: Date) throws {87        guard x.account == ownAddress.lowercased() else { throw DerivApproval.no("account is not the wallet's own address") }88        if let me = s.account?.address { guard DerivApproval.sameAddress(me, ownAddress) else { throw DerivApproval.no("account") } }89        guard x.contracts == s.pins.id, let router = s.contract("exchangeRouter"), x.exchangeRouter == router else { throw DerivApproval.no("contract set") }90        let p = x.policy91        guard Set(p.allowedMarkets.map { $0.lowercased() }) == Set(r.allowedMarkets.map { $0.lowercased() }), p.allowedMarkets.count == r.allowedMarkets.count else { throw DerivApproval.no("markets") }92        guard p.maxLeverage == r.maxLeverage, VenueDecimal.same(p.maxOrderSizeUsd, r.maxOrderSizeUsd), p.maxOrdersPerDay == r.maxOrdersPerDay, p.maxPriceDeviationBps == r.maxPriceDeviationBps else { throw DerivApproval.no("limits") }93        guard let fee = try? BaseUnits(p.maxExecutionFeeWei), !fee.isZero, fee <= maxExecutionFeeWei, VenueDecimal.same(fee.formatted(decimals: 18), maxExecutionFeeEth) else { throw DerivApproval.no("execution fee ceiling") }94        guard x.expiresAt - x.createdAt == r.days * 86_400 else { throw DerivApproval.no("duration") }95        guard x.expiry > now else { throw ApprovalError.expired }96    }9798    /** Step 2: the signer verifies the passkey over the same bytes, the account, the contract set and the acknowledgement hash. The authorization goes back as served. */99    public func approveAuthorization(_ p: GmxAuthorizationPreparation, acknowledged: Bool, with authenticator: PasskeyAuthenticator, locale: String? = nil, now: Date = Date()) async throws -> GmxStatus {100        struct Body: Encodable, Sendable { let authorization: JSONValue; let assertion: PasskeyAssertion }101        guard acknowledged else { throw ApprovalError.inconsistent("the jurisdiction summary was not acknowledged") }102        guard p.authorization.expiry > now else { throw ApprovalError.expired }103        let assertion = try await DerivApproval.assertion(p.approval.options, client, authenticator)104        return try await client.send(.post, "\(Self.base)/authorization/approve", query: q(locale), body: Body(authorization: p.authorization.served, assertion: assertion))105    }106107    /** Stopping never needs a passkey, a server setting or a readable chain. */108    public func revokeAuthorization(locale: String? = nil) async throws -> GmxStatus { try await client.send(.post, "\(Self.base)/authorization/revoke", query: q(locale)) }109110    // MARK: orders111112    /** Estimates, the risk verdict, the blockers and what the signer's venue policy would refuse; nothing is stored. */113    public func previewOrder(_ request: GmxOrderRequest) async throws -> GmxOrderPreview { try await client.post("\(Self.base)/orders/preview", body: request) }114115    private struct Prepared: Decodable, Sendable { let operation: GmxOperation; let intent: Intent; let estimate: JSONValue?; let fields: [GmxField]?; let fixed: [GmxField]?; let options: PasskeyRequestOptions? }116117    private func preparation(_ a: Prepared, check: (Intent) throws -> Void) throws -> GmxOrderPreparation {118        var approvable: GmxOrderApproval?119        if let options = a.options {120            try check(a.intent)121            if let p = a.operation.proposalId { guard p == a.intent.proposalId else { throw DerivApproval.no("operation") } }122            try DerivApproval.requireHash(a.operation.hash, of: a.intent)123            approvable = GmxOrderApproval(operationId: a.operation.id, approval: try ApprovalBinding.verify(a.intent, options: options, rpId: rpId))124        }125        return GmxOrderPreparation(operation: a.operation, estimate: a.estimate, fields: a.fields ?? [], fixed: a.fixed ?? [], approvable: approvable)126    }127128    /** Prepare a market increase or decrease. The intent must be this order, on the pinned contracts of `status`, from the wallet's own address. */129    public func prepareOrder(_ request: GmxOrderRequest, status: GmxStatus, ownAddress: String, idempotencyKey: String, now: Date = Date()) async throws -> GmxOrderPreparation {130        let a: Prepared = try await client.post("\(Self.base)/orders", body: request, idempotencyKey: idempotencyKey)131        return try preparation(a) { try Self.check(order: $0, request: request, status: status, ownAddress: ownAddress, now: now) }132    }133134    /** Prepare the decrease of `fraction` of the position the owner is looking at. */135    public func prepareClose(_ request: GmxCloseRequest, position: GmxPositionView, status: GmxStatus, ownAddress: String, idempotencyKey: String, now: Date = Date()) async throws -> GmxOrderPreparation {136        let a: Prepared = try await client.post("\(Self.base)/positions/close", body: request, idempotencyKey: idempotencyKey)137        return try preparation(a) { i in138            guard DerivApproval.sameAddress(position.market, request.market), position.side == request.side.rawValue else { throw DerivApproval.no("position") }139            try Self.check(order: i, request: .decrease(market: request.market, side: request.side, sizeUsd: position.sizeUsd, slippageBps: request.slippageBps), status: status, ownAddress: ownAddress, now: now)140            if VenueDecimal(request.fraction) == VenueDecimal("1") {141                guard i.gmx?.sizeDeltaUsd == VenueDecimal(position.sizeUsd)?.units(decimals: 30) else { throw DerivApproval.no("size") }142            }143        }144    }145146    /** Prepare the cancellation of a still-pending order of this wallet (possible for a market order only after GMX's request expiration). */147    public func prepareCancel(of target: GmxOperation, status: GmxStatus, ownAddress: String, now: Date = Date()) async throws -> GmxOrderPreparation {148        let a: Prepared = try await client.post("\(Self.base)/orders/\(APIClient.segment(target.id))/cancel")149        return try preparation(a) { try Self.check(cancel: $0, target: target, status: status, ownAddress: ownAddress, now: now) }150    }151152    /** What every GMX intent must be, whatever its action: this wallet, Arbitrum, the pinned contracts, the active authorization. */153    static func checkCommon(_ i: Intent, status s: GmxStatus, ownAddress: String, now: Date) throws -> (Intent.GMX, GmxStatus.Authorization) {154        guard i.kind == .gmx, let g = i.gmx, i.evm != nil, i.memo == nil else { throw DerivApproval.no("not a GMX order") }155        guard i.network == s.network, i.chainRef == String(s.chainId), g.venue == "gmx-v2" else { throw DerivApproval.no("network") }156        guard DerivApproval.sameAddress(i.from, ownAddress) else { throw DerivApproval.no("source is not the wallet's own address") }157        if let me = s.account?.address { guard DerivApproval.sameAddress(me, ownAddress) else { throw DerivApproval.no("account") } }158        guard let auth = s.authorization, auth.state == "active", g.authorizationId == auth.id else { throw DerivApproval.no("authorization") }159        guard let exchange = s.contract("exchangeRouter"), let router = s.contract("router"), let vault = s.contract("orderVault"),160              g.exchangeRouter == exchange, g.router == router, g.orderVault == vault, i.to == exchange else { throw DerivApproval.no("contracts") }161        guard g.triggerPrice == "0" else { throw DerivApproval.no("trigger price") }162        guard i.expiry > now else { throw ApprovalError.expired }163        return (g, auth)164    }165166    public static func check(order i: Intent, request r: GmxOrderRequest, status s: GmxStatus, ownAddress: String, now: Date) throws {167        let (g, auth) = try checkCommon(i, status: s, ownAddress: ownAddress, now: now)168        guard g.action == r.action.rawValue, g.orderKey == nil else { throw DerivApproval.no("action") }169        guard let m = s.markets.first(where: { DerivApproval.sameAddress($0.market, r.market) }), DerivApproval.sameAddress(g.market, m.market) else { throw DerivApproval.no("market") }170        guard g.isLong == (r.side == .long) else { throw DerivApproval.no("side") }171        guard g.orderType == (r.action == .increase ? "MarketIncrease" : "MarketDecrease") else { throw DerivApproval.no("order type") }172        guard let c = m.collateral.first(where: { DerivApproval.sameAddress($0.token, g.collateralToken) }), DerivApproval.sameAddress(i.asset, c.token), i.symbol == c.symbol, i.decimals == c.decimals else { throw DerivApproval.no("collateral token") }173        guard let size = try? BaseUnits(g.sizeDeltaUsd), !size.isZero else { throw DerivApproval.no("size") }174        switch r.action {175        case .increase:176            guard let collateral = r.collateral, let cd = VenueDecimal(collateral), cd.isPositive, i.amount == cd.units(decimals: c.decimals) else { throw DerivApproval.no("collateral") }177            let want: String?178            switch (r.sizeUsd, r.leverage) {179            case let (s?, nil): want = VenueDecimal(s)?.units(decimals: 30)180            // gmx-exec.ts: size = collateral × leverage cut to cents, never rounded up181            case let (nil, l?): want = VenueDecimal(l).flatMap { cd.multiplied(by: $0).truncated(toDecimals: 2).units(decimals: 30) }182            default: throw DerivApproval.no("give the leverage or the size, not both")183            }184            guard let want, g.sizeDeltaUsd == want else { throw DerivApproval.no("size") }185        case .decrease:186            guard i.amount == "0", g.approveGas == "0" else { throw DerivApproval.no("a decrease sends no collateral") }187            // the server closes at most the position: the size signed is never above the size asked188            if let asked = r.sizeUsd { guard let cap = VenueDecimal(asked)?.units(decimals: 30).flatMap({ try? BaseUnits($0) }), size <= cap else { throw DerivApproval.no("size") } }189        }190        if let ceiling = auth.policy.maxExecutionFeeWei { guard let fee = try? BaseUnits(g.executionFee), let max = try? BaseUnits(ceiling), fee <= max else { throw DerivApproval.no("execution fee") } }191        guard let fee = try? BaseUnits(g.executionFee), fee <= maxExecutionFeeWei else { throw DerivApproval.no("execution fee") }192    }193194    public static func check(cancel i: Intent, target: GmxOperation, status s: GmxStatus, ownAddress: String, now: Date) throws {195        let (g, _) = try checkCommon(i, status: s, ownAddress: ownAddress, now: now)196        guard g.action == "cancel", g.orderType == "None" else { throw DerivApproval.no("action") }197        guard let key = target.orderKey, g.orderKey == key else { throw DerivApproval.no("order key") }198        guard i.amount == "0", i.asset == "native", g.sizeDeltaUsd == "0", g.executionFee == "0", g.approveGas == "0" else { throw DerivApproval.no("a cancellation moves nothing out of the wallet") }199    }200201    /** The passkey assertion over the intent hash is the approval. `created` is not `executed`: follow the operation. */202    public func approve(_ o: GmxOrderApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> GmxOperation {203        guard o.intent.expiry > now else { throw ApprovalError.expired }204        let assertion = try await DerivApproval.assertion(o.approval.options, client, authenticator)205        return try await client.post("\(Self.base)/operations/\(APIClient.segment(o.operationId))/approve", body: DerivAssertionBody(assertion: assertion), as: GmxOperationAnswer.self).operation206    }207208    /** Withdraw an operation that is still waiting for the passkey: nothing was signed. */209    public func withdraw(_ operationId: String) async throws -> GmxOperation {210        try await client.post("\(Self.base)/operations/\(APIClient.segment(operationId))/withdraw", as: GmxOperationAnswer.self).operation211    }212213    // MARK: kill switch and loss limits (new risk only)214215    /** Stops NEW GMX positions — no passkey. It cancels nothing and closes nothing. */216    public func halt(reason: String, locale: String? = nil) async throws -> GmxStatus {217        struct Body: Encodable, Sendable { let reason: String }218        return try await client.send(.post, "\(Self.base)/halt", query: q(locale), body: Body(reason: reason))219    }220221    private struct LimitsBody: Encodable, Sendable { let maxDailyLoss: String; let maxTotalLoss: String }222223    /** Tightening is free; a higher loss limit is refused with `passkey_required`: use `prepareLimits`. */224    public func setLimits(maxDailyLoss: String, maxTotalLoss: String, locale: String? = nil) async throws -> GmxStatus {225        try await client.send(.post, "\(Self.base)/limits", query: q(locale), body: LimitsBody(maxDailyLoss: maxDailyLoss, maxTotalLoss: maxTotalLoss))226    }227228    public func prepareLimits(maxDailyLoss: String, maxTotalLoss: String, status: GmxStatus, now: Date = Date()) async throws -> GmxRiskPreparation {229        try await prepareRisk(.limits, path: "limits/prepare", body: LimitsBody(maxDailyLoss: maxDailyLoss, maxTotalLoss: maxTotalLoss), status: status, now: now)230    }231    public func prepareResume(status: GmxStatus, now: Date = Date()) async throws -> GmxRiskPreparation {232        try await prepareRisk(.resume, path: "resume/prepare", body: nil, status: status, now: now)233    }234235    private func prepareRisk(_ kind: GmxRiskIntent.Kind, path: String, body: LimitsBody?, status: GmxStatus, now: Date) async throws -> GmxRiskPreparation {236        struct Answer: Decodable, Sendable { let needed: Bool; let intent: GmxRiskIntent?; let hash: String?; let options: PasskeyRequestOptions? }237        let a: Answer = try await client.post("\(Self.base)/\(path)", body: body)238        guard a.needed else { return .notNeeded }239        guard let intent = a.intent, let options = a.options else { throw ApprovalError.unsupported("the server asked for an approval without the object to approve") }240        try Self.check(risk: intent, kind: kind, limits: body.map { ($0.maxDailyLoss, $0.maxTotalLoss) }, status: status, now: now)241        try DerivApproval.requireHash(a.hash, of: intent)242        return .approval(GmxRiskApproval(approval: try ApprovalBinding.verify(intent, options: options, rpId: rpId)))243    }244245    public static func check(risk i: GmxRiskIntent, kind: GmxRiskIntent.Kind, limits: (maxDailyLoss: String, maxTotalLoss: String)?, status s: GmxStatus, now: Date) throws {246        guard i.kind == kind else { throw DerivApproval.no("kind of change") }247        guard let auth = s.authorization, i.authorizationId == auth.id else { throw DerivApproval.no("authorization") }248        switch kind {249        case .limits:250            guard let limits, let l = i.limits, VenueDecimal.same(l.maxDailyLoss, limits.maxDailyLoss), VenueDecimal.same(l.maxTotalLoss, limits.maxTotalLoss) else { throw DerivApproval.no("limits") }251        case .resume:252            guard let halt = s.risk?.halt, i.subject == halt else { throw DerivApproval.no("halt") }253        }254        guard i.expiry > now else { throw ApprovalError.expired }255    }256257    public func approveRiskChange(_ r: GmxRiskApproval, with authenticator: PasskeyAuthenticator, locale: String? = nil, now: Date = Date()) async throws -> GmxStatus {258        guard r.intent.expiry > now else { throw ApprovalError.expired }259        let assertion = try await DerivApproval.assertion(r.approval.options, client, authenticator)260        return try await client.send(.post, "\(Self.base)/\(r.intent.kind == .limits ? "limits/approve" : "resume")", query: q(locale), body: DerivAssertionBody(assertion: assertion))261    }262}263
Files main
Menu

Theme