-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsoroban.ts
393 lines (338 loc) · 10.4 KB
/
soroban.ts
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
384
385
386
387
388
389
390
391
392
393
import {
Address,
Contract,
Memo,
MemoType,
Operation,
scValToNative,
SorobanRpc,
StrKey,
TimeoutInfinite,
Transaction,
TransactionBuilder,
xdr,
scValToBigInt,
ScInt,
} from "@stellar/stellar-sdk";
import BigNumber from "bignumber.js";
import { StellarWalletsKit } from "stellar-wallets-kit";
import { NetworkDetails, signData } from "./network";
import { ERRORS } from "./error";
import { authorizeEntry } from "./sign-auth-entry";
export const SendTxStatus: {
[index: string]: SorobanRpc.Api.SendTransactionStatus;
} = {
Pending: "PENDING",
Duplicate: "DUPLICATE",
Retry: "TRY_AGAIN_LATER",
Error: "ERROR",
};
export const BASE_FEE = "100";
export const RPC_URLS: { [key: string]: string } = {
TESTNET: "https://soroban-testnet.stellar.org",
};
// Given a display value for a token and a number of decimals, return the corresponding BigNumber
export const parseTokenAmount = (value: string, decimals: number) => {
const comps = value.split(".");
let whole = comps[0];
let fraction = comps[1];
if (!whole) {
whole = "0";
}
if (!fraction) {
fraction = "0";
}
// Trim trailing zeros
while (fraction[fraction.length - 1] === "0") {
fraction = fraction.substring(0, fraction.length - 1);
}
// If decimals is 0, we have an empty string for fraction
if (fraction === "") {
fraction = "0";
}
// Fully pad the string with zeros to get to value
while (fraction.length < decimals) {
fraction += "0";
}
const wholeValue = new BigNumber(whole);
const fractionValue = new BigNumber(fraction);
return wholeValue.shiftedBy(decimals).plus(fractionValue);
};
export const accountToScVal = (account: string) =>
new Address(account).toScVal();
export const valueToI128String = (value: xdr.ScVal) =>
scValToBigInt(value).toString();
// Get a server configfured for a specific network
export const getServer = (networkDetails: NetworkDetails) =>
new SorobanRpc.Server(RPC_URLS[networkDetails.network], {
allowHttp: networkDetails.networkUrl.startsWith("http://"),
});
// Can be used whenever we need to perform a "read-only" operation
// Used in getTokenSymbol, getTokenName, and getTokenDecimals
export const simulateTx = async <ArgType>(
tx: Transaction<Memo<MemoType>, Operation[]>,
server: SorobanRpc.Server,
): Promise<ArgType> => {
const response = await server.simulateTransaction(tx);
if (
SorobanRpc.Api.isSimulationSuccess(response) &&
response.result !== undefined
) {
return scValToNative(response.result.retval);
}
throw new Error("simulation returned no result");
};
// Get the tokens decimals, decoded as a number
export const getTokenDecimals = async (
tokenId: string,
txBuilder: TransactionBuilder,
server: SorobanRpc.Server,
) => {
const contract = new Contract(tokenId);
const tx = txBuilder
.addOperation(contract.call("decimals"))
.setTimeout(TimeoutInfinite)
.build();
const result = await simulateTx<number>(tx, server);
return result;
};
// Get a TransactionBuilder configured with our public key
export const getTxBuilder = async (
pubKey: string,
fee: string,
server: SorobanRpc.Server,
networkPassphrase: string,
) => {
const source = await server.getAccount(pubKey);
return new TransactionBuilder(source, {
fee,
networkPassphrase,
});
};
export const buildSwap = async (
contractID: string,
tokenA: {
id: string;
amount: string;
minAmount: string;
},
tokenB: {
id: string;
amount: string;
minAmount: string;
},
swapperAPubKey: string,
swapperBPubKey: string,
memo: string,
server: SorobanRpc.Server,
txBuilder: TransactionBuilder,
) => {
const swapContract = new Contract(contractID);
const contractA = new Contract(tokenA.id);
const contractB = new Contract(tokenB.id);
const tx = txBuilder
.addOperation(
swapContract.call(
"swap",
...[
accountToScVal(swapperAPubKey),
accountToScVal(swapperBPubKey),
accountToScVal(contractA.contractId()),
accountToScVal(contractB.contractId()),
new ScInt(tokenA.amount).toI128(),
new ScInt(tokenA.minAmount).toI128(),
new ScInt(tokenB.amount).toI128(),
new ScInt(tokenB.minAmount).toI128(),
],
),
)
.setTimeout(TimeoutInfinite);
if (memo.length > 0) {
tx.addMemo(Memo.text(memo));
}
const built = tx.build();
const sim = (await server.simulateTransaction(
built,
)) as SorobanRpc.Api.SimulateTransactionSuccessResponse;
const preparedTransaction = SorobanRpc.assembleTransaction(built, sim);
if (!SorobanRpc.Api.isSimulationSuccess(sim)) {
throw new Error(ERRORS.TX_SIM_FAILED);
}
return {
preparedTransaction,
footprint: sim.transactionData.getFootprint(),
};
};
// Get the tokens symbol, decoded as a string
export const getTokenSymbol = async (
tokenId: string,
txBuilder: TransactionBuilder,
server: SorobanRpc.Server,
) => {
const contract = new Contract(tokenId);
const tx = txBuilder
.addOperation(contract.call("symbol"))
.setTimeout(TimeoutInfinite)
.build();
const result = await simulateTx<string>(tx, server);
return result;
};
export const buildContractAuth = async (
authEntries: xdr.SorobanAuthorizationEntry[],
signerPubKey: string,
networkPassphrase: string,
contractID: string,
server: SorobanRpc.Server,
kit: StellarWalletsKit,
) => {
const signedAuthEntries = [];
for (const entry of authEntries) {
if (
entry.credentials().switch() !==
xdr.SorobanCredentialsType.sorobanCredentialsAddress()
) {
signedAuthEntries.push(entry);
} else {
const entryAddress = entry.credentials().address().address().accountId();
if (
signerPubKey === StrKey.encodeEd25519PublicKey(entryAddress.ed25519())
) {
let expirationLedgerSeq = 0;
const key = xdr.LedgerKey.contractData(
new xdr.LedgerKeyContractData({
contract: new Address(contractID).toScAddress(),
key: xdr.ScVal.scvLedgerKeyContractInstance(),
durability: xdr.ContractDataDurability.persistent(),
}),
);
// Fetch the current contract ledger seq
// eslint-disable-next-line no-await-in-loop
const entryRes = await server.getLedgerEntries(key);
if (entryRes.entries && entryRes.entries.length) {
// set auth entry to expire when contract data expires, but could any number of blocks in the future
expirationLedgerSeq = entryRes.entries[0].liveUntilLedgerSeq || 0;
} else {
throw new Error(ERRORS.CANNOT_FETCH_LEDGER_ENTRY);
}
const signingMethod = async (input: Buffer) => {
// eslint-disable-next-line no-await-in-loop
const signature = (await signData(
input.toString("base64"),
signerPubKey,
kit,
)) as any as { data: number[] };
return Buffer.from(signature.data);
};
try {
// eslint-disable-next-line no-await-in-loop
const authEntry = await authorizeEntry(
entry,
signingMethod,
expirationLedgerSeq,
networkPassphrase,
);
signedAuthEntries.push(authEntry);
} catch (error) {
console.log(error);
}
} else {
signedAuthEntries.push(entry);
}
}
}
return signedAuthEntries;
};
export const signContractAuth = async (
contractID: string,
signerPubKey: string,
tx: Transaction,
server: SorobanRpc.Server,
networkPassphrase: string,
kit: StellarWalletsKit,
) => {
const builder = TransactionBuilder.cloneFrom(tx);
// Soroban transaction can only have 1 operation
const rawInvokeHostFunctionOp = tx
.operations[0] as Operation.InvokeHostFunction;
const auth = rawInvokeHostFunctionOp.auth ? rawInvokeHostFunctionOp.auth : [];
const signedAuth = await buildContractAuth(
auth,
signerPubKey,
networkPassphrase,
contractID,
server,
kit,
);
builder.clearOperations().addOperation(
Operation.invokeHostFunction({
...rawInvokeHostFunctionOp,
auth: signedAuth,
}),
);
return builder.build();
};
export const getArgsFromEnvelope = (
envelopeXdr: string,
networkPassphrase: string,
) => {
const txEnvelope = TransactionBuilder.fromXDR(
envelopeXdr,
networkPassphrase,
) as Transaction<Memo<MemoType>, Operation.InvokeHostFunction[]>;
// only one op per tx in Soroban
const op = txEnvelope.operations[0].func;
if (!op) {
throw new Error(ERRORS.BAD_ENVELOPE);
}
const args = op.invokeContract().args();
const tokenA = StrKey.encodeContract(args[2].address().contractId());
const tokenB = StrKey.encodeContract(args[3].address().contractId());
return {
addressA: StrKey.encodeEd25519PublicKey(
args[0].address().accountId().ed25519(),
),
addressB: StrKey.encodeEd25519PublicKey(
args[1].address().accountId().ed25519(),
),
tokenA,
tokenB,
amountA: valueToI128String(args[4]),
minBForA: valueToI128String(args[5]),
amountB: valueToI128String(args[6]),
minAForB: valueToI128String(args[7]),
};
};
// Build and submits a transaction to the Soroban RPC
// Polls for non-pending state, returns result after status is updated
export const submitTx = async (
signedXDR: string,
networkPassphrase: string,
server: SorobanRpc.Server,
) => {
const tx = TransactionBuilder.fromXDR(signedXDR, networkPassphrase);
const sendResponse = await server.sendTransaction(tx);
if (sendResponse.errorResult) {
throw new Error(ERRORS.UNABLE_TO_SUBMIT_TX);
}
if (sendResponse.status === SendTxStatus.Pending) {
let txResponse = await server.getTransaction(sendResponse.hash);
// Poll this until the status is not "NOT_FOUND"
while (
txResponse.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND
) {
// See if the transaction is complete
// eslint-disable-next-line no-await-in-loop
txResponse = await server.getTransaction(sendResponse.hash);
// Wait a second
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => setTimeout(resolve, 1000));
}
if (txResponse.status === SorobanRpc.Api.GetTransactionStatus.SUCCESS) {
return txResponse.resultXdr.toXDR("base64");
}
throw new Error(
`Unabled to submit transaction, status: ${sendResponse.status}`,
);
}
return null;
};