forked from koshikraj/ottopus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransfer.ts
More file actions
383 lines (358 loc) · 15 KB
/
Copy pathtransfer.ts
File metadata and controls
383 lines (358 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import { randomUUID } from 'node:crypto'
import { encodeFunctionData } from 'viem'
import type { ArmRef, Portfolio } from '../connectors/portfolio/index.js'
import { SimulationUnavailableError, type Simulator, asSimulation } from '../connectors/simulation/index.js'
import {
type Call,
type PlanDraft,
type Simulation,
type TransferIntent,
type WalletCandidate,
type Warning,
accountOn,
assemblePlan,
chainName,
findChain,
isNativeAsset,
nativeAssetIdOf,
parseAccountId,
parseAssetId,
planDraftSchema,
resolveTransferWallet,
sourceChainOf,
transferIntentSchema,
} from '../core/index.js'
import type { CreatePlanInput, PlanRecord, ReviewLink } from '../plans/index.js'
import { KNOWN_ABI, type Lookups, blockWarnings, decodeCalls, verifyPlan } from '../verify/index.js'
import type { Arm } from '../wallets/index.js'
import { humanAmount, truncateAddress } from './readable.js'
/**
* prepare_transfer, end to end: intent, wallet, one call, decode, verify,
* hash, store, link. Nothing here signs; the last thing it does is hand back
* a URL a person opens.
*
* Kept out of server.ts so the tool registration stays a registration and
* this can be tested as a function. The order is the security order — verify
* runs between decode and hash, so a plan that fails never has a hash and
* never has a link.
*/
/** A transfer carries no quote, so this is the plan's whole clock. */
export const PLAN_TTL_MS = 15 * 60_000
export interface PrepareDeps {
listWallets(userId: string): Promise<Arm[]>
readPortfolio: ((arms: readonly ArmRef[]) => Promise<Portfolio>) | null
lookups: Lookups
/** Null on a deployment with no simulator; the plan is then reviewed on its decoding alone. */
simulator: Simulator | null
createPlan(input: CreatePlanInput): Promise<PlanRecord>
issueReviewLink(planId: string, version: number, planExpiresAt: string): Promise<ReviewLink>
/** Keeps the run beside the plan. Optional: the tools work without the log. */
recordSimulation?: ((input: { planId: string; planVersion: number; simulation: Simulation; raw?: unknown }) => Promise<void>) | undefined
}
export interface PrepareContext {
userId: string
grantId: string | null
}
export interface PrepareInput {
asset: string
amount: string
to: string
fromAccount?: string | undefined
note?: string | undefined
}
export type PrepareOutcome =
| { kind: 'invalid'; reasons: string[] }
| { kind: 'no_wallet'; reasons: string[] }
| { kind: 'blocked'; planId: string; summary: string; reasons: string[]; warnings: Warning[] }
| {
kind: 'ready'
planId: string
status: 'awaiting_review'
summary: string
recommendedAccount: string
reason: string
warnings: Warning[]
expiresAt: string
reviewUrl: string
linkExpiresAt: string
}
/** One call. Native value to the recipient, or ERC-20 transfer on the token. */
export function buildTransferCall(intent: TransferIntent): Call {
const chainId = sourceChainOf(intent)
const chain = `${chainId.namespace}:${chainId.reference}`
if (isNativeAsset(intent.asset)) {
return { to: intent.to, value: intent.amount, data: '0x', chainId: chain }
}
const token = parseAssetId(intent.asset).assetReference
const recipient = parseAccountId(intent.to).address
return {
to: accountOn(chainId, token),
value: '0',
data: encodeFunctionData({
abi: KNOWN_ABI,
functionName: 'transfer',
args: [recipient as `0x${string}`, BigInt(intent.amount)],
}).toLowerCase(),
chainId: chain,
}
}
interface AssetWords {
symbol: string
decimals: number
}
/** What to call the asset. The portfolio knows; failing that, the chain's own currency or the contract. */
function assetWords(intent: TransferIntent, portfolio: Portfolio | null): AssetWords {
const held = portfolio?.assets.find((a) => a.assetId.toLowerCase() === intent.asset.toLowerCase())
if (held) return { symbol: held.asset.symbol, decimals: held.asset.decimals }
const chain = sourceChainOf(intent)
if (isNativeAsset(intent.asset)) {
const info = findChain(chain)
return info ? { symbol: info.nativeCurrency.symbol, decimals: info.nativeCurrency.decimals } : { symbol: 'units', decimals: 0 }
}
return { symbol: `units of ${truncateAddress(parseAssetId(intent.asset).assetReference)}`, decimals: 0 }
}
function holdingOf(portfolio: Portfolio | null, assetId: string, walletId: string): bigint {
const asset = portfolio?.assets.find((a) => a.assetId.toLowerCase() === assetId.toLowerCase())
const holding = asset?.holdings.find((h) => h.walletId === walletId)
return holding ? BigInt(holding.amount) : 0n
}
/** Every EVM wallet, as a candidate on the intent's chain. */
function candidatesFrom(
arms: readonly Arm[],
intent: TransferIntent,
portfolio: Portfolio | null,
gasAsset: string,
): WalletCandidate[] {
const chain = sourceChainOf(intent)
return arms
.filter((arm) => arm.namespace === 'eip155')
.map((arm) => ({
walletId: arm.id,
account: accountOn(chain, arm.address),
label: arm.label,
canSign: !arm.isWatchOnly && arm.provedAt !== null,
assetBalance: holdingOf(portfolio, intent.asset, arm.id),
gasBalance: holdingOf(portfolio, gasAsset, arm.id),
}))
}
export function transferSummary(intent: TransferIntent, asset: AssetWords, from: { label?: string | undefined; caip10: string }): string {
const amount = `${humanAmount(intent.amount, asset.decimals)} ${asset.symbol}`
const address = truncateAddress(parseAccountId(intent.to).address)
const to = intent.toName ? `${intent.toName} (${address})` : address
const fromName = from.label ?? truncateAddress(parseAccountId(from.caip10).address)
return `Send ${amount} to ${to} from ${fromName} on ${chainName(sourceChainOf(intent))}`
}
/** Looks like an ENS name rather than an address or a CAIP-10. */
const ENS_NAME = /^[^\s:/]+\.[a-z]{2,}$/i
/**
* `to` may be a CAIP-10, a bare 0x address, or an ENS name. A name resolves
* on Ethereum and the address it gives is used on the intent's chain — the
* same account, as an EOA is the same on every EVM chain. The name is kept
* on the intent so the page shows both and the hash covers the pairing.
*/
async function recipientOf(
to: string,
chainId: string,
lookups: Lookups,
): Promise<{ to: string; toName?: string } | { error: string }> {
const trimmed = to.trim()
if (/^0x[0-9a-fA-F]{40}$/.test(trimmed)) return { to: `${chainId}:${trimmed.toLowerCase()}` }
if (!ENS_NAME.test(trimmed)) return { to: trimmed }
// ENS names are case-insensitive; the registry normalises further.
const name = trimmed.toLowerCase()
const address = await lookups.resolveName(name)
if (!address) return { error: `${name} does not resolve to an address on ENS` }
return { to: `${chainId}:${address}`, toName: name }
}
export async function prepareTransfer(
ctx: PrepareContext,
deps: PrepareDeps,
input: PrepareInput,
now: Date = new Date(),
): Promise<PrepareOutcome> {
// The chain comes from the asset, so a recipient given by name or bare
// address can be placed on it before the intent is parsed as a whole.
let assetChain: string
try {
const parsedAsset = parseAssetId(input.asset)
assetChain = `${parsedAsset.namespace}:${parsedAsset.reference}`
} catch {
return { kind: 'invalid', reasons: [`asset: ${input.asset} is not a CAIP-19 asset id; get_portfolio lists each holding's assetId`] }
}
const recipient = await recipientOf(input.to, assetChain, deps.lookups)
if ('error' in recipient) return { kind: 'invalid', reasons: [recipient.error] }
const parsed = transferIntentSchema.safeParse({
kind: 'transfer',
asset: input.asset,
amount: input.amount,
to: recipient.to,
...(recipient.toName ? { toName: recipient.toName } : {}),
...(input.fromAccount ? { fromAccount: input.fromAccount } : {}),
...(input.note?.trim() ? { note: input.note.trim() } : {}),
})
if (!parsed.success) {
return { kind: 'invalid', reasons: parsed.error.issues.map((i) => `${i.path.join('.') || 'intent'}: ${i.message}`) }
}
const intent = parsed.data
const chain = sourceChainOf(intent)
const chainId = `${chain.namespace}:${chain.reference}`
if (!findChain(chain)) {
return { kind: 'invalid', reasons: [`chain ${chainId} is not one Ottopus knows`] }
}
// Gas is paid in the chain's own currency, so a transfer needs its name.
// A chain whose coin type is not on file is refused here, in a sentence,
// rather than three steps later as an exception.
const gasAsset = nativeAssetIdOf(chain)
if (!gasAsset) {
return {
kind: 'invalid',
reasons: [
`${chainName(chain)} (${chainId}) is not supported for transfers yet: Ottopus cannot name its native currency, ` +
'so it cannot check for gas. Base, Ethereum, Arbitrum, Optimism, Polygon and BNB Chain are supported.',
],
}
}
// Balances decide eligibility. Without a provider nothing can be known
// about what a wallet holds, and a plan built on a guess is not a plan.
const arms = await deps.listWallets(ctx.userId)
if (arms.length === 0) return { kind: 'no_wallet', reasons: ['no wallet is linked to this account'] }
if (!deps.readPortfolio) {
return { kind: 'no_wallet', reasons: ['balances are not available on this deployment, so no wallet can be chosen'] }
}
const portfolio = await deps.readPortfolio(
arms.map((arm) => ({ walletId: arm.id, namespace: arm.namespace, address: arm.address })),
)
const asset = assetWords(intent, portfolio)
const native = isNativeAsset(intent.asset)
const chosen = resolveTransferWallet({ intent, candidates: candidatesFrom(arms, intent, portfolio, gasAsset), asset, native })
if (!chosen.ok) return { kind: 'no_wallet', reasons: chosen.reasons }
const call = buildTransferCall(intent)
const expiresAt = new Date(now.getTime() + PLAN_TTL_MS).toISOString()
const summary = transferSummary(intent, asset, chosen.resolution.account)
// Decode, then simulate, then hash. The fee estimate the simulation
// produces goes into the human plan, which is hashed — the number a person
// agreed to has to be bound to the plan they agreed to, like every other
// sentence on the page.
const decodedActions = await decodeCalls([call], deps.lookups)
const simulation = await simulate(deps, {
chainId,
account: chosen.resolution.account.caip10,
calls: [call],
gasAsset,
portfolio,
})
const draft: PlanDraft = planDraftSchema.parse({
id: randomUUID(),
version: 1,
userId: ctx.userId,
createdVia: 'agent',
intent,
provenance: 'route_provider',
resolution: chosen.resolution,
outcome: { type: 'calls', calls: [call] },
quote: { provider: 'ottopus', expiresAt },
humanPlan: {
summary,
steps: [summary, ...(intent.note ? [`Note from the request: ${intent.note}`] : [])],
feesUsd: simulation?.gasUsd ?? 'unknown',
warnings: [],
assets: [{ id: intent.asset, symbol: asset.symbol, decimals: asset.decimals }],
},
status: 'awaiting_review',
expiresAt,
})
const verdict = verifyPlan({ intent, calls: [call], decodedActions, simulation })
const warnings = blockWarnings(verdict)
const plan = assemblePlan(
{ ...draft, status: verdict.ok ? 'awaiting_review' : 'blocked', humanPlan: { ...draft.humanPlan, warnings } },
{ decodedActions, simulation },
)
const record = await deps.createPlan({ plan, walletId: chosen.walletId, grantId: ctx.grantId })
if (simulation && deps.recordSimulation) {
// The log is a nicety; a plan that exists must not be lost to it.
await deps
.recordSimulation({ planId: record.plan.id, planVersion: record.plan.version, simulation })
.catch(() => {})
}
if (!verdict.ok) {
return { kind: 'blocked', planId: record.plan.id, summary, reasons: verdict.reasons, warnings }
}
const link = await deps.issueReviewLink(record.plan.id, record.plan.version, record.plan.expiresAt)
return {
kind: 'ready',
planId: record.plan.id,
status: 'awaiting_review',
summary,
recommendedAccount: chosen.resolution.account.label
? `${chosen.resolution.account.label} (${truncateAddress(parseAccountId(chosen.resolution.account.caip10).address)})`
: truncateAddress(parseAccountId(chosen.resolution.account.caip10).address),
reason: chosen.resolution.reason,
warnings,
expiresAt: record.plan.expiresAt,
reviewUrl: link.url,
linkExpiresAt: link.expiresAt,
}
}
interface SimulateArgs {
chainId: string
account: string
calls: Call[]
gasAsset: string
portfolio: Portfolio | null
}
/**
* Run the simulation, or return null and say nothing about it.
*
* Absence of evidence must never read as evidence: a chain no simulator
* serves, or an RPC that would not answer, leaves `simulation` null, and the
* policy skips its rules rather than blocking. What must not happen is a
* simulation quietly failing and the page implying one passed.
*
* Gas is priced here because this is where the portfolio is: the simulator
* reports units and the block's base fee, the portfolio knows what the
* chain's currency is worth, and neither has any business knowing the other.
*/
async function simulate(deps: PrepareDeps, args: SimulateArgs): Promise<Simulation | null> {
if (!deps.simulator || !deps.simulator.serves(args.chainId)) return null
try {
const run = await deps.simulator.simulate({
chainId: args.chainId,
account: args.account,
calls: args.calls,
})
const native = args.portfolio?.assets.find((a) => a.assetId.toLowerCase() === args.gasAsset.toLowerCase())
return asSimulation(run, {
gasPriceWei: (run.raw as { baseFeePerGas?: string | null } | null)?.baseFeePerGas ?? null,
nativePriceUsd: native?.price ?? null,
nativeDecimals: native?.asset.decimals ?? findChain(args.chainId)?.nativeCurrency.decimals ?? null,
})
} catch (err) {
if (err instanceof SimulationUnavailableError) return null
// An RPC that will not answer is not a verdict either. The decoded plan
// still stands, and the page says the simulation did not run.
return null
}
}
/** The words the agent reads out. The structured copy carries the same facts. */
export function prepareText(outcome: PrepareOutcome): string {
switch (outcome.kind) {
case 'invalid':
return `That is not a transfer Ottopus can build:\n${outcome.reasons.map((r) => `- ${r}`).join('\n')}`
case 'no_wallet':
return `No linked wallet can make this transfer:\n${outcome.reasons.map((r) => `- ${r}`).join('\n')}`
case 'blocked':
return [
`Ottopus refused to build "${outcome.summary}":`,
...outcome.reasons.map((r) => `- ${r}`),
'The refusal is recorded in Activity. Nothing was sent.',
].join('\n')
case 'ready':
return [
`Plan ready: ${outcome.summary}.`,
outcome.reason,
...outcome.warnings.map((w) => `Heads up: ${w.message}`),
`Review and sign: ${outcome.reviewUrl}`,
`The link is good for a few minutes and the plan expires at ${outcome.expiresAt}. Nothing moves until the person signs in their own wallet.`,
].join('\n')
}
}