@t2000/sdk 0.22.3 → 0.23.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.
package/dist/index.cjs CHANGED
@@ -7,7 +7,7 @@ var jsonRpc = require('@mysten/sui/jsonRpc');
7
7
  var utils = require('@mysten/sui/utils');
8
8
  var ed25519 = require('@mysten/sui/keypairs/ed25519');
9
9
  var cryptography = require('@mysten/sui/cryptography');
10
- var crypto = require('crypto');
10
+ var crypto$1 = require('crypto');
11
11
  var promises = require('fs/promises');
12
12
  var path = require('path');
13
13
  var os = require('os');
@@ -490,15 +490,27 @@ function assertAllowedAsset(op, asset) {
490
490
  );
491
491
  }
492
492
  }
493
- var T2000_PACKAGE_ID = process.env.T2000_PACKAGE_ID ?? "0xab92e9f1fe549ad3d6a52924a73181b45791e76120b975138fac9ec9b75db9f3";
494
- var T2000_CONFIG_ID = process.env.T2000_CONFIG_ID ?? "0x408add9aa9322f93cfd87523d8f603006eb8713894f4c460283c58a6888dae8a";
495
- var T2000_TREASURY_ID = process.env.T2000_TREASURY_ID ?? "0x3bb501b8300125dca59019247941a42af6b292a150ce3cfcce9449456be2ec91";
493
+ var T2000_PACKAGE_ID = process.env.T2000_PACKAGE_ID ?? "0xd775fcc66eae26797654d435d751dea56b82eeb999de51fd285348e573b968ad";
494
+ var T2000_CONFIG_ID = process.env.T2000_CONFIG_ID ?? "0x08ba26f0d260b5edf6a19c71492b3eb914906a7419baf2df1426765157e5862a";
495
+ var T2000_ADMIN_CAP_ID = "0xa97bfff140f5a2c268a03fe5422d382c228057deb7bcfdaf2967ca18b9bdbbd9";
496
+ var T2000_TREASURY_ID = process.env.T2000_TREASURY_ID ?? "0xf420ec0dcad44433042fb56e1413fb88d3ff65be94fcf425ef9ff750164590e8";
496
497
  var DEFAULT_NETWORK = "mainnet";
497
498
  var DEFAULT_RPC_URL = "https://fullnode.mainnet.sui.io:443";
498
499
  var DEFAULT_KEY_PATH = "~/.t2000/wallet.key";
499
500
  var API_BASE_URL = process.env.T2000_API_URL ?? "https://api.t2000.ai";
500
501
  var CETUS_USDC_SUI_POOL = "0x51e883ba7c0b566a26cbc8a94cd33eb0abd418a77cc1e60ad22fd9b1f29cd2ab";
501
502
  var GAS_RESERVE_MIN = 0.05;
503
+ var ALLOWANCE_FEATURES = {
504
+ BRIEFING: 0,
505
+ YIELD_ALERT: 1,
506
+ PAYMENT_ALERT: 2,
507
+ ACTION_REMIND: 3,
508
+ SESSION: 4,
509
+ AUTO_COMPOUND: 5,
510
+ DCA: 6,
511
+ HF_ALERT: 7
512
+ };
513
+ var FEATURES_ALL = 255;
502
514
 
503
515
  // src/utils/sui.ts
504
516
  init_errors();
@@ -534,13 +546,13 @@ function expandPath(p) {
534
546
  return path.resolve(p);
535
547
  }
536
548
  function deriveKey(passphrase, salt) {
537
- return crypto.scryptSync(passphrase, salt, 32, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
549
+ return crypto$1.scryptSync(passphrase, salt, 32, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
538
550
  }
539
551
  function encrypt(data, passphrase) {
540
- const salt = crypto.randomBytes(SALT_LENGTH);
552
+ const salt = crypto$1.randomBytes(SALT_LENGTH);
541
553
  const key = deriveKey(passphrase, salt);
542
- const iv = crypto.randomBytes(IV_LENGTH);
543
- const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
554
+ const iv = crypto$1.randomBytes(IV_LENGTH);
555
+ const cipher = crypto$1.createCipheriv(ALGORITHM, key, iv);
544
556
  const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
545
557
  const tag = cipher.getAuthTag();
546
558
  return {
@@ -558,7 +570,7 @@ function decrypt(encrypted, passphrase) {
558
570
  const iv = Buffer.from(encrypted.iv, "hex");
559
571
  const tag = Buffer.from(encrypted.tag, "hex");
560
572
  const ciphertext = Buffer.from(encrypted.ciphertext, "hex");
561
- const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
573
+ const decipher = crypto$1.createDecipheriv(ALGORITHM, key, iv);
562
574
  decipher.setAuthTag(tag);
563
575
  try {
564
576
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
@@ -1648,7 +1660,7 @@ function solveHashcash(challenge) {
1648
1660
  let counter = 0;
1649
1661
  while (true) {
1650
1662
  const stamp = `${challenge}${counter.toString(16)}`;
1651
- const hash = crypto.createHash("sha256").update(stamp).digest();
1663
+ const hash = crypto$1.createHash("sha256").update(stamp).digest();
1652
1664
  if (hasLeadingZeroBits(hash, bits)) return stamp;
1653
1665
  counter++;
1654
1666
  }
@@ -3263,6 +3275,190 @@ async function callUsdcSponsorApi(address) {
3263
3275
 
3264
3276
  // src/index.ts
3265
3277
  init_errors();
3278
+ var USDC_TYPE2 = SUPPORTED_ASSETS.USDC.type;
3279
+ function buildCreateAllowanceTx(options = {}) {
3280
+ const tx = new transactions.Transaction();
3281
+ tx.moveCall({
3282
+ target: `${T2000_PACKAGE_ID}::allowance::create`,
3283
+ typeArguments: [USDC_TYPE2],
3284
+ arguments: [
3285
+ tx.pure.u64(options.permittedFeatures ?? BigInt(FEATURES_ALL)),
3286
+ tx.pure.u64(options.expiresAt ?? 0n),
3287
+ tx.pure.u64(options.dailyLimit ?? 0n),
3288
+ tx.object(CLOCK_ID)
3289
+ ]
3290
+ });
3291
+ return tx;
3292
+ }
3293
+ function addDepositAllowanceTx(tx, allowanceId, paymentCoin) {
3294
+ tx.moveCall({
3295
+ target: `${T2000_PACKAGE_ID}::allowance::deposit`,
3296
+ typeArguments: [USDC_TYPE2],
3297
+ arguments: [tx.object(allowanceId), paymentCoin]
3298
+ });
3299
+ }
3300
+ function buildDepositAllowanceTx(allowanceId, usdcCoin, amount) {
3301
+ const tx = new transactions.Transaction();
3302
+ const [split] = tx.splitCoins(tx.object(usdcCoin), [tx.pure.u64(amount)]);
3303
+ addDepositAllowanceTx(tx, allowanceId, split);
3304
+ return tx;
3305
+ }
3306
+ function buildAdminDepositAllowanceTx(allowanceId, usdcCoin, amount) {
3307
+ const tx = new transactions.Transaction();
3308
+ const [split] = tx.splitCoins(tx.object(usdcCoin), [tx.pure.u64(amount)]);
3309
+ tx.moveCall({
3310
+ target: `${T2000_PACKAGE_ID}::allowance::admin_deposit`,
3311
+ typeArguments: [USDC_TYPE2],
3312
+ arguments: [
3313
+ tx.object(allowanceId),
3314
+ tx.object(T2000_ADMIN_CAP_ID),
3315
+ split
3316
+ ]
3317
+ });
3318
+ return tx;
3319
+ }
3320
+ function buildDeductAllowanceTx(allowanceId, amount, feature) {
3321
+ const tx = new transactions.Transaction();
3322
+ tx.moveCall({
3323
+ target: `${T2000_PACKAGE_ID}::allowance::deduct`,
3324
+ typeArguments: [USDC_TYPE2],
3325
+ arguments: [
3326
+ tx.object(allowanceId),
3327
+ tx.object(T2000_CONFIG_ID),
3328
+ tx.object(T2000_ADMIN_CAP_ID),
3329
+ tx.pure.u64(amount),
3330
+ tx.pure.u8(feature),
3331
+ tx.object(CLOCK_ID)
3332
+ ]
3333
+ });
3334
+ return tx;
3335
+ }
3336
+ function buildWithdrawAllowanceTx(allowanceId) {
3337
+ const tx = new transactions.Transaction();
3338
+ tx.moveCall({
3339
+ target: `${T2000_PACKAGE_ID}::allowance::withdraw`,
3340
+ typeArguments: [USDC_TYPE2],
3341
+ arguments: [tx.object(allowanceId)]
3342
+ });
3343
+ return tx;
3344
+ }
3345
+ function buildWithdrawAmountAllowanceTx(allowanceId, amount) {
3346
+ const tx = new transactions.Transaction();
3347
+ tx.moveCall({
3348
+ target: `${T2000_PACKAGE_ID}::allowance::withdraw_amount`,
3349
+ typeArguments: [USDC_TYPE2],
3350
+ arguments: [tx.object(allowanceId), tx.pure.u64(amount)]
3351
+ });
3352
+ return tx;
3353
+ }
3354
+ async function getAllowance(client, allowanceId) {
3355
+ const obj = await client.getObject({
3356
+ id: allowanceId,
3357
+ options: { showContent: true, showType: true }
3358
+ });
3359
+ if (!obj.data?.content || obj.data.content.dataType !== "moveObject") {
3360
+ throw new Error(`Allowance ${allowanceId} not found or is not a Move object`);
3361
+ }
3362
+ const fields = obj.data.content.fields;
3363
+ const coinType = extractCoinType(obj.data.content.type);
3364
+ return {
3365
+ id: allowanceId,
3366
+ owner: fields.owner,
3367
+ balance: parseU64Field(fields.balance),
3368
+ totalDeposited: parseU64Field(fields.total_deposited),
3369
+ totalSpent: parseU64Field(fields.total_spent),
3370
+ createdAt: Number(fields.created_at),
3371
+ coinType,
3372
+ permittedFeatures: parseU64Field(fields.permitted_features),
3373
+ expiresAt: Number(fields.expires_at),
3374
+ dailyLimit: parseU64Field(fields.daily_limit),
3375
+ dailySpent: parseU64Field(fields.daily_spent),
3376
+ windowStart: Number(fields.window_start)
3377
+ };
3378
+ }
3379
+ async function getAllowanceBalance(client, allowanceId) {
3380
+ const info = await getAllowance(client, allowanceId);
3381
+ return info.balance;
3382
+ }
3383
+ function parseU64Field(raw) {
3384
+ if (typeof raw === "string" || typeof raw === "number") return BigInt(raw);
3385
+ if (typeof raw === "object" && raw !== null && "value" in raw) {
3386
+ return BigInt(raw.value);
3387
+ }
3388
+ return 0n;
3389
+ }
3390
+ function extractCoinType(objectType) {
3391
+ const match = objectType.match(/<(.+)>/);
3392
+ return match ? match[1] : "unknown";
3393
+ }
3394
+
3395
+ // src/protocols/financialSummary.ts
3396
+ var HF_WARN_THRESHOLD = 1.8;
3397
+ var HF_CRITICAL_THRESHOLD = 1.3;
3398
+ var HF_FALLBACK = {
3399
+ healthFactor: Infinity,
3400
+ supplied: 0,
3401
+ borrowed: 0,
3402
+ maxBorrow: 0,
3403
+ liquidationThreshold: 0.75
3404
+ };
3405
+ function classifyHF(hf, hasBorrow) {
3406
+ if (!hasBorrow || !Number.isFinite(hf)) return "none";
3407
+ if (hf <= HF_CRITICAL_THRESHOLD) return "critical";
3408
+ if (hf <= HF_WARN_THRESHOLD) return "warn";
3409
+ return "none";
3410
+ }
3411
+ async function fetchSuiPriceUsd(client) {
3412
+ try {
3413
+ const pool = await client.getObject({
3414
+ id: CETUS_USDC_SUI_POOL,
3415
+ options: { showContent: true }
3416
+ });
3417
+ if (pool.data?.content?.dataType === "moveObject") {
3418
+ const fields = pool.data.content.fields;
3419
+ const sqrtPrice = BigInt(String(fields.current_sqrt_price ?? "0"));
3420
+ if (sqrtPrice > 0n) {
3421
+ const Q64 = 2n ** 64n;
3422
+ const sqrtFloat = Number(sqrtPrice) / Number(Q64);
3423
+ const price = 1e3 / (sqrtFloat * sqrtFloat);
3424
+ if (price > 0.01 && price < 1e3) return price;
3425
+ }
3426
+ }
3427
+ } catch {
3428
+ }
3429
+ return 1;
3430
+ }
3431
+ async function getFinancialSummary(client, walletAddress, options = {}) {
3432
+ const [usdcBal, suiBal, hf, rates, suiPrice, allowance] = await Promise.all([
3433
+ client.getBalance({ owner: walletAddress, coinType: SUPPORTED_ASSETS.USDC.type }).catch(() => ({ totalBalance: "0" })),
3434
+ client.getBalance({ owner: walletAddress, coinType: SUPPORTED_ASSETS.SUI.type }).catch(() => ({ totalBalance: "0" })),
3435
+ getHealthFactor(client, walletAddress).catch(() => HF_FALLBACK),
3436
+ getRates(client),
3437
+ fetchSuiPriceUsd(client),
3438
+ options.allowanceId ? getAllowanceBalance(client, options.allowanceId).catch(() => null) : Promise.resolve(null)
3439
+ ]);
3440
+ const usdcAvailable = Number(usdcBal.totalBalance) / 10 ** SUPPORTED_ASSETS.USDC.decimals;
3441
+ const gasReserveSui = Number(suiBal.totalBalance) / Number(MIST_PER_SUI);
3442
+ const saveApy = rates.USDC?.saveApy ?? 0;
3443
+ const borrowApy = rates.USDC?.borrowApy ?? 0;
3444
+ const dailyYield = hf.supplied * (saveApy / 365);
3445
+ return {
3446
+ walletAddress,
3447
+ usdcAvailable,
3448
+ savingsBalance: hf.supplied,
3449
+ debtBalance: hf.borrowed,
3450
+ idleUsdc: Math.max(0, usdcAvailable),
3451
+ healthFactor: hf.healthFactor,
3452
+ hfAlertLevel: classifyHF(hf.healthFactor, hf.borrowed > 0),
3453
+ saveApy,
3454
+ borrowApy,
3455
+ dailyYield,
3456
+ gasReserveSui,
3457
+ gasReserveUsd: gasReserveSui * suiPrice,
3458
+ allowanceBalance: allowance,
3459
+ fetchedAt: Date.now()
3460
+ };
3461
+ }
3266
3462
 
3267
3463
  // src/utils/simulate.ts
3268
3464
  init_errors();
@@ -3374,7 +3570,60 @@ async function getSwapQuote(params) {
3374
3570
  init_cetus_swap();
3375
3571
  init_token_registry();
3376
3572
  init_volo();
3573
+ var DEFAULT_TTL_MS = 6e4;
3574
+ async function buildScopedIntent(adminKeypair, params) {
3575
+ const now = Date.now();
3576
+ const nonceBytes = new Uint8Array(32);
3577
+ crypto.getRandomValues(nonceBytes);
3578
+ const nonce = Buffer.from(nonceBytes).toString("hex");
3579
+ const payload = {
3580
+ version: 1,
3581
+ userId: params.userId,
3582
+ walletAddress: params.walletAddress,
3583
+ allowanceObjectId: params.allowanceObjectId,
3584
+ featureCode: params.featureCode,
3585
+ maxAmount: params.maxAmount,
3586
+ issuedAt: now,
3587
+ expiresAt: now + (params.ttlMs ?? DEFAULT_TTL_MS),
3588
+ nonce
3589
+ };
3590
+ const message = canonicalIntentBytes(payload);
3591
+ const signature = await adminKeypair.sign(message);
3592
+ return {
3593
+ ...payload,
3594
+ signature: Buffer.from(signature).toString("hex")
3595
+ };
3596
+ }
3597
+ async function verifyScopedIntent(intent, adminPublicKeyBytes) {
3598
+ if (Date.now() > intent.expiresAt) return false;
3599
+ const payload = {
3600
+ version: intent.version,
3601
+ userId: intent.userId,
3602
+ walletAddress: intent.walletAddress,
3603
+ allowanceObjectId: intent.allowanceObjectId,
3604
+ featureCode: intent.featureCode,
3605
+ maxAmount: intent.maxAmount,
3606
+ issuedAt: intent.issuedAt,
3607
+ expiresAt: intent.expiresAt,
3608
+ nonce: intent.nonce
3609
+ };
3610
+ const message = canonicalIntentBytes(payload);
3611
+ const signatureBytes = Buffer.from(intent.signature, "hex");
3612
+ try {
3613
+ const publicKey = new ed25519.Ed25519PublicKey(adminPublicKeyBytes);
3614
+ return await publicKey.verify(message, signatureBytes);
3615
+ } catch {
3616
+ return false;
3617
+ }
3618
+ }
3619
+ function canonicalIntentBytes(payload) {
3620
+ const sorted = Object.fromEntries(
3621
+ Object.entries(payload).sort(([a], [b]) => a.localeCompare(b))
3622
+ );
3623
+ return new TextEncoder().encode(JSON.stringify(sorted));
3624
+ }
3377
3625
 
3626
+ exports.ALLOWANCE_FEATURES = ALLOWANCE_FEATURES;
3378
3627
  exports.ALL_NAVI_ASSETS = ALL_NAVI_ASSETS;
3379
3628
  exports.BPS_DENOMINATOR = BPS_DENOMINATOR;
3380
3629
  exports.CETUS_USDC_SUI_POOL = CETUS_USDC_SUI_POOL;
@@ -3383,6 +3632,8 @@ exports.ContactManager = ContactManager;
3383
3632
  exports.DEFAULT_NETWORK = DEFAULT_NETWORK;
3384
3633
  exports.DEFAULT_SAFEGUARD_CONFIG = DEFAULT_SAFEGUARD_CONFIG;
3385
3634
  exports.GAS_RESERVE_MIN = GAS_RESERVE_MIN;
3635
+ exports.HF_CRITICAL_THRESHOLD = HF_CRITICAL_THRESHOLD;
3636
+ exports.HF_WARN_THRESHOLD = HF_WARN_THRESHOLD;
3386
3637
  exports.KeypairSigner = KeypairSigner;
3387
3638
  exports.MIST_PER_SUI = MIST_PER_SUI;
3388
3639
  exports.NaviAdapter = NaviAdapter;
@@ -3398,11 +3649,19 @@ exports.T2000 = T2000;
3398
3649
  exports.USDC_DECIMALS = USDC_DECIMALS;
3399
3650
  exports.ZkLoginSigner = ZkLoginSigner;
3400
3651
  exports.addCollectFeeToTx = addCollectFeeToTx;
3652
+ exports.addDepositAllowanceTx = addDepositAllowanceTx;
3401
3653
  exports.allDescriptors = allDescriptors;
3402
3654
  exports.assertAllowedAsset = assertAllowedAsset;
3655
+ exports.buildAdminDepositAllowanceTx = buildAdminDepositAllowanceTx;
3656
+ exports.buildCreateAllowanceTx = buildCreateAllowanceTx;
3657
+ exports.buildDeductAllowanceTx = buildDeductAllowanceTx;
3658
+ exports.buildDepositAllowanceTx = buildDepositAllowanceTx;
3659
+ exports.buildScopedIntent = buildScopedIntent;
3403
3660
  exports.buildStakeVSuiTx = buildStakeVSuiTx;
3404
3661
  exports.buildSwapTx = buildSwapTx;
3405
3662
  exports.buildUnstakeVSuiTx = buildUnstakeVSuiTx;
3663
+ exports.buildWithdrawAllowanceTx = buildWithdrawAllowanceTx;
3664
+ exports.buildWithdrawAmountAllowanceTx = buildWithdrawAmountAllowanceTx;
3406
3665
  exports.calculateFee = calculateFee;
3407
3666
  exports.executeAutoTopUp = executeAutoTopUp;
3408
3667
  exports.executeWithGas = executeWithGas;
@@ -3413,8 +3672,11 @@ exports.formatSui = formatSui;
3413
3672
  exports.formatUsd = formatUsd;
3414
3673
  exports.generateKeypair = generateKeypair;
3415
3674
  exports.getAddress = getAddress;
3675
+ exports.getAllowance = getAllowance;
3676
+ exports.getAllowanceBalance = getAllowanceBalance;
3416
3677
  exports.getDecimals = getDecimals;
3417
3678
  exports.getDecimalsForCoinType = getDecimalsForCoinType;
3679
+ exports.getFinancialSummary = getFinancialSummary;
3418
3680
  exports.getGasStatus = getGasStatus;
3419
3681
  exports.getRates = getRates;
3420
3682
  exports.getSwapQuote = getSwapQuote;
@@ -3444,6 +3706,7 @@ exports.throwIfSimulationFailed = throwIfSimulationFailed;
3444
3706
  exports.truncateAddress = truncateAddress;
3445
3707
  exports.usdcToRaw = usdcToRaw;
3446
3708
  exports.validateAddress = validateAddress;
3709
+ exports.verifyScopedIntent = verifyScopedIntent;
3447
3710
  exports.walletExists = walletExists;
3448
3711
  //# sourceMappingURL=index.cjs.map
3449
3712
  //# sourceMappingURL=index.cjs.map