@piprail/sdk 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,389 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
- var _chunkJG6KRAW6cjs = require('./chunk-JG6KRAW6.cjs');
12
-
13
- // src/drivers/algorand/index.ts
14
- var _algosdk = require('algosdk'); var _algosdk2 = _interopRequireDefault(_algosdk);
15
-
16
- // src/drivers/algorand/chains.ts
17
- var ALGO_DECIMALS = 6;
18
- var ALGO_SYMBOL = "ALGO";
19
- var ALGORAND_MAINNET = {
20
- caip2: "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k",
21
- defaultAlgod: "https://mainnet-api.algonode.cloud",
22
- defaultIndexer: "https://mainnet-idx.algonode.cloud",
23
- tokens: {
24
- // Circle USDC — ASA id + 6 decimals verified live on mainnet algod
25
- // (/v2/assets/31566704 → unit-name "USDC", decimals 6, creator = Circle) before shipping.
26
- // USDC-only: Tether deprecated USDT on Algorand, so it's intentionally omitted.
27
- USDC: { assetId: 31566704, decimals: 6, symbol: "USDC" }
28
- }
29
- };
30
- function algorandAssetId(assetId) {
31
- return String(assetId);
32
- }
33
- function parseAlgorandAssetId(asset) {
34
- if (asset === "native") return null;
35
- if (!/^\d+$/.test(asset)) return null;
36
- const n = Number(asset);
37
- return Number.isSafeInteger(n) && n > 0 ? n : null;
38
- }
39
-
40
- // src/drivers/algorand/pay.ts
41
- async function payAlgorand(params) {
42
- const { client, sk, sender, accept } = params;
43
- const note = new TextEncoder().encode(accept.extra.nonce);
44
- const amount = BigInt(accept.amount);
45
- const assetId = parseAlgorandAssetId(accept.asset);
46
- try {
47
- const { txn, txId } = await client.build({
48
- sender,
49
- receiver: accept.payTo,
50
- amount,
51
- note,
52
- ...assetId === null ? {} : { assetId }
53
- });
54
- await client.signSend({ txn, sk });
55
- return txId;
56
- } catch (err) {
57
- const mapped = mapAlgorandError(err, accept.payTo);
58
- if (mapped) throw mapped;
59
- throw _nullishCoalesce(_chunkJG6KRAW6cjs.toInsufficientFundsError.call(void 0, err), () => ( err));
60
- }
61
- }
62
- function mapAlgorandError(err, payTo) {
63
- const m = err instanceof Error ? err.message : String(err);
64
- if (/must optin/i.test(m) || /missing from/i.test(m) && m.includes(payTo)) {
65
- return new (0, _chunkJG6KRAW6cjs.RecipientNotReadyError)(
66
- `Algorand recipient ${payTo} hasn't opted into this asset \u2014 it must opt in (a 0-amount asset transfer to itself) before it can receive. (Algorand: ${firstLine(m)})`,
67
- { cause: err }
68
- );
69
- }
70
- if (/overspend|below min|min(imum)? balance|tried to spend|balance \d+ below|asset \d+ missing from|insufficient|underflow/i.test(
71
- m
72
- )) {
73
- return new (0, _chunkJG6KRAW6cjs.InsufficientFundsError)(
74
- `Algorand payment failed: the sender can't cover it \u2014 token balance, ALGO for fees, the 0.1-ALGO minimum balance, or a missing asset opt-in on the sender. (Algorand: ${firstLine(m)})`,
75
- { cause: err }
76
- );
77
- }
78
- return null;
79
- }
80
- function firstLine(message) {
81
- return message.split("\n")[0].slice(0, 160);
82
- }
83
-
84
- // src/drivers/algorand/verify.ts
85
- async function verifyAlgorand(params) {
86
- const { reader, accept } = params;
87
- const nonce = accept.extra.nonce;
88
- const required = BigInt(accept.amount);
89
- const wantAssetId = parseAlgorandAssetId(accept.asset);
90
- let txs;
91
- try {
92
- txs = await reader.transactionsForAccount(accept.payTo, 50);
93
- } catch (e2) {
94
- return rpcFailed(nonce);
95
- }
96
- const tx = txs.find((t) => typeof t.note === "string" && t.note === nonce);
97
- if (!tx) return notFound(nonce);
98
- if (typeof tx.roundTime === "number") {
99
- const ageSeconds = Math.floor(Date.now() / 1e3) - tx.roundTime;
100
- if (Number.isFinite(ageSeconds) && ageSeconds > accept.maxTimeoutSeconds) {
101
- return {
102
- ok: false,
103
- error: "payment_expired",
104
- detail: `Payment is ${ageSeconds}s old; max allowed is ${accept.maxTimeoutSeconds}s.`
105
- };
106
- }
107
- }
108
- const isNative = wantAssetId === null;
109
- const typeOk = isNative ? tx.txType === "pay" : tx.txType === "axfer";
110
- const assetOk = isNative ? tx.assetId == null : tx.assetId === wantAssetId;
111
- if (!typeOk || tx.receiver !== accept.payTo || !assetOk) {
112
- return {
113
- ok: false,
114
- error: "transfer_not_found",
115
- detail: `Algorand tx ${tx.id} carries our nonce but has no matching ${isNative ? "ALGO" : `ASA ${wantAssetId}`} transfer to ${accept.payTo}.`
116
- };
117
- }
118
- let paid = 0n;
119
- try {
120
- paid = tx.amount ? BigInt(tx.amount) : 0n;
121
- } catch (e3) {
122
- paid = 0n;
123
- }
124
- if (paid < required) {
125
- return { ok: false, error: "amount_too_low", detail: `Paid ${paid}, required ${required}.` };
126
- }
127
- return {
128
- ok: true,
129
- receipt: {
130
- scheme: "onchain-proof",
131
- success: true,
132
- network: accept.network,
133
- transaction: tx.id,
134
- asset: accept.asset,
135
- amount: accept.amount,
136
- payer: _nullishCoalesce(tx.sender, () => ( "")),
137
- payTo: accept.payTo,
138
- verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
139
- }
140
- };
141
- }
142
- function notFound(nonce) {
143
- return {
144
- ok: false,
145
- error: "transfer_not_found",
146
- detail: `No matching Algorand payment found for nonce ${nonce} (not yet settled, or wrong recipient/amount/asset/note).`
147
- };
148
- }
149
- function rpcFailed(nonce) {
150
- return {
151
- ok: false,
152
- error: "tx_not_found",
153
- detail: `Could not read the Algorand indexer for nonce ${nonce} (transient RPC failure) \u2014 retry.`
154
- };
155
- }
156
-
157
- // src/drivers/algorand/wallet.ts
158
-
159
- function assertAlgorandWallet(wallet, network) {
160
- if (typeof wallet !== "object" || wallet === null) {
161
- throw new (0, _chunkJG6KRAW6cjs.WrongFamilyError)(
162
- `chain ${network} is Algorand; wallet must be { key } (25-word mnemonic) or { account }.`
163
- );
164
- }
165
- _chunkJG6KRAW6cjs.assertNoLegacyWalletKey.call(void 0, wallet, "Algorand");
166
- if (!("key" in wallet) && !("account" in wallet)) {
167
- throw new (0, _chunkJG6KRAW6cjs.WrongFamilyError)(
168
- `chain ${network} is Algorand; wallet must be { key } (25-word mnemonic) or { account }.`
169
- );
170
- }
171
- return wallet;
172
- }
173
- function resolveAlgorandWallet(config) {
174
- if (config.account) {
175
- return { addr: String(config.account.addr), sk: config.account.sk };
176
- }
177
- if (config.key != null) {
178
- try {
179
- const { addr, sk } = _algosdk2.default.mnemonicToSecretKey(config.key);
180
- return { addr: addr.toString(), sk };
181
- } catch (cause) {
182
- throw new (0, _chunkJG6KRAW6cjs.WrongFamilyError)(
183
- "Algorand wallet { key } is not a valid 25-word Algorand mnemonic.",
184
- { cause }
185
- );
186
- }
187
- }
188
- throw new (0, _chunkJG6KRAW6cjs.WrongFamilyError)("Algorand wallet needs { key } (25-word mnemonic) or { account }.");
189
- }
190
-
191
- // src/drivers/algorand/index.ts
192
- var algorandDriver = {
193
- family: "algorand",
194
- resolve(opts) {
195
- if (opts.chain !== "algorand") return null;
196
- const algodUrl = _nullishCoalesce(opts.rpcUrl, () => ( ALGORAND_MAINNET.defaultAlgod));
197
- return makeAlgorandNetwork(ALGORAND_MAINNET, algodUrl);
198
- }
199
- };
200
- function makeAlgorandNetwork(preset, algodUrl) {
201
- const algod = new _algosdk2.default.Algodv2("", algodUrl, "");
202
- const indexer = new _algosdk2.default.Indexer("", preset.defaultIndexer, "");
203
- const network = preset.caip2;
204
- const reader = {
205
- async transactionsForAccount(account, limit) {
206
- const res = await indexer.lookupAccountTransactions(account).limit(limit).do();
207
- return (_nullishCoalesce(res.transactions, () => ( []))).map((t) => adaptTxn(t)).filter((r) => r !== null);
208
- }
209
- };
210
- const payClient = {
211
- async build(transfer) {
212
- const suggestedParams = await algod.getTransactionParams().do();
213
- const common = {
214
- sender: transfer.sender,
215
- receiver: transfer.receiver,
216
- amount: transfer.amount,
217
- note: transfer.note,
218
- suggestedParams
219
- };
220
- const txn = transfer.assetId === void 0 ? _algosdk2.default.makePaymentTxnWithSuggestedParamsFromObject(common) : _algosdk2.default.makeAssetTransferTxnWithSuggestedParamsFromObject({
221
- ...common,
222
- assetIndex: transfer.assetId
223
- });
224
- return { txn, txId: txn.txID() };
225
- },
226
- async signSend({ txn, sk }) {
227
- const signed = txn.signTxn(sk);
228
- await algod.sendRawTransaction(signed).do();
229
- }
230
- };
231
- return {
232
- family: "algorand",
233
- network,
234
- supports: (n) => n === network,
235
- resolveToken(token) {
236
- if (token === "native") {
237
- return { asset: "native", decimals: ALGO_DECIMALS, symbol: ALGO_SYMBOL };
238
- }
239
- if (typeof token === "string") {
240
- const info = preset.tokens[token.toUpperCase()];
241
- if (!info) {
242
- const known = Object.keys(preset.tokens).join(", ") || "(none built in)";
243
- throw new (0, _chunkJG6KRAW6cjs.UnknownTokenError)(
244
- `token "${token}" isn't built in for Algorand (known: ${known}). Pass { assetId, decimals } for a custom ASA, or use 'native'.`
245
- );
246
- }
247
- return { asset: algorandAssetId(info.assetId), decimals: info.decimals, symbol: info.symbol };
248
- }
249
- _chunkJG6KRAW6cjs.rejectForeignToken.call(void 0, token, "algorand", network);
250
- const t = token;
251
- if (typeof t.assetId !== "number" || typeof t.decimals !== "number") {
252
- throw new (0, _chunkJG6KRAW6cjs.WrongFamilyError)(
253
- `chain ${network} is Algorand; a custom token must be { assetId, decimals }.`
254
- );
255
- }
256
- return {
257
- asset: algorandAssetId(t.assetId),
258
- decimals: t.decimals,
259
- ...t.symbol ? { symbol: t.symbol } : {}
260
- };
261
- },
262
- describeAsset(asset) {
263
- if (asset === "native") return { symbol: ALGO_SYMBOL, decimals: ALGO_DECIMALS };
264
- for (const info of Object.values(preset.tokens)) {
265
- if (algorandAssetId(info.assetId) === asset) {
266
- return { symbol: info.symbol, decimals: info.decimals };
267
- }
268
- }
269
- return null;
270
- },
271
- assertValidPayTo(payTo) {
272
- if (payTo.startsWith("0x")) {
273
- throw new (0, _chunkJG6KRAW6cjs.WrongFamilyError)(
274
- `chain ${network} is Algorand, but payTo "${payTo}" looks like an EVM address.`
275
- );
276
- }
277
- if (!_algosdk2.default.isValidAddress(payTo)) {
278
- throw new (0, _chunkJG6KRAW6cjs.WrongFamilyError)(
279
- `chain ${network} is Algorand, but payTo "${payTo}" is not a valid Algorand address.`
280
- );
281
- }
282
- },
283
- bindWallet(wallet) {
284
- return { _native: assertAlgorandWallet(wallet, network) };
285
- },
286
- async send(wallet, accept) {
287
- const signer = resolveAlgorandWallet(wallet._native);
288
- return payAlgorand({ client: payClient, sk: signer.sk, sender: signer.addr, accept });
289
- },
290
- async confirm(ref) {
291
- try {
292
- const info = await _algosdk2.default.waitForConfirmation(algod, ref, 10);
293
- return { height: String(_nullishCoalesce(info.confirmedRound, () => ( 0))) };
294
- } catch (err) {
295
- throw new (0, _chunkJG6KRAW6cjs.ConfirmationTimeoutError)(`Algorand tx ${ref} did not confirm in time.`, {
296
- cause: err
297
- });
298
- }
299
- },
300
- async estimateCost() {
301
- return _chunkJG6KRAW6cjs.nativeCost.call(void 0, {
302
- symbol: ALGO_SYMBOL,
303
- decimals: ALGO_DECIMALS,
304
- fee: 1000n,
305
- basis: "heuristic",
306
- detail: "min fee 1000 \xB5Algos (1 transaction)"
307
- });
308
- },
309
- async balanceOf(wallet, asset) {
310
- let owner;
311
- try {
312
- owner = resolveAlgorandWallet(wallet._native).addr;
313
- } catch (e4) {
314
- return { token: null, native: null };
315
- }
316
- let info;
317
- try {
318
- info = await algod.accountInformation(owner).do();
319
- } catch (e5) {
320
- return { token: null, native: null };
321
- }
322
- const native = info.amount != null ? BigInt(info.amount) : null;
323
- if (asset === "native") return { token: native, native };
324
- const assetId = parseAlgorandAssetId(asset);
325
- const holding = (_nullishCoalesce(info.assets, () => ( []))).find((a) => Number(a.assetId) === assetId);
326
- return { token: holding ? BigInt(holding.amount) : 0n, native };
327
- },
328
- async recipientReady(payTo, asset) {
329
- if (asset === "native") return { ready: "n/a" };
330
- const assetId = parseAlgorandAssetId(asset);
331
- if (assetId == null) return { ready: "unknown" };
332
- try {
333
- const info = await algod.accountInformation(payTo).do();
334
- const optedIn = (_nullishCoalesce(info.assets, () => ( []))).some((a) => Number(a.assetId) === assetId);
335
- return optedIn ? { ready: true } : { ready: false, reason: "NOT_OPTED_IN" };
336
- } catch (e) {
337
- if (/does not exist|no accounts found|404|account not found/i.test(String(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _ => _.message]), () => ( e))))) {
338
- return { ready: false, reason: "NOT_OPTED_IN" };
339
- }
340
- return { ready: "unknown" };
341
- }
342
- },
343
- async verify(_ref, accept) {
344
- return verifyAlgorand({ reader, accept });
345
- }
346
- };
347
- }
348
- function adaptTxn(raw) {
349
- const t = raw;
350
- if (!t || typeof t.id !== "string") return null;
351
- const note = t.note && t.note.length ? decodeNote(t.note) : void 0;
352
- const base = {
353
- id: t.id,
354
- txType: String(_nullishCoalesce(t.txType, () => ( ""))),
355
- ...note !== void 0 ? { note } : {},
356
- ...t.sender != null ? { sender: String(t.sender) } : {},
357
- ...typeof t.roundTime === "number" ? { roundTime: t.roundTime } : {}
358
- };
359
- if (t.paymentTransaction) {
360
- const pt = t.paymentTransaction;
361
- return {
362
- ...base,
363
- txType: "pay",
364
- ...pt.receiver != null ? { receiver: String(pt.receiver) } : {},
365
- ...pt.amount != null ? { amount: String(pt.amount) } : {}
366
- };
367
- }
368
- if (t.assetTransferTransaction) {
369
- const att = t.assetTransferTransaction;
370
- return {
371
- ...base,
372
- txType: "axfer",
373
- ...att.receiver != null ? { receiver: String(att.receiver) } : {},
374
- ...att.amount != null ? { amount: String(att.amount) } : {},
375
- ...att.assetId != null ? { assetId: Number(att.assetId) } : {}
376
- };
377
- }
378
- return base;
379
- }
380
- function decodeNote(bytes) {
381
- try {
382
- return new TextDecoder().decode(bytes);
383
- } catch (e6) {
384
- return void 0;
385
- }
386
- }
387
-
388
-
389
- exports.algorandDriver = algorandDriver;