-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCharge.ts
More file actions
285 lines (251 loc) · 8.95 KB
/
Charge.ts
File metadata and controls
285 lines (251 loc) · 8.95 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
import {
Account,
Address,
BASE_FEE,
Contract,
Keypair,
Memo,
TransactionBuilder,
authorizeEntry,
nativeToScVal,
rpc,
xdr as StellarXdr,
} from '@stellar/stellar-sdk'
import { Credential, Method } from 'mppx'
import { z } from 'zod/mini'
import {
ALL_ZEROS,
DEFAULT_DECIMALS,
DEFAULT_TIMEOUT,
NETWORK_PASSPHRASE,
SOROBAN_RPC_URLS,
type NetworkId,
} from '../constants.js'
import * as Methods from '../Methods.js'
import { fromBaseUnits } from '../Methods.js'
/**
* Creates a Stellar charge method for use on the **client**.
*
* Builds a Soroban SAC `transfer` invocation, signs it, and either:
* - **pull** (default): sends the signed XDR to the server to broadcast
* - **push**: broadcasts itself and sends the tx hash
*
* @example
* ```ts
* import { Keypair } from '@stellar/stellar-sdk'
* import { Mppx } from 'mppx/client'
* import { stellar } from 'stellar-mpp-sdk/client'
*
* Mppx.create({
* methods: [
* stellar.charge({
* keypair: Keypair.fromSecret('S...'),
* }),
* ],
* })
*
* const response = await fetch('https://api.example.com/resource')
* ```
*/
export function charge(parameters: charge.Parameters) {
const {
decimals = DEFAULT_DECIMALS,
keypair: keypairParam,
mode: defaultMode = 'pull',
onProgress,
rpcUrl,
secretKey,
timeout = DEFAULT_TIMEOUT,
} = parameters
if (!keypairParam && !secretKey) {
throw new Error(
'Either keypair or secretKey must be provided.',
)
}
const keypair = keypairParam ?? Keypair.fromSecret(secretKey!)
return Method.toClient(Methods.charge, {
context: z.object({
mode: z.optional(z.enum(['push', 'pull'])),
}),
async createCredential({ challenge, context }) {
const { request } = challenge
const { amount, currency, recipient } = request
const network: NetworkId =
(request.methodDetails?.network as NetworkId) ?? 'testnet'
const memo = request.methodDetails?.memo as string | undefined
onProgress?.({
type: 'challenge',
recipient,
amount: fromBaseUnits(amount, decimals),
currency,
})
const resolvedRpcUrl = rpcUrl ?? SOROBAN_RPC_URLS[network]
const networkPassphrase = NETWORK_PASSPHRASE[network]
const server = new rpc.Server(resolvedRpcUrl)
// Build SAC `transfer(from, to, amount)` invocation
const contract = new Contract(currency)
const stellarAmount = BigInt(amount)
const effectiveMode = context?.mode ?? defaultMode
const isServerSponsored = request.methodDetails?.feePayer === true
if (isServerSponsored && effectiveMode === 'push') {
throw new Error(
'Push mode is not supported for server-sponsored transactions. ' +
'The server must submit sponsored transactions. Use mode: \'pull\' (default).',
)
}
if (isServerSponsored) {
// ── Spec-compliant sponsored path ──────────────────────────────────
// Client uses an all-zeros source account so the server can swap in
// its own fee-payer account when rebuilding the transaction.
const placeholderSource = new Account(ALL_ZEROS, '0')
const transferOp = contract.call(
'transfer',
new Address(keypair.publicKey()).toScVal(),
new Address(recipient).toScVal(),
nativeToScVal(stellarAmount, { type: 'i128' }),
)
const sponsoredBuilder = new TransactionBuilder(placeholderSource, {
fee: BASE_FEE,
networkPassphrase,
})
.addOperation(transferOp)
.setTimeout(timeout)
if (memo) {
sponsoredBuilder.addMemo(Memo.text(memo))
}
const unsignedTx = sponsoredBuilder.build()
const prepared = await server.prepareTransaction(unsignedTx)
// Determine auth-entry expiry from the current ledger sequence
const latestLedger = await server.getLatestLedger()
const validUntilLedger =
latestLedger.sequence + Math.ceil(timeout / 5) + 10
onProgress?.({ type: 'signing' })
// Sign only the Soroban authorization entries — do NOT sign the
// transaction envelope (the server will do that after rebuilding).
const envelope = prepared.toEnvelope().v1()
for (const op of envelope.tx().operations()) {
const body = op.body()
if (
body.switch().value !==
StellarXdr.OperationType.invokeHostFunction().value
) {
continue
}
const authEntries = body.invokeHostFunctionOp().auth()
for (let i = 0; i < authEntries.length; i++) {
const entry = authEntries[i]
if (
entry.credentials().switch().value ===
StellarXdr.SorobanCredentialsType.sorobanCredentialsAddress().value
) {
authEntries[i] = await authorizeEntry(
entry,
keypair,
validUntilLedger,
networkPassphrase,
)
}
}
}
const signedXdr = prepared.toEnvelope().toXDR('base64')
onProgress?.({ type: 'signed', transaction: signedXdr })
return Credential.serialize({
challenge,
payload: { type: 'transaction' as const, transaction: signedXdr },
})
}
// ── Standard (unsponsored) path ────────────────────────────────────────
// Client builds and signs the full transaction; server submits as-is
// (or wraps it in a fee bump if it has a configured fee payer).
const sourceAccount = await server.getAccount(keypair.publicKey())
const transferOp = contract.call(
'transfer',
new Address(keypair.publicKey()).toScVal(),
new Address(recipient).toScVal(),
nativeToScVal(stellarAmount, { type: 'i128' }),
)
const builder = new TransactionBuilder(sourceAccount, {
fee: BASE_FEE,
networkPassphrase,
})
.addOperation(transferOp)
.setTimeout(timeout)
if (memo) {
builder.addMemo(Memo.text(memo))
}
const transaction = builder.build()
// Simulate to attach Soroban resource data
const prepared = await server.prepareTransaction(transaction)
onProgress?.({ type: 'signing' })
prepared.sign(keypair)
const signedXdr = prepared.toXDR()
onProgress?.({ type: 'signed', transaction: signedXdr })
if (effectiveMode === 'push') {
// Client broadcasts
onProgress?.({ type: 'paying' })
const result = await server.sendTransaction(prepared)
// Poll until confirmed
onProgress?.({ type: 'confirming', hash: result.hash })
let txResult = await server.getTransaction(result.hash)
let pollAttempts = 0
while (txResult.status === 'NOT_FOUND') {
if (++pollAttempts >= 60) {
throw new Error(
`Transaction not confirmed after ${pollAttempts} polling attempts.`,
)
}
await new Promise((r) => setTimeout(r, 1000))
txResult = await server.getTransaction(result.hash)
}
if (txResult.status !== 'SUCCESS') {
throw new Error(
`Transaction failed: ${txResult.status}`,
)
}
onProgress?.({ type: 'paid', hash: result.hash })
return Credential.serialize({
challenge,
payload: { type: 'hash' as const, hash: result.hash },
})
}
// Pull mode: send signed XDR for server to broadcast
return Credential.serialize({
challenge,
payload: { type: 'transaction' as const, transaction: signedXdr },
})
},
})
}
export declare namespace charge {
type ProgressEvent =
| { type: 'challenge'; recipient: string; amount: string; currency: string }
| { type: 'signing' }
| { type: 'signed'; transaction: string }
| { type: 'paying' }
| { type: 'confirming'; hash: string }
| { type: 'paid'; hash: string }
type Parameters = {
/** Stellar secret key (S...). Provide either this or `keypair`. */
secretKey?: string
/** Stellar Keypair instance. Provide either this or `secretKey`. */
keypair?: Keypair
/** Number of decimal places for the token. @default 7 */
decimals?: number
/** Custom Soroban RPC URL. Defaults based on network. */
rpcUrl?: string
/**
* Controls how the charge transaction is submitted.
*
* - `'push'`: Client broadcasts the transaction and sends the tx hash.
* - `'pull'`: Client signs the transaction and sends the signed XDR
* to the server for broadcast.
*
* @default 'pull'
*/
mode?: 'push' | 'pull'
/** Transaction timeout in seconds. @default 180 */
timeout?: number
/** Callback invoked at each lifecycle stage. */
onProgress?: (event: ProgressEvent) => void
}
}