@autonomys/auto-consensus 1.5.1 → 1.5.3

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.
Files changed (62) hide show
  1. package/dist/account.d.ts +26 -0
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/account.js +26 -0
  4. package/dist/balances.d.ts +50 -0
  5. package/dist/balances.d.ts.map +1 -1
  6. package/dist/balances.js +50 -0
  7. package/dist/batch.d.ts +29 -0
  8. package/dist/batch.d.ts.map +1 -1
  9. package/dist/batch.js +29 -0
  10. package/dist/domain.d.ts +58 -1
  11. package/dist/domain.d.ts.map +1 -1
  12. package/dist/domain.js +116 -12
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -0
  16. package/dist/info.d.ts +406 -0
  17. package/dist/info.d.ts.map +1 -1
  18. package/dist/info.js +406 -0
  19. package/dist/position/index.d.ts +42 -0
  20. package/dist/position/index.d.ts.map +1 -0
  21. package/dist/position/index.js +170 -0
  22. package/dist/position/price.d.ts +69 -0
  23. package/dist/position/price.d.ts.map +1 -0
  24. package/dist/position/price.js +137 -0
  25. package/dist/position/utils.d.ts +62 -0
  26. package/dist/position/utils.d.ts.map +1 -0
  27. package/dist/position/utils.js +73 -0
  28. package/dist/position.d.ts +4 -0
  29. package/dist/position.d.ts.map +1 -0
  30. package/dist/position.js +20 -0
  31. package/dist/remark.d.ts +29 -0
  32. package/dist/remark.d.ts.map +1 -1
  33. package/dist/remark.js +29 -0
  34. package/dist/staking.d.ts +305 -0
  35. package/dist/staking.d.ts.map +1 -1
  36. package/dist/staking.js +327 -4
  37. package/dist/transfer.d.ts +59 -0
  38. package/dist/transfer.d.ts.map +1 -1
  39. package/dist/transfer.js +59 -0
  40. package/dist/types/domain.d.ts +1 -0
  41. package/dist/types/domain.d.ts.map +1 -1
  42. package/dist/types/index.d.ts +1 -0
  43. package/dist/types/index.d.ts.map +1 -1
  44. package/dist/types/index.js +1 -0
  45. package/dist/types/position.d.ts +13 -0
  46. package/dist/types/position.d.ts.map +1 -0
  47. package/dist/types/position.js +2 -0
  48. package/dist/types/staking.d.ts +2 -2
  49. package/dist/types/staking.d.ts.map +1 -1
  50. package/dist/utils/format.d.ts +86 -0
  51. package/dist/utils/format.d.ts.map +1 -1
  52. package/dist/utils/format.js +86 -0
  53. package/dist/utils/parse.d.ts +1 -1
  54. package/dist/utils/parse.d.ts.map +1 -1
  55. package/dist/utils/parse.js +5 -3
  56. package/dist/utils/query.d.ts +31 -0
  57. package/dist/utils/query.d.ts.map +1 -1
  58. package/dist/utils/query.js +31 -0
  59. package/dist/utils/sudo.d.ts +36 -0
  60. package/dist/utils/sudo.d.ts.map +1 -1
  61. package/dist/utils/sudo.js +36 -0
  62. package/package.json +3 -3
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.nominatorPosition = void 0;
13
+ const domain_1 = require("../domain");
14
+ const staking_1 = require("../staking");
15
+ const price_1 = require("./price");
16
+ const utils_1 = require("./utils");
17
+ /**
18
+ * Processes pending deposits to calculate additional shares and storage fees
19
+ */
20
+ const processPendingDeposits = (api, operatorId, depositData, currentEpochIndex) => __awaiter(void 0, void 0, void 0, function* () {
21
+ const zeroAmounts = {
22
+ additionalShares: BigInt(0),
23
+ pendingStorageFee: BigInt(0),
24
+ pendingDeposits: [],
25
+ };
26
+ if (!depositData.pending)
27
+ return zeroAmounts;
28
+ const { effectiveDomainEpoch, amount, storageFeeDeposit: pendingStorageFee } = depositData.pending;
29
+ // If epoch hasn't passed yet, keep as pending
30
+ if (effectiveDomainEpoch >= currentEpochIndex) {
31
+ return Object.assign(Object.assign({}, zeroAmounts), { pendingStorageFee, pendingDeposits: [{ amount, effectiveEpoch: effectiveDomainEpoch }] });
32
+ }
33
+ // Epoch has passed - convert pending amount to shares
34
+ try {
35
+ const epochSharePrice = yield (0, price_1.operatorEpochSharePrice)(api, operatorId, effectiveDomainEpoch, 0);
36
+ const additionalShares = epochSharePrice !== undefined ? (0, utils_1.stakeToShare)(amount, epochSharePrice) : amount; // Fallback: assume 1:1 conversion
37
+ if (epochSharePrice === undefined) {
38
+ console.warn(`No epoch share price found for epoch ${effectiveDomainEpoch}, using pending amount as is`);
39
+ }
40
+ return {
41
+ additionalShares,
42
+ pendingStorageFee, // Storage fee from processed pending deposit
43
+ pendingDeposits: [], // Empty array indicates pending deposit was processed
44
+ };
45
+ }
46
+ catch (error) {
47
+ console.warn(`Error getting epoch share price for epoch ${effectiveDomainEpoch}, treating as still pending:`, error);
48
+ return Object.assign(Object.assign({}, zeroAmounts), { pendingStorageFee, pendingDeposits: [{ amount, effectiveEpoch: effectiveDomainEpoch }] });
49
+ }
50
+ });
51
+ /**
52
+ * Processes pending withdrawals to calculate withdrawal amounts and unlock blocks
53
+ */
54
+ const processPendingWithdrawals = (api, operatorId, withdrawalsData, currentEpochIndex) => __awaiter(void 0, void 0, void 0, function* () {
55
+ const pendingWithdrawals = [];
56
+ if (withdrawalsData.length === 0)
57
+ return pendingWithdrawals;
58
+ for (const withdrawal of withdrawalsData) {
59
+ const { withdrawalInShares } = withdrawal;
60
+ // Skip if no withdrawalInShares
61
+ if (!withdrawalInShares)
62
+ continue;
63
+ const { domainEpoch, shares, unlockAtConfirmedDomainBlockNumber } = withdrawalInShares;
64
+ // Process regular withdrawals
65
+ for (const w of withdrawal.withdrawals) {
66
+ pendingWithdrawals.push({
67
+ amount: w.amountToUnlock,
68
+ unlockAtDomainBlock: w.unlockAtConfirmedDomainBlockNumber,
69
+ });
70
+ }
71
+ const sharePrice =
72
+ // If withdrawal epoch has passed, use its share price, otherwise use instant share price
73
+ domainEpoch[1] < currentEpochIndex
74
+ ? yield (0, price_1.operatorEpochSharePrice)(api, operatorId, domainEpoch[1], // epoch index
75
+ domainEpoch[0])
76
+ : yield (0, price_1.instantSharePrice)(api, operatorId);
77
+ const withdrawalAmount = sharePrice ? (0, utils_1.shareToStake)(shares, sharePrice) : BigInt(0); // fallback to 0 if no price available
78
+ pendingWithdrawals.push({
79
+ amount: withdrawalAmount,
80
+ unlockAtDomainBlock: unlockAtConfirmedDomainBlockNumber,
81
+ });
82
+ }
83
+ return pendingWithdrawals;
84
+ });
85
+ /**
86
+ * Retrieves the complete staking position of a nominator for a specific operator.
87
+ *
88
+ * This function calculates the comprehensive staking position of a nominator including
89
+ * current value, pending deposits, pending withdrawals, and storage fee deposits.
90
+ * It handles complex calculations involving share prices across different epochs
91
+ * and provides a complete view of the nominator's stake position.
92
+ *
93
+ * @param api - The connected API instance
94
+ * @param operatorId - The ID of the operator to query position for
95
+ * @param nominatorAccountId - The account ID of the nominator
96
+ * @returns Promise that resolves to NominatorPosition with complete position details
97
+ * @throws Error if operator not found, domain staking summary unavailable, or calculation fails
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * import { nominatorPosition } from '@autonomys/auto-consensus'
102
+ * import { activate } from '@autonomys/auto-utils'
103
+ *
104
+ * const api = await activate({ networkId: 'gemini-3h' })
105
+ * const position = await nominatorPosition(api, '1', 'nominator_account_address')
106
+ *
107
+ * console.log(`Current Value: ${position.knownValue}`)
108
+ * console.log(`Storage Fee Deposit: ${position.storageFeeDeposit}`)
109
+ * console.log(`Pending Deposits: ${position.pendingDeposits.length}`)
110
+ * console.log(`Pending Withdrawals: ${position.pendingWithdrawals.length}`)
111
+ *
112
+ * // Check pending deposits
113
+ * position.pendingDeposits.forEach(deposit => {
114
+ * console.log(`Pending: ${deposit.amount} at epoch ${deposit.effectiveEpoch}`)
115
+ * })
116
+ *
117
+ * // Check pending withdrawals
118
+ * position.pendingWithdrawals.forEach(withdrawal => {
119
+ * console.log(`Withdrawal: ${withdrawal.amount} unlocks at block ${withdrawal.unlockAtBlock}`)
120
+ * })
121
+ * ```
122
+ */
123
+ const nominatorPosition = (api, operatorId, nominatorAccountId) => __awaiter(void 0, void 0, void 0, function* () {
124
+ try {
125
+ // TODO: handle when operator is not found
126
+ const operatorData = yield (0, staking_1.operator)(api, operatorId);
127
+ // Step 1: Get deposits, withdrawals, and domain staking summary
128
+ const [depositsData, withdrawalsData, stakingSummary] = yield Promise.all([
129
+ (0, staking_1.deposits)(api, operatorId, nominatorAccountId),
130
+ (0, staking_1.withdrawals)(api, operatorId, nominatorAccountId),
131
+ (0, domain_1.domainStakingSummary)(api, operatorData.currentDomainId),
132
+ ]);
133
+ if (!stakingSummary) {
134
+ throw new Error('Domain staking summary not found');
135
+ }
136
+ // Find the deposit data for the operator
137
+ const depositData = depositsData.find((d) => String(d.operatorId) === String(operatorId));
138
+ if (!depositData) {
139
+ return {
140
+ knownValue: BigInt(0),
141
+ pendingDeposits: [],
142
+ pendingWithdrawals: [],
143
+ storageFeeDeposit: BigInt(0),
144
+ };
145
+ }
146
+ const { currentEpochIndex } = stakingSummary;
147
+ // Process pending deposits
148
+ const { additionalShares, pendingStorageFee, pendingDeposits } = yield processPendingDeposits(api, operatorId, depositData, currentEpochIndex);
149
+ // Calculate final totals
150
+ const totalShares = depositData.known.shares + additionalShares;
151
+ // Calculate total storage fee deposit: known + pending (handled by processPendingDeposits)
152
+ const totalStorageFeeDeposit = depositData.known.storageFeeDeposit + pendingStorageFee;
153
+ // Calculate current position value
154
+ const currentSharePrice = yield (0, price_1.instantSharePrice)(api, operatorId);
155
+ const knownValue = (0, utils_1.shareToStake)(totalShares, currentSharePrice);
156
+ // Process pending withdrawals
157
+ const pendingWithdrawals = yield processPendingWithdrawals(api, operatorId, withdrawalsData, currentEpochIndex);
158
+ return {
159
+ knownValue,
160
+ pendingDeposits,
161
+ pendingWithdrawals,
162
+ storageFeeDeposit: totalStorageFeeDeposit,
163
+ };
164
+ }
165
+ catch (error) {
166
+ console.error('Error calculating nominator position:', error);
167
+ throw new Error(`Error calculating position for nominator ${nominatorAccountId} in operator ${operatorId}: ${error}`);
168
+ }
169
+ });
170
+ exports.nominatorPosition = nominatorPosition;
@@ -0,0 +1,69 @@
1
+ import type { Api } from '@autonomys/auto-utils';
2
+ /**
3
+ * Retrieves the stored share price for a specific operator at a given domain epoch.
4
+ *
5
+ * This function fetches the historical share price that was recorded for an operator
6
+ * at a specific domain epoch. Share prices are stored when staking activity occurs
7
+ * and are used to convert between stake amounts and shares at different points in time.
8
+ * The price is returned in 18-decimal Perbill format.
9
+ *
10
+ * @param api - The connected API instance
11
+ * @param operatorId - The ID of the operator to query price for
12
+ * @param domainEpoch - The domain epoch index to query price for
13
+ * @param domainId - The domain ID (default: 0)
14
+ * @returns Promise that resolves to share price in 18-decimal Perbill format, or undefined if no price stored
15
+ * @throws Error if the query fails or operator/epoch not found
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { operatorEpochSharePrice } from '@autonomys/auto-consensus'
20
+ * import { activate } from '@autonomys/auto-utils'
21
+ *
22
+ * const api = await activate({ networkId: 'gemini-3h' })
23
+ *
24
+ * // Get share price for operator 1 at epoch 100
25
+ * const sharePrice = await operatorEpochSharePrice(api, '1', 100, 0)
26
+ *
27
+ * if (sharePrice) {
28
+ * console.log(`Share price at epoch 100: ${sharePrice}`)
29
+ * // Use for stake/share conversions at that epoch
30
+ * } else {
31
+ * console.log('No share price recorded for that epoch')
32
+ * }
33
+ * ```
34
+ */
35
+ export declare const operatorEpochSharePrice: (api: Api, operatorId: string | number | bigint, domainEpoch: string | number | bigint, domainId?: string | number | bigint) => Promise<bigint | undefined>;
36
+ /**
37
+ * Calculates the current real-time share price for an operator.
38
+ *
39
+ * This function computes the current share price by considering the operator's
40
+ * total stake, current epoch rewards (after nomination tax), and total shares.
41
+ * The calculation provides an up-to-date price that reflects recent staking
42
+ * activity and rewards distribution.
43
+ *
44
+ * Formula: (currentTotalStake + currentEpochReward * (1 - nominationTax)) / currentTotalShares
45
+ *
46
+ * @param api - The connected API instance
47
+ * @param operatorId - The ID of the operator to calculate price for
48
+ * @returns Promise that resolves to current share price in 18-decimal Perbill format
49
+ * @throws Error if operator not found, domain staking summary unavailable, or calculation fails
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * import { instantSharePrice } from '@autonomys/auto-consensus'
54
+ * import { activate } from '@autonomys/auto-utils'
55
+ *
56
+ * const api = await activate({ networkId: 'gemini-3h' })
57
+ *
58
+ * // Get current share price for operator 1
59
+ * const currentPrice = await instantSharePrice(api, '1')
60
+ * console.log(`Current share price: ${currentPrice}`)
61
+ *
62
+ * // Use for real-time stake/share conversions
63
+ * const stakeAmount = BigInt('1000000000000000000') // 1 AI3
64
+ * const sharesEquivalent = (stakeAmount * BigInt(10 ** 18)) / currentPrice
65
+ * console.log(`${stakeAmount} stake = ${sharesEquivalent} shares`)
66
+ * ```
67
+ */
68
+ export declare const instantSharePrice: (api: Api, operatorId: string | number | bigint) => Promise<bigint>;
69
+ //# sourceMappingURL=price.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"price.d.ts","sourceRoot":"","sources":["../../src/position/price.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,uBAAuB,CAAA;AAKhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,eAAO,MAAM,uBAAuB,GAClC,KAAK,GAAG,EACR,YAAY,MAAM,GAAG,MAAM,GAAG,MAAM,EACpC,aAAa,MAAM,GAAG,MAAM,GAAG,MAAM,EACrC,WAAU,MAAM,GAAG,MAAM,GAAG,MAAU,KACrC,OAAO,CAAC,MAAM,GAAG,SAAS,CAmC5B,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,eAAO,MAAM,iBAAiB,GAC5B,KAAK,GAAG,EACR,YAAY,MAAM,GAAG,MAAM,GAAG,MAAM,KACnC,OAAO,CAAC,MAAM,CAiChB,CAAA"}
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.instantSharePrice = exports.operatorEpochSharePrice = void 0;
13
+ const domain_1 = require("../domain");
14
+ const staking_1 = require("../staking");
15
+ const parse_1 = require("../utils/parse");
16
+ /**
17
+ * Retrieves the stored share price for a specific operator at a given domain epoch.
18
+ *
19
+ * This function fetches the historical share price that was recorded for an operator
20
+ * at a specific domain epoch. Share prices are stored when staking activity occurs
21
+ * and are used to convert between stake amounts and shares at different points in time.
22
+ * The price is returned in 18-decimal Perbill format.
23
+ *
24
+ * @param api - The connected API instance
25
+ * @param operatorId - The ID of the operator to query price for
26
+ * @param domainEpoch - The domain epoch index to query price for
27
+ * @param domainId - The domain ID (default: 0)
28
+ * @returns Promise that resolves to share price in 18-decimal Perbill format, or undefined if no price stored
29
+ * @throws Error if the query fails or operator/epoch not found
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * import { operatorEpochSharePrice } from '@autonomys/auto-consensus'
34
+ * import { activate } from '@autonomys/auto-utils'
35
+ *
36
+ * const api = await activate({ networkId: 'gemini-3h' })
37
+ *
38
+ * // Get share price for operator 1 at epoch 100
39
+ * const sharePrice = await operatorEpochSharePrice(api, '1', 100, 0)
40
+ *
41
+ * if (sharePrice) {
42
+ * console.log(`Share price at epoch 100: ${sharePrice}`)
43
+ * // Use for stake/share conversions at that epoch
44
+ * } else {
45
+ * console.log('No share price recorded for that epoch')
46
+ * }
47
+ * ```
48
+ */
49
+ const operatorEpochSharePrice = (api_1, operatorId_1, domainEpoch_1, ...args_1) => __awaiter(void 0, [api_1, operatorId_1, domainEpoch_1, ...args_1], void 0, function* (api, operatorId, domainEpoch, domainId = 0) {
50
+ try {
51
+ // Create domain epoch tuple [domainId, epochIndex]
52
+ const domainEpochTuple = [(0, parse_1.parseString)(domainId), (0, parse_1.parseString)(domainEpoch)];
53
+ const sharePrice = yield api.query.domains.operatorEpochSharePrice((0, parse_1.parseString)(operatorId), domainEpochTuple);
54
+ if (sharePrice.isEmpty) {
55
+ return undefined;
56
+ }
57
+ // The response is a direct Perbill value, not an object
58
+ const priceValue = sharePrice.toJSON();
59
+ if (priceValue === null || priceValue === undefined) {
60
+ return undefined;
61
+ }
62
+ // Convert to bigint - the value is already in Perbill format but needs to be scaled to 18 decimals
63
+ // The raw value from chain is in parts per billion (9 decimals), we need 18 decimals
64
+ const perbillValue = BigInt(priceValue.toString());
65
+ const scaledPrice = perbillValue * BigInt(Math.pow(10, 9)); // Scale from 9 to 18 decimals
66
+ // Invert the share price: if API returns 0.5601 (shares worth 56% of original),
67
+ // we need 1/0.5601 ≈ 1.785 for stakeToShare conversion
68
+ const oneInPerbill = BigInt(Math.pow(10, 18));
69
+ return (oneInPerbill * oneInPerbill) / scaledPrice;
70
+ }
71
+ catch (error) {
72
+ console.error('Error fetching operator epoch share price:', error);
73
+ throw new Error(`Error fetching share price for operator ${operatorId} at epoch ${domainEpoch}: ${error}`);
74
+ }
75
+ });
76
+ exports.operatorEpochSharePrice = operatorEpochSharePrice;
77
+ /**
78
+ * Calculates the current real-time share price for an operator.
79
+ *
80
+ * This function computes the current share price by considering the operator's
81
+ * total stake, current epoch rewards (after nomination tax), and total shares.
82
+ * The calculation provides an up-to-date price that reflects recent staking
83
+ * activity and rewards distribution.
84
+ *
85
+ * Formula: (currentTotalStake + currentEpochReward * (1 - nominationTax)) / currentTotalShares
86
+ *
87
+ * @param api - The connected API instance
88
+ * @param operatorId - The ID of the operator to calculate price for
89
+ * @returns Promise that resolves to current share price in 18-decimal Perbill format
90
+ * @throws Error if operator not found, domain staking summary unavailable, or calculation fails
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * import { instantSharePrice } from '@autonomys/auto-consensus'
95
+ * import { activate } from '@autonomys/auto-utils'
96
+ *
97
+ * const api = await activate({ networkId: 'gemini-3h' })
98
+ *
99
+ * // Get current share price for operator 1
100
+ * const currentPrice = await instantSharePrice(api, '1')
101
+ * console.log(`Current share price: ${currentPrice}`)
102
+ *
103
+ * // Use for real-time stake/share conversions
104
+ * const stakeAmount = BigInt('1000000000000000000') // 1 AI3
105
+ * const sharesEquivalent = (stakeAmount * BigInt(10 ** 18)) / currentPrice
106
+ * console.log(`${stakeAmount} stake = ${sharesEquivalent} shares`)
107
+ * ```
108
+ */
109
+ const instantSharePrice = (api, operatorId) => __awaiter(void 0, void 0, void 0, function* () {
110
+ try {
111
+ // Get operator details
112
+ const operatorDetails = yield (0, staking_1.operator)(api, operatorId);
113
+ const { currentTotalStake, currentTotalShares, nominationTax, currentDomainId } = operatorDetails;
114
+ // Get domain staking summary to find current epoch rewards
115
+ const domainSummary = yield (0, domain_1.domainStakingSummary)(api, currentDomainId);
116
+ if (!domainSummary) {
117
+ throw new Error(`No staking summary found for domain ${currentDomainId}`);
118
+ }
119
+ // Get current epoch reward for this operator
120
+ const currentEpochReward = domainSummary.currentEpochRewards[(0, parse_1.parseString)(operatorId)];
121
+ const rewardBigInt = currentEpochReward ? BigInt(currentEpochReward) : BigInt(0);
122
+ // Calculate effective stake: currentTotalStake + currentEpochReward * (1 - nominationTax)
123
+ const rewardAfterTax = (rewardBigInt * BigInt(100 - nominationTax)) / BigInt(100);
124
+ const effectiveStake = currentTotalStake + rewardAfterTax;
125
+ // Avoid division by zero
126
+ if (currentTotalShares === BigInt(0)) {
127
+ return BigInt(Math.pow(10, 18)); // Return 1.0 in Perbill format
128
+ }
129
+ // Return price in 18-decimal Perbill format
130
+ return (effectiveStake * BigInt(Math.pow(10, 18))) / currentTotalShares;
131
+ }
132
+ catch (error) {
133
+ console.error('Error computing instant share price:', error);
134
+ throw new Error(`Error computing instant share price for operator ${operatorId}: ${error}`);
135
+ }
136
+ });
137
+ exports.instantSharePrice = instantSharePrice;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Converts operator shares to stake amount using a given share price.
3
+ *
4
+ * This utility function converts a number of operator shares to the equivalent
5
+ * stake amount using the provided share price. The share price should be in
6
+ * 18-decimal Perbill format as returned by the price functions.
7
+ *
8
+ * Formula: shares * price / 10^18
9
+ *
10
+ * @param shares - Number of shares to convert
11
+ * @param price - Share price in 18-decimal Perbill format
12
+ * @returns Equivalent stake amount in smallest token units
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { shareToStake, instantSharePrice } from '@autonomys/auto-consensus'
17
+ * import { activate } from '@autonomys/auto-utils'
18
+ *
19
+ * const api = await activate({ networkId: 'gemini-3h' })
20
+ *
21
+ * // Get current share price
22
+ * const sharePrice = await instantSharePrice(api, '1')
23
+ *
24
+ * // Convert 1000 shares to stake amount
25
+ * const shares = BigInt(1000)
26
+ * const stakeAmount = shareToStake(shares, sharePrice)
27
+ * console.log(`${shares} shares = ${stakeAmount} tokens`)
28
+ * ```
29
+ */
30
+ export declare const shareToStake: (shares: bigint, price: bigint) => bigint;
31
+ /**
32
+ * Converts stake amount to operator shares using a given share price.
33
+ *
34
+ * This utility function converts a stake amount to the equivalent number
35
+ * of operator shares using the provided share price. The share price should
36
+ * be in 18-decimal Perbill format as returned by the price functions.
37
+ *
38
+ * Formula: stake * 10^18 / price
39
+ *
40
+ * @param stake - Stake amount in smallest token units to convert
41
+ * @param price - Share price in 18-decimal Perbill format
42
+ * @returns Equivalent number of shares
43
+ * @throws Error if price is zero (division by zero)
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * import { stakeToShare, instantSharePrice } from '@autonomys/auto-consensus'
48
+ * import { activate } from '@autonomys/auto-utils'
49
+ *
50
+ * const api = await activate({ networkId: 'gemini-3h' })
51
+ *
52
+ * // Get current share price
53
+ * const sharePrice = await instantSharePrice(api, '1')
54
+ *
55
+ * // Convert 1 AI3 to shares
56
+ * const stakeAmount = BigInt('1000000000000000000') // 1 AI3
57
+ * const shares = stakeToShare(stakeAmount, sharePrice)
58
+ * console.log(`${stakeAmount} tokens = ${shares} shares`)
59
+ * ```
60
+ */
61
+ export declare const stakeToShare: (stake: bigint, price: bigint) => bigint;
62
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/position/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,MAAM,EAAE,OAAO,MAAM,KAAG,MAE5D,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,eAAO,MAAM,YAAY,GAAI,OAAO,MAAM,EAAE,OAAO,MAAM,KAAG,MAK3D,CAAA"}
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stakeToShare = exports.shareToStake = void 0;
4
+ /**
5
+ * Converts operator shares to stake amount using a given share price.
6
+ *
7
+ * This utility function converts a number of operator shares to the equivalent
8
+ * stake amount using the provided share price. The share price should be in
9
+ * 18-decimal Perbill format as returned by the price functions.
10
+ *
11
+ * Formula: shares * price / 10^18
12
+ *
13
+ * @param shares - Number of shares to convert
14
+ * @param price - Share price in 18-decimal Perbill format
15
+ * @returns Equivalent stake amount in smallest token units
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { shareToStake, instantSharePrice } from '@autonomys/auto-consensus'
20
+ * import { activate } from '@autonomys/auto-utils'
21
+ *
22
+ * const api = await activate({ networkId: 'gemini-3h' })
23
+ *
24
+ * // Get current share price
25
+ * const sharePrice = await instantSharePrice(api, '1')
26
+ *
27
+ * // Convert 1000 shares to stake amount
28
+ * const shares = BigInt(1000)
29
+ * const stakeAmount = shareToStake(shares, sharePrice)
30
+ * console.log(`${shares} shares = ${stakeAmount} tokens`)
31
+ * ```
32
+ */
33
+ const shareToStake = (shares, price) => {
34
+ return (shares * price) / BigInt(Math.pow(10, 18));
35
+ };
36
+ exports.shareToStake = shareToStake;
37
+ /**
38
+ * Converts stake amount to operator shares using a given share price.
39
+ *
40
+ * This utility function converts a stake amount to the equivalent number
41
+ * of operator shares using the provided share price. The share price should
42
+ * be in 18-decimal Perbill format as returned by the price functions.
43
+ *
44
+ * Formula: stake * 10^18 / price
45
+ *
46
+ * @param stake - Stake amount in smallest token units to convert
47
+ * @param price - Share price in 18-decimal Perbill format
48
+ * @returns Equivalent number of shares
49
+ * @throws Error if price is zero (division by zero)
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * import { stakeToShare, instantSharePrice } from '@autonomys/auto-consensus'
54
+ * import { activate } from '@autonomys/auto-utils'
55
+ *
56
+ * const api = await activate({ networkId: 'gemini-3h' })
57
+ *
58
+ * // Get current share price
59
+ * const sharePrice = await instantSharePrice(api, '1')
60
+ *
61
+ * // Convert 1 AI3 to shares
62
+ * const stakeAmount = BigInt('1000000000000000000') // 1 AI3
63
+ * const shares = stakeToShare(stakeAmount, sharePrice)
64
+ * console.log(`${stakeAmount} tokens = ${shares} shares`)
65
+ * ```
66
+ */
67
+ const stakeToShare = (stake, price) => {
68
+ if (price === BigInt(0)) {
69
+ throw new Error('Price cannot be zero for stake to share conversion');
70
+ }
71
+ return (stake * BigInt(Math.pow(10, 18))) / price;
72
+ };
73
+ exports.stakeToShare = stakeToShare;
@@ -0,0 +1,4 @@
1
+ export * from './position/index';
2
+ export * from './position/price';
3
+ export * from './position/utils';
4
+ //# sourceMappingURL=position.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"position.d.ts","sourceRoot":"","sources":["../src/position.ts"],"names":[],"mappings":"AAEA,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA"}
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ // file: src/position.ts
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ __exportStar(require("./position/index"), exports);
19
+ __exportStar(require("./position/price"), exports);
20
+ __exportStar(require("./position/utils"), exports);
package/dist/remark.d.ts CHANGED
@@ -1,3 +1,32 @@
1
1
  import type { ApiPromise } from '@autonomys/auto-utils';
2
+ /**
3
+ * Creates a remark transaction for adding arbitrary data to the blockchain.
4
+ *
5
+ * Remark transactions allow you to include arbitrary data in the blockchain without
6
+ * affecting the state. This is useful for timestamping data, adding metadata,
7
+ * or including custom information that needs to be permanently recorded.
8
+ *
9
+ * @param api - The connected API promise instance
10
+ * @param remark - The remark data to include in the transaction (as string or bytes)
11
+ * @param withEvent - Whether to emit an event for this remark (default: false)
12
+ * @returns A submittable remark transaction
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { remark } from '@autonomys/auto-consensus'
17
+ * import { activate, signAndSendTx } from '@autonomys/auto-utils'
18
+ *
19
+ * const api = await activate({ networkId: 'gemini-3h' })
20
+ *
21
+ * // Create a simple remark
22
+ * const remarkTx = remark(api, 'Hello, blockchain!')
23
+ *
24
+ * // Create a remark with event
25
+ * const remarkWithEventTx = remark(api, JSON.stringify({ timestamp: Date.now() }), true)
26
+ *
27
+ * // Sign and send the transaction
28
+ * await signAndSendTx(sender, remarkTx)
29
+ * ```
30
+ */
2
31
  export declare const remark: (api: ApiPromise, remark: string, withEvent?: boolean) => import("@autonomys/auto-utils").SubmittableExtrinsic<"promise", import("@autonomys/auto-utils").ISubmittableResult>;
3
32
  //# sourceMappingURL=remark.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"remark.d.ts","sourceRoot":"","sources":["../src/remark.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAEvD,eAAO,MAAM,MAAM,GAAI,KAAK,UAAU,EAAE,QAAQ,MAAM,EAAE,YAAY,OAAO,wHACQ,CAAA"}
1
+ {"version":3,"file":"remark.d.ts","sourceRoot":"","sources":["../src/remark.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAEvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,MAAM,GAAI,KAAK,UAAU,EAAE,QAAQ,MAAM,EAAE,YAAY,OAAO,wHACQ,CAAA"}
package/dist/remark.js CHANGED
@@ -1,5 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.remark = void 0;
4
+ /**
5
+ * Creates a remark transaction for adding arbitrary data to the blockchain.
6
+ *
7
+ * Remark transactions allow you to include arbitrary data in the blockchain without
8
+ * affecting the state. This is useful for timestamping data, adding metadata,
9
+ * or including custom information that needs to be permanently recorded.
10
+ *
11
+ * @param api - The connected API promise instance
12
+ * @param remark - The remark data to include in the transaction (as string or bytes)
13
+ * @param withEvent - Whether to emit an event for this remark (default: false)
14
+ * @returns A submittable remark transaction
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { remark } from '@autonomys/auto-consensus'
19
+ * import { activate, signAndSendTx } from '@autonomys/auto-utils'
20
+ *
21
+ * const api = await activate({ networkId: 'gemini-3h' })
22
+ *
23
+ * // Create a simple remark
24
+ * const remarkTx = remark(api, 'Hello, blockchain!')
25
+ *
26
+ * // Create a remark with event
27
+ * const remarkWithEventTx = remark(api, JSON.stringify({ timestamp: Date.now() }), true)
28
+ *
29
+ * // Sign and send the transaction
30
+ * await signAndSendTx(sender, remarkTx)
31
+ * ```
32
+ */
4
33
  const remark = (api, remark, withEvent) => !withEvent ? api.tx.system.remark(remark) : api.tx.system.remarkWithEvent(remark);
5
34
  exports.remark = remark;