|
| 1 | +// Copyright (c) Mysten Labs, Inc. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import type { Experimental_SuiClientTypes } from '@mysten/sui/experimental'; |
| 5 | +import { parse, safeParse } from 'valibot'; |
| 6 | +import type { BaseAnalysis } from '../transaction-analyzer/base.js'; |
| 7 | +import type { CoinValueAnalysis, TransactionAnalysisIssue } from '../transaction-analyzer/index.js'; |
| 8 | +import type { AutoApprovalState } from './schemas/state.js'; |
| 9 | +import { AutoApprovalStateSchema } from './schemas/state.js'; |
| 10 | +import type { AutoApprovalSettings } from './schemas/policy.js'; |
| 11 | +import { AutoApprovalPolicySchema, AutoApprovalSettingsSchema } from './schemas/policy.js'; |
| 12 | + |
| 13 | +export interface AutoApprovalManagerOptions { |
| 14 | + policy: string; |
| 15 | + state: string | null; |
| 16 | + network: string; |
| 17 | + origin: string; |
| 18 | +} |
| 19 | + |
| 20 | +export interface AutoApprovalAnalysis { |
| 21 | + results: BaseAnalysis & { |
| 22 | + usdValue: CoinValueAnalysis; |
| 23 | + operationType: string | null; |
| 24 | + }; |
| 25 | + issues: TransactionAnalysisIssue[]; |
| 26 | +} |
| 27 | + |
| 28 | +export class AutoApprovalManager { |
| 29 | + #state: AutoApprovalState; |
| 30 | + |
| 31 | + constructor(options: AutoApprovalManagerOptions) { |
| 32 | + let state: AutoApprovalState | null = null; |
| 33 | + |
| 34 | + if (options.state) { |
| 35 | + const parseResult = safeParse(AutoApprovalStateSchema, JSON.parse(options.state)); |
| 36 | + if (parseResult.success) { |
| 37 | + const providedPolicy = parse(AutoApprovalPolicySchema, JSON.parse(options.policy)); |
| 38 | + const currentPolicy = parseResult.output.policy; |
| 39 | + |
| 40 | + if (JSON.stringify(currentPolicy) === JSON.stringify(providedPolicy)) { |
| 41 | + state = parseResult.output; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + this.#state = |
| 47 | + state ?? |
| 48 | + parse(AutoApprovalStateSchema, { |
| 49 | + schemaVersion: '1.0.0', |
| 50 | + origin: options.origin, |
| 51 | + network: options.network, |
| 52 | + policy: parse(AutoApprovalPolicySchema, JSON.parse(options.policy)), |
| 53 | + settings: null, |
| 54 | + createdObjects: {}, |
| 55 | + pendingDigests: [], |
| 56 | + } satisfies AutoApprovalState); |
| 57 | + |
| 58 | + if (this.#state.network !== options.network) { |
| 59 | + throw new Error(`Network mismatch: expected ${options.network}, got ${this.#state.network}`); |
| 60 | + } |
| 61 | + |
| 62 | + if (this.#state.origin !== options.origin) { |
| 63 | + throw new Error(`Origin mismatch: expected ${options.origin}, got ${this.#state.origin}`); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + canAutoApprove(analysis: AutoApprovalAnalysis): boolean { |
| 68 | + if (!this.#state.policy || !this.#state.settings) { |
| 69 | + return false; |
| 70 | + } |
| 71 | + |
| 72 | + if (analysis.issues.length > 0) { |
| 73 | + return false; |
| 74 | + } |
| 75 | + |
| 76 | + if (new Date() > new Date(this.#state.settings.expiration)) { |
| 77 | + return false; |
| 78 | + } |
| 79 | + |
| 80 | + if ( |
| 81 | + this.#state.settings.remainingTransactions !== null && |
| 82 | + this.#state.settings.remainingTransactions <= 0 |
| 83 | + ) { |
| 84 | + return false; |
| 85 | + } |
| 86 | + |
| 87 | + if ( |
| 88 | + !analysis.results.operationType || |
| 89 | + !this.#state.settings.approvedOperations.includes(analysis.results.operationType) |
| 90 | + ) { |
| 91 | + return false; |
| 92 | + } |
| 93 | + |
| 94 | + if (!analysis.results.operationType) { |
| 95 | + return false; |
| 96 | + } |
| 97 | + |
| 98 | + // TODO: analyze balances and budgets |
| 99 | + |
| 100 | + return true; |
| 101 | + } |
| 102 | + |
| 103 | + commitTransaction(analysis: AutoApprovalAnalysis): void { |
| 104 | + if (this.#state.settings?.remainingTransactions !== null && this.#state.settings) { |
| 105 | + this.#state.settings.remainingTransactions = Math.max( |
| 106 | + 0, |
| 107 | + this.#state.settings.remainingTransactions - 1, |
| 108 | + ); |
| 109 | + } |
| 110 | + |
| 111 | + for (const outflow of analysis.results.coinFlows) { |
| 112 | + const currentBudget = BigInt(this.#state.settings?.coinBudgets[outflow.coinType] ?? '0'); |
| 113 | + const newBalance = currentBudget - outflow.amount; |
| 114 | + |
| 115 | + if (this.#state.settings) { |
| 116 | + this.#state.settings.coinBudgets[outflow.coinType] = newBalance.toString(); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // TODO: track USD budget |
| 121 | + |
| 122 | + this.#state.pendingDigests.push(analysis.results.digest); |
| 123 | + } |
| 124 | + |
| 125 | + revertTransaction(analysis: AutoApprovalAnalysis): void { |
| 126 | + this.#removePendingDigest(analysis.results.digest); |
| 127 | + |
| 128 | + if (this.#state.settings?.remainingTransactions !== null && this.#state.settings) { |
| 129 | + this.#state.settings.remainingTransactions += 1; |
| 130 | + } |
| 131 | + |
| 132 | + this.#revertCoinFlows(analysis.results); |
| 133 | + } |
| 134 | + |
| 135 | + #revertCoinFlows(analysis: BaseAnalysis): void { |
| 136 | + for (const outflow of analysis.coinFlows) { |
| 137 | + const currentBudget = BigInt(this.#state.settings?.coinBudgets[outflow.coinType] ?? '0'); |
| 138 | + const newBalance = currentBudget + outflow.amount; |
| 139 | + |
| 140 | + if (this.#state.settings) { |
| 141 | + this.#state.settings.coinBudgets[outflow.coinType] = newBalance.toString(); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + // TODO: revert USD budget |
| 146 | + } |
| 147 | + |
| 148 | + #removePendingDigest(digest: string): void { |
| 149 | + const pendingIndex = this.#state.pendingDigests.indexOf(digest); |
| 150 | + if (pendingIndex >= 0) { |
| 151 | + this.#state.pendingDigests.splice(pendingIndex, 1); |
| 152 | + } else { |
| 153 | + throw new Error(`Transaction with digest ${digest} not found in pending digests`); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + applyTransactionEffects( |
| 158 | + analysis: AutoApprovalAnalysis, |
| 159 | + result: Experimental_SuiClientTypes.TransactionResponse, |
| 160 | + ): void { |
| 161 | + this.#removePendingDigest(result.digest); |
| 162 | + |
| 163 | + for (const changed of result.effects.changedObjects) { |
| 164 | + if (changed.idOperation === 'Created' && changed.outputState === 'ObjectWrite') { |
| 165 | + this.#state.createdObjects[changed.id] = { |
| 166 | + objectId: changed.id, |
| 167 | + version: changed.outputVersion!, |
| 168 | + digest: changed.outputDigest!, |
| 169 | + objectType: analysis.results.objectsById.get(changed.id)?.type || 'unknown', |
| 170 | + }; |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + // Revert coin flows and use real balance changes instead |
| 175 | + this.#revertCoinFlows(analysis.results); |
| 176 | + for (const change of result.balanceChanges) { |
| 177 | + const currentBudget = BigInt(this.#state.settings?.coinBudgets[change.coinType] ?? '0'); |
| 178 | + const newBalance = currentBudget + BigInt(change.amount); |
| 179 | + if (this.#state.settings) { |
| 180 | + this.#state.settings.coinBudgets[change.coinType] = newBalance.toString(); |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + // TODO: track USD budget |
| 185 | + } |
| 186 | + |
| 187 | + reset() { |
| 188 | + this.#state.settings = null; |
| 189 | + this.#state.createdObjects = {}; |
| 190 | + this.#state.pendingDigests = []; |
| 191 | + } |
| 192 | + |
| 193 | + export(): string { |
| 194 | + return JSON.stringify(parse(AutoApprovalStateSchema, this.#state)); |
| 195 | + } |
| 196 | + |
| 197 | + getSettings(): AutoApprovalSettings | null { |
| 198 | + return this.#state.settings; |
| 199 | + } |
| 200 | + |
| 201 | + updateSettings(settings: AutoApprovalSettings): void { |
| 202 | + const validatedSettings = parse(AutoApprovalSettingsSchema, settings); |
| 203 | + this.#state.settings = validatedSettings; |
| 204 | + } |
| 205 | +} |
0 commit comments