-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsoroban.ts
321 lines (279 loc) · 8.45 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
import {
Address,
Contract,
Memo,
MemoType,
nativeToScVal,
Operation,
scValToNative,
Server,
SorobanRpc,
TimeoutInfinite,
Transaction,
TransactionBuilder,
xdr,
} from "soroban-client";
import BigNumber from "bignumber.js";
import { NetworkDetails } from "./network";
import { stroopToXlm } from "./format";
import { ERRORS } from "./error";
// TODO: once soroban supports estimated fees, we can fetch this
export const BASE_FEE = "100";
export const baseFeeXlm = stroopToXlm(BASE_FEE).toString();
export const SendTxStatus: {
[index: string]: SorobanRpc.SendTransactionStatus;
} = {
Pending: "PENDING",
Duplicate: "DUPLICATE",
Retry: "TRY_AGAIN_LATER",
Error: "ERROR",
};
export const GetTxStatus: {
[index: string]: SorobanRpc.GetTransactionStatus;
} = {
Success: "SUCCESS",
NotFound: "NOT_FOUND",
Failed: "FAILED",
};
export const XLM_DECIMALS = 7;
export const RPC_URLS: { [key: string]: string } = {
FUTURENET: "https://rpc-futurenet.stellar.org/",
};
// Can be used whenever you need an Address argument for a contract method
export const accountToScVal = (account: string) =>
new Address(account).toScVal();
// Can be used whenever you need an i128 argument for a contract method
export const numberToI128 = (value: number): xdr.ScVal =>
nativeToScVal(value, { type: "i128" });
// Given a display value for a token and a number of decimals, return the correspding 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);
};
// Get a server configfured for a specific network
export const getServer = (networkDetails: NetworkDetails) =>
new Server(RPC_URLS[networkDetails.network], {
allowHttp: networkDetails.networkUrl.startsWith("http://"),
});
// Get a TransactionBuilder configured with our public key
export const getTxBuilder = async (
pubKey: string,
fee: string,
server: Server,
networkPassphrase: string,
) => {
const source = await server.getAccount(pubKey);
return new TransactionBuilder(source, {
fee,
networkPassphrase,
});
};
// Can be used whenever we need to perform a "read-only" operation
// Used in getTokenSymbol, getTokenName, getTokenDecimals, and getTokenBalance
export const simulateTx = async <ArgType>(
tx: Transaction<Memo<MemoType>, Operation[]>,
server: Server,
): Promise<ArgType> => {
const { results, ...rest } = await server.simulateTransaction(tx);
console.log(results, rest);
if (!results || results.length !== 1) {
throw new Error("Invalid response from simulateTransaction");
}
const result = results[0];
const scVal = xdr.ScVal.fromXDR(result.xdr, "base64");
let convertedScVal: any;
try {
// handle a case where scValToNative doesn't properly handle scvString
convertedScVal = scVal.str().toString();
return convertedScVal;
} catch (e) {
console.error(e);
}
return scValToNative(scVal);
};
// 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: Server,
) => {
const tx = TransactionBuilder.fromXDR(signedXDR, networkPassphrase);
const sendResponse = await server.sendTransaction(tx);
if (sendResponse.errorResultXdr) {
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 === GetTxStatus.NotFound) {
// 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));
}
return txResponse.resultXdr!;
// eslint-disable-next-line no-else-return
} else {
throw new Error(
`Unabled to submit transaction, status: ${sendResponse.status}`,
);
}
};
// Get the tokens symbol, decoded as a string
export const getTokenSymbol = async (
tokenId: string,
txBuilder: TransactionBuilder,
server: 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;
};
// Get the tokens name, decoded as a string
export const getTokenName = async (
tokenId: string,
txBuilder: TransactionBuilder,
server: Server,
) => {
const contract = new Contract(tokenId);
const tx = txBuilder
.addOperation(contract.call("name"))
.setTimeout(TimeoutInfinite)
.build();
const result = await simulateTx<string>(tx, server);
return result;
};
// Get the tokens decimals, decoded as a number
export const getTokenDecimals = async (
tokenId: string,
txBuilder: TransactionBuilder,
server: 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 the tokens balance, decoded as a string
export const getTokenBalance = async (
address: string,
tokenId: string,
txBuilder: TransactionBuilder,
server: Server,
) => {
const params = [accountToScVal(address)];
const contract = new Contract(tokenId);
const tx = txBuilder
.addOperation(contract.call("balance", ...params))
.setTimeout(TimeoutInfinite)
.build();
const result = await simulateTx<string>(tx, server);
return result;
};
// Build a "transfer" operation, and prepare the corresponding XDR
// https://github.com/stellar/soroban-examples/blob/main/token/src/contract.rs#L27
export const makePayment = async (
tokenId: string,
amount: number,
to: string,
pubKey: string,
memo: string,
txBuilder: TransactionBuilder,
server: Server,
networkPassphrase: string,
) => {
const contract = new Contract(tokenId);
const tx = txBuilder
.addOperation(
contract.call(
"transfer",
...[
accountToScVal(pubKey), // from
accountToScVal(to), // to
numberToI128(amount), // amount
],
),
)
.setTimeout(TimeoutInfinite);
if (memo.length > 0) {
tx.addMemo(Memo.text(memo));
}
const preparedTransaction = await server.prepareTransaction(
tx.build(),
networkPassphrase,
);
return preparedTransaction.toXDR();
};
export const getEstimatedFee = async (
tokenId: string,
amount: number,
to: string,
pubKey: string,
memo: string,
txBuilder: TransactionBuilder,
server: Server,
) => {
const contract = new Contract(tokenId);
const tx = txBuilder
.addOperation(
contract.call(
"transfer",
...[
accountToScVal(pubKey), // from
accountToScVal(to), // to
numberToI128(amount), // amount
],
),
)
.setTimeout(TimeoutInfinite);
if (memo.length > 0) {
tx.addMemo(Memo.text(memo));
}
const raw = tx.build();
const simResponse = await server.simulateTransaction(raw);
if (simResponse.error) {
throw simResponse.error;
}
if (!simResponse.results || simResponse.results.length < 1) {
throw new Error("transaction simulation failed");
}
// 'classic' tx fees are measured as the product of tx.fee * 'number of operations', In soroban contract tx,
// there can only be single operation in the tx, so can make simplification
// of total classic fees for the soroban transaction will be equal to incoming tx.fee + minResourceFee.
const classicFeeNum = parseInt(raw.fee, 10) || 0;
const minResourceFeeNum = parseInt(simResponse.minResourceFee, 10) || 0;
const fee = (classicFeeNum + minResourceFeeNum).toString();
return fee;
};