@yellow-org/sdk 1.0.0-alpha.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.
Files changed (72) hide show
  1. package/README.md +984 -0
  2. package/dist/abis/generated.d.ts +4300 -0
  3. package/dist/abis/generated.js +1 -0
  4. package/dist/app/index.d.ts +2 -0
  5. package/dist/app/index.js +2 -0
  6. package/dist/app/packing.d.ts +7 -0
  7. package/dist/app/packing.js +111 -0
  8. package/dist/app/types.d.ts +91 -0
  9. package/dist/app/types.js +42 -0
  10. package/dist/asset_store.d.ts +13 -0
  11. package/dist/asset_store.js +121 -0
  12. package/dist/blockchain/evm/channel_hub_abi.d.ts +4284 -0
  13. package/dist/blockchain/evm/channel_hub_abi.js +5475 -0
  14. package/dist/blockchain/evm/client.d.ts +46 -0
  15. package/dist/blockchain/evm/client.js +428 -0
  16. package/dist/blockchain/evm/erc20.d.ts +13 -0
  17. package/dist/blockchain/evm/erc20.js +54 -0
  18. package/dist/blockchain/evm/erc20_abi.d.ts +144 -0
  19. package/dist/blockchain/evm/erc20_abi.js +96 -0
  20. package/dist/blockchain/evm/index.d.ts +6 -0
  21. package/dist/blockchain/evm/index.js +6 -0
  22. package/dist/blockchain/evm/interface.d.ts +10 -0
  23. package/dist/blockchain/evm/interface.js +1 -0
  24. package/dist/blockchain/evm/types.d.ts +27 -0
  25. package/dist/blockchain/evm/types.js +1 -0
  26. package/dist/blockchain/evm/utils.d.ts +9 -0
  27. package/dist/blockchain/evm/utils.js +129 -0
  28. package/dist/blockchain/index.d.ts +1 -0
  29. package/dist/blockchain/index.js +1 -0
  30. package/dist/client.d.ts +99 -0
  31. package/dist/client.js +720 -0
  32. package/dist/config.d.ts +12 -0
  33. package/dist/config.js +28 -0
  34. package/dist/core/event.d.ts +29 -0
  35. package/dist/core/event.js +1 -0
  36. package/dist/core/index.d.ts +6 -0
  37. package/dist/core/index.js +6 -0
  38. package/dist/core/interface.d.ts +53 -0
  39. package/dist/core/interface.js +1 -0
  40. package/dist/core/state.d.ts +21 -0
  41. package/dist/core/state.js +267 -0
  42. package/dist/core/state_packer.d.ts +13 -0
  43. package/dist/core/state_packer.js +98 -0
  44. package/dist/core/types.d.ts +203 -0
  45. package/dist/core/types.js +220 -0
  46. package/dist/core/utils.d.ts +16 -0
  47. package/dist/core/utils.js +181 -0
  48. package/dist/index.d.ts +9 -0
  49. package/dist/index.js +9 -0
  50. package/dist/rpc/api.d.ts +181 -0
  51. package/dist/rpc/api.js +1 -0
  52. package/dist/rpc/client.d.ts +36 -0
  53. package/dist/rpc/client.js +102 -0
  54. package/dist/rpc/dialer.d.ts +30 -0
  55. package/dist/rpc/dialer.js +146 -0
  56. package/dist/rpc/error.d.ts +18 -0
  57. package/dist/rpc/error.js +27 -0
  58. package/dist/rpc/index.d.ts +7 -0
  59. package/dist/rpc/index.js +7 -0
  60. package/dist/rpc/message.d.ts +25 -0
  61. package/dist/rpc/message.js +102 -0
  62. package/dist/rpc/methods.d.ts +30 -0
  63. package/dist/rpc/methods.js +27 -0
  64. package/dist/rpc/types.d.ts +101 -0
  65. package/dist/rpc/types.js +1 -0
  66. package/dist/signers.d.ts +48 -0
  67. package/dist/signers.js +96 -0
  68. package/dist/utils/sign.d.ts +2 -0
  69. package/dist/utils/sign.js +8 -0
  70. package/dist/utils.d.ts +42 -0
  71. package/dist/utils.js +226 -0
  72. package/package.json +89 -0
@@ -0,0 +1,203 @@
1
+ import { Address, Hex } from 'viem';
2
+ import Decimal from 'decimal.js';
3
+ export declare enum ChannelType {
4
+ Home = 1,
5
+ Escrow = 2
6
+ }
7
+ export declare enum ChannelParticipant {
8
+ User = 0,
9
+ Node = 1
10
+ }
11
+ export declare enum ChannelSignerType {
12
+ Default = 0,
13
+ SessionKey = 1
14
+ }
15
+ export declare enum ChannelStatus {
16
+ Void = 0,
17
+ Open = 1,
18
+ Challenged = 2,
19
+ Closed = 3
20
+ }
21
+ export declare enum TransitionType {
22
+ Void = 0,
23
+ Acknowledgement = 1,
24
+ HomeDeposit = 10,
25
+ HomeWithdrawal = 11,
26
+ EscrowDeposit = 20,
27
+ EscrowWithdraw = 21,
28
+ TransferSend = 30,
29
+ TransferReceive = 31,
30
+ Commit = 40,
31
+ Release = 41,
32
+ Migrate = 100,
33
+ EscrowLock = 110,
34
+ MutualLock = 120,
35
+ Finalize = 200
36
+ }
37
+ export declare enum TransactionType {
38
+ HomeDeposit = 10,
39
+ HomeWithdrawal = 11,
40
+ EscrowDeposit = 20,
41
+ EscrowWithdraw = 21,
42
+ Transfer = 30,
43
+ Commit = 40,
44
+ Release = 41,
45
+ Rebalance = 42,
46
+ Migrate = 100,
47
+ EscrowLock = 110,
48
+ MutualLock = 120,
49
+ Finalize = 200
50
+ }
51
+ export declare const INTENT_OPERATE = 0;
52
+ export declare const INTENT_CLOSE = 1;
53
+ export declare const INTENT_DEPOSIT = 2;
54
+ export declare const INTENT_WITHDRAW = 3;
55
+ export declare const INTENT_INITIATE_ESCROW_DEPOSIT = 4;
56
+ export declare const INTENT_FINALIZE_ESCROW_DEPOSIT = 5;
57
+ export declare const INTENT_INITIATE_ESCROW_WITHDRAWAL = 6;
58
+ export declare const INTENT_FINALIZE_ESCROW_WITHDRAWAL = 7;
59
+ export declare const INTENT_INITIATE_MIGRATION = 8;
60
+ export declare const INTENT_FINALIZE_MIGRATION = 9;
61
+ export interface ChannelDefinition {
62
+ nonce: bigint;
63
+ challenge: number;
64
+ approvedSigValidators: string;
65
+ }
66
+ export interface Channel {
67
+ channelId: string;
68
+ userWallet: Address;
69
+ asset: string;
70
+ type: ChannelType;
71
+ blockchainId: bigint;
72
+ tokenAddress: Address;
73
+ challengeDuration: number;
74
+ challengeExpiresAt?: Date;
75
+ nonce: bigint;
76
+ approvedSigValidators: string;
77
+ status: ChannelStatus;
78
+ stateVersion: bigint;
79
+ }
80
+ export interface Ledger {
81
+ tokenAddress: Address;
82
+ blockchainId: bigint;
83
+ userBalance: Decimal;
84
+ userNetFlow: Decimal;
85
+ nodeBalance: Decimal;
86
+ nodeNetFlow: Decimal;
87
+ }
88
+ export interface Transition {
89
+ type: TransitionType;
90
+ txId: string;
91
+ accountId?: string;
92
+ amount: Decimal;
93
+ }
94
+ export interface State {
95
+ id: string;
96
+ transition: Transition;
97
+ asset: string;
98
+ userWallet: Address;
99
+ epoch: bigint;
100
+ version: bigint;
101
+ homeChannelId?: string;
102
+ escrowChannelId?: string;
103
+ homeLedger: Ledger;
104
+ escrowLedger?: Ledger;
105
+ userSig?: Hex;
106
+ nodeSig?: Hex;
107
+ }
108
+ export interface Transaction {
109
+ id: string;
110
+ asset: string;
111
+ txType: TransactionType;
112
+ fromAccount: Address;
113
+ toAccount: Address;
114
+ senderNewStateId?: string;
115
+ receiverNewStateId?: string;
116
+ amount: Decimal;
117
+ createdAt: Date;
118
+ }
119
+ export interface Blockchain {
120
+ name: string;
121
+ id: bigint;
122
+ channelHubAddress: Address;
123
+ blockStep: bigint;
124
+ }
125
+ export interface Token {
126
+ name: string;
127
+ symbol: string;
128
+ address: Address;
129
+ blockchainId: bigint;
130
+ decimals: number;
131
+ }
132
+ export interface Asset {
133
+ name: string;
134
+ decimals: number;
135
+ symbol: string;
136
+ suggestedBlockchainId: bigint;
137
+ tokens: Token[];
138
+ }
139
+ export interface AssetAllowance {
140
+ asset: string;
141
+ allowance: Decimal;
142
+ used: Decimal;
143
+ }
144
+ export interface SessionKey {
145
+ id: bigint;
146
+ sessionKey: string;
147
+ application: string;
148
+ allowances: AssetAllowance[];
149
+ scope?: string;
150
+ expiresAt: string;
151
+ createdAt: string;
152
+ }
153
+ export interface BalanceEntry {
154
+ asset: string;
155
+ balance: Decimal;
156
+ }
157
+ export interface PaginationParams {
158
+ offset?: number;
159
+ limit?: number;
160
+ }
161
+ export interface PaginationMetadata {
162
+ page: number;
163
+ perPage: number;
164
+ totalCount: number;
165
+ pageCount: number;
166
+ }
167
+ export interface NodeConfig {
168
+ nodeAddress: Address;
169
+ nodeVersion: string;
170
+ supportedSigValidators: number[];
171
+ blockchains: Blockchain[];
172
+ }
173
+ export interface HomeChannelDataResponse {
174
+ definition: ChannelDefinition;
175
+ node: Address;
176
+ lastState: State;
177
+ challengeExpiry: bigint;
178
+ }
179
+ export interface EscrowDepositDataResponse {
180
+ escrowChannelId: string;
181
+ node: Address;
182
+ lastState: State;
183
+ unlockExpiry: bigint;
184
+ challengeExpiry: bigint;
185
+ }
186
+ export interface EscrowWithdrawalDataResponse {
187
+ escrowChannelId: string;
188
+ node: Address;
189
+ lastState: State;
190
+ }
191
+ export declare function newChannel(channelId: string, userWallet: Address, asset: string, type: ChannelType, blockchainId: bigint, tokenAddress: Address, nonce: bigint, challenge: number, approvedSigValidators?: string): Channel;
192
+ export declare function newVoidState(asset: string, userWallet: Address): State;
193
+ export declare function newTransition(type: TransitionType, txId: string, accountId: string, amount: Decimal): Transition;
194
+ export declare function newTransaction(id: string, asset: string, txType: TransactionType, fromAccount: Address, toAccount: Address, amount: Decimal): Transaction;
195
+ export declare function transitionToString(type: TransitionType): string;
196
+ export declare function transitionRequiresOpenChannel(type: TransitionType): boolean;
197
+ export declare function transitionsEqual(a: Transition, b: Transition): string | null;
198
+ export declare function ledgerEqual(a: Ledger, b: Ledger): string | null;
199
+ export declare function validateLedger(ledger: Ledger): void;
200
+ export declare function getOffsetAndLimit(params: PaginationParams | undefined, defaultLimit: number, maxLimit: number): {
201
+ offset: number;
202
+ limit: number;
203
+ };
@@ -0,0 +1,220 @@
1
+ import Decimal from 'decimal.js';
2
+ export var ChannelType;
3
+ (function (ChannelType) {
4
+ ChannelType[ChannelType["Home"] = 1] = "Home";
5
+ ChannelType[ChannelType["Escrow"] = 2] = "Escrow";
6
+ })(ChannelType || (ChannelType = {}));
7
+ export var ChannelParticipant;
8
+ (function (ChannelParticipant) {
9
+ ChannelParticipant[ChannelParticipant["User"] = 0] = "User";
10
+ ChannelParticipant[ChannelParticipant["Node"] = 1] = "Node";
11
+ })(ChannelParticipant || (ChannelParticipant = {}));
12
+ export var ChannelSignerType;
13
+ (function (ChannelSignerType) {
14
+ ChannelSignerType[ChannelSignerType["Default"] = 0] = "Default";
15
+ ChannelSignerType[ChannelSignerType["SessionKey"] = 1] = "SessionKey";
16
+ })(ChannelSignerType || (ChannelSignerType = {}));
17
+ export var ChannelStatus;
18
+ (function (ChannelStatus) {
19
+ ChannelStatus[ChannelStatus["Void"] = 0] = "Void";
20
+ ChannelStatus[ChannelStatus["Open"] = 1] = "Open";
21
+ ChannelStatus[ChannelStatus["Challenged"] = 2] = "Challenged";
22
+ ChannelStatus[ChannelStatus["Closed"] = 3] = "Closed";
23
+ })(ChannelStatus || (ChannelStatus = {}));
24
+ export var TransitionType;
25
+ (function (TransitionType) {
26
+ TransitionType[TransitionType["Void"] = 0] = "Void";
27
+ TransitionType[TransitionType["Acknowledgement"] = 1] = "Acknowledgement";
28
+ TransitionType[TransitionType["HomeDeposit"] = 10] = "HomeDeposit";
29
+ TransitionType[TransitionType["HomeWithdrawal"] = 11] = "HomeWithdrawal";
30
+ TransitionType[TransitionType["EscrowDeposit"] = 20] = "EscrowDeposit";
31
+ TransitionType[TransitionType["EscrowWithdraw"] = 21] = "EscrowWithdraw";
32
+ TransitionType[TransitionType["TransferSend"] = 30] = "TransferSend";
33
+ TransitionType[TransitionType["TransferReceive"] = 31] = "TransferReceive";
34
+ TransitionType[TransitionType["Commit"] = 40] = "Commit";
35
+ TransitionType[TransitionType["Release"] = 41] = "Release";
36
+ TransitionType[TransitionType["Migrate"] = 100] = "Migrate";
37
+ TransitionType[TransitionType["EscrowLock"] = 110] = "EscrowLock";
38
+ TransitionType[TransitionType["MutualLock"] = 120] = "MutualLock";
39
+ TransitionType[TransitionType["Finalize"] = 200] = "Finalize";
40
+ })(TransitionType || (TransitionType = {}));
41
+ export var TransactionType;
42
+ (function (TransactionType) {
43
+ TransactionType[TransactionType["HomeDeposit"] = 10] = "HomeDeposit";
44
+ TransactionType[TransactionType["HomeWithdrawal"] = 11] = "HomeWithdrawal";
45
+ TransactionType[TransactionType["EscrowDeposit"] = 20] = "EscrowDeposit";
46
+ TransactionType[TransactionType["EscrowWithdraw"] = 21] = "EscrowWithdraw";
47
+ TransactionType[TransactionType["Transfer"] = 30] = "Transfer";
48
+ TransactionType[TransactionType["Commit"] = 40] = "Commit";
49
+ TransactionType[TransactionType["Release"] = 41] = "Release";
50
+ TransactionType[TransactionType["Rebalance"] = 42] = "Rebalance";
51
+ TransactionType[TransactionType["Migrate"] = 100] = "Migrate";
52
+ TransactionType[TransactionType["EscrowLock"] = 110] = "EscrowLock";
53
+ TransactionType[TransactionType["MutualLock"] = 120] = "MutualLock";
54
+ TransactionType[TransactionType["Finalize"] = 200] = "Finalize";
55
+ })(TransactionType || (TransactionType = {}));
56
+ export const INTENT_OPERATE = 0;
57
+ export const INTENT_CLOSE = 1;
58
+ export const INTENT_DEPOSIT = 2;
59
+ export const INTENT_WITHDRAW = 3;
60
+ export const INTENT_INITIATE_ESCROW_DEPOSIT = 4;
61
+ export const INTENT_FINALIZE_ESCROW_DEPOSIT = 5;
62
+ export const INTENT_INITIATE_ESCROW_WITHDRAWAL = 6;
63
+ export const INTENT_FINALIZE_ESCROW_WITHDRAWAL = 7;
64
+ export const INTENT_INITIATE_MIGRATION = 8;
65
+ export const INTENT_FINALIZE_MIGRATION = 9;
66
+ export function newChannel(channelId, userWallet, asset, type, blockchainId, tokenAddress, nonce, challenge, approvedSigValidators = '0x00') {
67
+ return {
68
+ channelId,
69
+ userWallet,
70
+ asset,
71
+ type,
72
+ blockchainId,
73
+ tokenAddress,
74
+ nonce,
75
+ challengeDuration: challenge,
76
+ approvedSigValidators,
77
+ status: ChannelStatus.Void,
78
+ stateVersion: 0n,
79
+ };
80
+ }
81
+ export function newVoidState(asset, userWallet) {
82
+ return {
83
+ id: '',
84
+ transition: { type: TransitionType.Void, txId: '', amount: new Decimal(0) },
85
+ asset,
86
+ userWallet,
87
+ epoch: 0n,
88
+ version: 0n,
89
+ homeLedger: {
90
+ tokenAddress: '0x0',
91
+ blockchainId: 0n,
92
+ userBalance: new Decimal(0),
93
+ userNetFlow: new Decimal(0),
94
+ nodeBalance: new Decimal(0),
95
+ nodeNetFlow: new Decimal(0),
96
+ },
97
+ };
98
+ }
99
+ export function newTransition(type, txId, accountId, amount) {
100
+ return {
101
+ type,
102
+ txId,
103
+ accountId,
104
+ amount,
105
+ };
106
+ }
107
+ export function newTransaction(id, asset, txType, fromAccount, toAccount, amount) {
108
+ return {
109
+ id,
110
+ asset,
111
+ txType,
112
+ fromAccount,
113
+ toAccount,
114
+ amount,
115
+ createdAt: new Date(),
116
+ };
117
+ }
118
+ export function transitionToString(type) {
119
+ switch (type) {
120
+ case TransitionType.Void:
121
+ return 'Void';
122
+ case TransitionType.Acknowledgement:
123
+ return 'Acknowledgement';
124
+ case TransitionType.HomeDeposit:
125
+ return 'HomeDeposit';
126
+ case TransitionType.HomeWithdrawal:
127
+ return 'HomeWithdrawal';
128
+ case TransitionType.EscrowDeposit:
129
+ return 'EscrowDeposit';
130
+ case TransitionType.EscrowWithdraw:
131
+ return 'EscrowWithdraw';
132
+ case TransitionType.TransferSend:
133
+ return 'TransferSend';
134
+ case TransitionType.TransferReceive:
135
+ return 'TransferReceive';
136
+ case TransitionType.Commit:
137
+ return 'Commit';
138
+ case TransitionType.Release:
139
+ return 'Release';
140
+ case TransitionType.Migrate:
141
+ return 'Migrate';
142
+ case TransitionType.EscrowLock:
143
+ return 'EscrowLock';
144
+ case TransitionType.MutualLock:
145
+ return 'MutualLock';
146
+ case TransitionType.Finalize:
147
+ return 'Finalize';
148
+ default:
149
+ return 'Unknown';
150
+ }
151
+ }
152
+ export function transitionRequiresOpenChannel(type) {
153
+ return type !== TransitionType.TransferReceive && type !== TransitionType.Release;
154
+ }
155
+ export function transitionsEqual(a, b) {
156
+ if (a.type !== b.type) {
157
+ return `type mismatch: expected=${a.type}, proposed=${b.type}`;
158
+ }
159
+ if (a.txId !== b.txId) {
160
+ return `tx ID mismatch: expected=${a.txId}, proposed=${b.txId}`;
161
+ }
162
+ if (a.accountId !== b.accountId) {
163
+ return `account ID mismatch: expected=${a.accountId}, proposed=${b.accountId}`;
164
+ }
165
+ if (!a.amount.equals(b.amount)) {
166
+ return `amount mismatch: expected=${a.amount.toString()}, proposed=${b.amount.toString()}`;
167
+ }
168
+ return null;
169
+ }
170
+ export function ledgerEqual(a, b) {
171
+ if (a.tokenAddress.toLowerCase() !== b.tokenAddress.toLowerCase()) {
172
+ return `token address mismatch: expected=${a.tokenAddress}, proposed=${b.tokenAddress}`;
173
+ }
174
+ if (a.blockchainId !== b.blockchainId) {
175
+ return `blockchain ID mismatch: expected=${a.blockchainId}, proposed=${b.blockchainId}`;
176
+ }
177
+ if (!a.userBalance.equals(b.userBalance)) {
178
+ return `user balance mismatch: expected=${a.userBalance.toString()}, proposed=${b.userBalance.toString()}`;
179
+ }
180
+ if (!a.userNetFlow.equals(b.userNetFlow)) {
181
+ return `user net flow mismatch: expected=${a.userNetFlow.toString()}, proposed=${b.userNetFlow.toString()}`;
182
+ }
183
+ if (!a.nodeBalance.equals(b.nodeBalance)) {
184
+ return `node balance mismatch: expected=${a.nodeBalance.toString()}, proposed=${b.nodeBalance.toString()}`;
185
+ }
186
+ if (!a.nodeNetFlow.equals(b.nodeNetFlow)) {
187
+ return `node net flow mismatch: expected=${a.nodeNetFlow.toString()}, proposed=${b.nodeNetFlow.toString()}`;
188
+ }
189
+ return null;
190
+ }
191
+ export function validateLedger(ledger) {
192
+ if (!ledger.tokenAddress || ledger.tokenAddress === '0x0') {
193
+ throw new Error('invalid token address');
194
+ }
195
+ if (ledger.blockchainId === 0n) {
196
+ throw new Error('invalid blockchain ID');
197
+ }
198
+ if (ledger.userBalance.isNegative()) {
199
+ throw new Error('user balance cannot be negative');
200
+ }
201
+ if (ledger.nodeBalance.isNegative()) {
202
+ throw new Error('node balance cannot be negative');
203
+ }
204
+ const sumBalances = ledger.userBalance.add(ledger.nodeBalance);
205
+ const sumNetFlows = ledger.userNetFlow.add(ledger.nodeNetFlow);
206
+ if (!sumBalances.equals(sumNetFlows)) {
207
+ throw new Error(`ledger balances do not match net flows: balances=${sumBalances.toString()}, net_flows=${sumNetFlows.toString()}`);
208
+ }
209
+ }
210
+ export function getOffsetAndLimit(params, defaultLimit, maxLimit) {
211
+ if (!params) {
212
+ return { offset: 0, limit: defaultLimit };
213
+ }
214
+ const offset = params.offset ?? 0;
215
+ let limit = params.limit ?? defaultLimit;
216
+ if (limit > maxLimit) {
217
+ limit = maxLimit;
218
+ }
219
+ return { offset, limit };
220
+ }
@@ -0,0 +1,16 @@
1
+ import { Address } from 'viem';
2
+ import Decimal from 'decimal.js';
3
+ import { Transition } from './types';
4
+ export declare const CHANNEL_HUB_VERSION = 1;
5
+ export declare function transitionToIntent(transition: Transition): number;
6
+ export declare function validateDecimalPrecision(amount: Decimal, maxDecimals: number): void;
7
+ export declare function decimalToBigInt(amount: Decimal, decimals: number): bigint;
8
+ export declare function getHomeChannelId(node: Address, user: Address, asset: string, nonce: bigint, challengeDuration: number, approvedSigValidators?: string): string;
9
+ export declare function getEscrowChannelId(homeChannelId: string, stateVersion: bigint): string;
10
+ export declare function getStateId(userWallet: Address, asset: string, epoch: bigint, version: bigint): string;
11
+ export declare function getStateTransitionHash(transition: Transition): string;
12
+ export declare function getSenderTransactionId(toAccount: string, senderNewStateId: string): string;
13
+ export declare function getReceiverTransactionId(fromAccount: string, receiverNewStateId: string): string;
14
+ export declare function generateChannelMetadata(asset: string): `0x${string}`;
15
+ export declare function getChannelSessionKeyAuthMetadataHashV1(version: bigint, assets: string[], expiresAt: bigint): `0x${string}`;
16
+ export declare function packChannelKeyStateV1(sessionKey: Address, metadataHash: `0x${string}`): `0x${string}`;
@@ -0,0 +1,181 @@
1
+ import { encodeAbiParameters, keccak256, toHex, pad, slice } from 'viem';
2
+ import Decimal from 'decimal.js';
3
+ import { TransitionType, INTENT_OPERATE, INTENT_CLOSE, INTENT_DEPOSIT, INTENT_WITHDRAW, INTENT_INITIATE_ESCROW_DEPOSIT, INTENT_FINALIZE_ESCROW_DEPOSIT, INTENT_INITIATE_ESCROW_WITHDRAWAL, INTENT_FINALIZE_ESCROW_WITHDRAWAL, INTENT_INITIATE_MIGRATION, } from './types';
4
+ Decimal.set({ precision: 50 });
5
+ export const CHANNEL_HUB_VERSION = 1;
6
+ export function transitionToIntent(transition) {
7
+ switch (transition.type) {
8
+ case TransitionType.Void:
9
+ case TransitionType.TransferSend:
10
+ case TransitionType.TransferReceive:
11
+ case TransitionType.Commit:
12
+ case TransitionType.Release:
13
+ return INTENT_OPERATE;
14
+ case TransitionType.Finalize:
15
+ return INTENT_CLOSE;
16
+ case TransitionType.HomeDeposit:
17
+ return INTENT_DEPOSIT;
18
+ case TransitionType.HomeWithdrawal:
19
+ return INTENT_WITHDRAW;
20
+ case TransitionType.MutualLock:
21
+ return INTENT_INITIATE_ESCROW_DEPOSIT;
22
+ case TransitionType.EscrowDeposit:
23
+ return INTENT_FINALIZE_ESCROW_DEPOSIT;
24
+ case TransitionType.EscrowLock:
25
+ return INTENT_INITIATE_ESCROW_WITHDRAWAL;
26
+ case TransitionType.EscrowWithdraw:
27
+ return INTENT_FINALIZE_ESCROW_WITHDRAWAL;
28
+ case TransitionType.Migrate:
29
+ return INTENT_INITIATE_MIGRATION;
30
+ default:
31
+ return INTENT_OPERATE;
32
+ }
33
+ }
34
+ export function validateDecimalPrecision(amount, maxDecimals) {
35
+ const exponent = amount.decimalPlaces();
36
+ if (exponent > maxDecimals) {
37
+ throw new Error(`amount exceeds maximum decimal precision: max ${maxDecimals} decimals allowed, got ${exponent}`);
38
+ }
39
+ }
40
+ export function decimalToBigInt(amount, decimals) {
41
+ const multiplier = new Decimal(10).pow(decimals);
42
+ const scaled = amount.mul(multiplier);
43
+ if (!scaled.isInteger()) {
44
+ throw new Error(`amount ${amount.toString()} exceeds maximum decimal precision: max ${decimals} decimals allowed`);
45
+ }
46
+ return BigInt(scaled.toFixed(0));
47
+ }
48
+ export function getHomeChannelId(node, user, asset, nonce, challengeDuration, approvedSigValidators = '0x00') {
49
+ const metadata = generateChannelMetadata(asset);
50
+ const validatorsBigInt = BigInt(approvedSigValidators || '0x00');
51
+ const packed = encodeAbiParameters([
52
+ {
53
+ name: 'channelDefinition',
54
+ type: 'tuple',
55
+ components: [
56
+ { name: 'challengeDuration', type: 'uint32' },
57
+ { name: 'user', type: 'address' },
58
+ { name: 'node', type: 'address' },
59
+ { name: 'nonce', type: 'uint64' },
60
+ { name: 'approvedSignatureValidators', type: 'uint256' },
61
+ { name: 'metadata', type: 'bytes32' },
62
+ ],
63
+ },
64
+ ], [
65
+ {
66
+ challengeDuration: challengeDuration,
67
+ user: user,
68
+ node: node,
69
+ nonce: nonce,
70
+ approvedSignatureValidators: validatorsBigInt,
71
+ metadata: metadata,
72
+ },
73
+ ]);
74
+ const baseId = keccak256(packed);
75
+ const versionHex = CHANNEL_HUB_VERSION.toString(16).padStart(2, '0');
76
+ return `0x${versionHex}${baseId.slice(4)}`;
77
+ }
78
+ export function getEscrowChannelId(homeChannelId, stateVersion) {
79
+ const packed = encodeAbiParameters([{ type: 'bytes32' }, { type: 'uint64' }], [homeChannelId, stateVersion]);
80
+ return keccak256(packed);
81
+ }
82
+ export function getStateId(userWallet, asset, epoch, version) {
83
+ const packed = encodeAbiParameters([{ type: 'address' }, { type: 'string' }, { type: 'uint256' }, { type: 'uint256' }], [userWallet, asset, epoch, version]);
84
+ return keccak256(packed);
85
+ }
86
+ export function getStateTransitionHash(transition) {
87
+ const contractTransition = {
88
+ type: transition.type,
89
+ txId: hexToBytes32(transition.txId),
90
+ accountId: parseAccountIdToBytes32(transition.accountId),
91
+ amount: transition.amount.toString(),
92
+ };
93
+ const packed = encodeAbiParameters([
94
+ {
95
+ type: 'tuple',
96
+ components: [
97
+ { name: 'type', type: 'uint8' },
98
+ { name: 'txId', type: 'bytes32' },
99
+ { name: 'accountId', type: 'bytes32' },
100
+ { name: 'amount', type: 'string' },
101
+ ],
102
+ },
103
+ ], [contractTransition]);
104
+ return keccak256(packed);
105
+ }
106
+ export function getSenderTransactionId(toAccount, senderNewStateId) {
107
+ return getTransactionId(toAccount, senderNewStateId);
108
+ }
109
+ export function getReceiverTransactionId(fromAccount, receiverNewStateId) {
110
+ return getTransactionId(fromAccount, receiverNewStateId);
111
+ }
112
+ function getTransactionId(account, newStateId) {
113
+ const packed = encodeAbiParameters([{ type: 'string' }, { type: 'bytes32' }], [account, newStateId]);
114
+ return keccak256(packed);
115
+ }
116
+ export function generateChannelMetadata(asset) {
117
+ const assetHash = keccak256(toHex(asset));
118
+ const first8Bytes = slice(assetHash, 0, 8);
119
+ const metadata = pad(first8Bytes, { dir: 'right', size: 32 });
120
+ return metadata;
121
+ }
122
+ function hexToBytes32(hexStr) {
123
+ let cleaned = hexStr.startsWith('0x') ? hexStr.slice(2) : hexStr;
124
+ if (cleaned.length % 2 === 1) {
125
+ cleaned = '0' + cleaned;
126
+ }
127
+ const bytes = [];
128
+ for (let i = 0; i < cleaned.length; i += 2) {
129
+ const hexPair = cleaned.slice(i, i + 2);
130
+ if (!/^[0-9a-fA-F]{2}$/.test(hexPair)) {
131
+ break;
132
+ }
133
+ bytes.push(parseInt(hexPair, 16));
134
+ }
135
+ const hexResult = bytes.map(b => b.toString(16).padStart(2, '0')).join('');
136
+ return pad(`0x${hexResult}`, { dir: 'left', size: 32 });
137
+ }
138
+ function parseAccountIdToBytes32(accountId) {
139
+ if (!accountId || accountId === '') {
140
+ return '0x0000000000000000000000000000000000000000000000000000000000000000';
141
+ }
142
+ let cleaned = accountId.startsWith('0x') ? accountId.slice(2) : accountId;
143
+ const hexLength = cleaned.length;
144
+ if (hexLength === 40 || hexLength === 64) {
145
+ if (/^[0-9a-fA-F]+$/.test(cleaned)) {
146
+ if (hexLength === 40) {
147
+ return pad((`0x${cleaned}`), { size: 32 });
148
+ }
149
+ else {
150
+ return `0x${cleaned}`;
151
+ }
152
+ }
153
+ }
154
+ if (cleaned.length % 2 === 1) {
155
+ cleaned = '0' + cleaned;
156
+ }
157
+ const bytes = [];
158
+ for (let i = 0; i < cleaned.length; i += 2) {
159
+ const hexPair = cleaned.slice(i, i + 2);
160
+ if (!/^[0-9a-fA-F]{2}$/.test(hexPair)) {
161
+ break;
162
+ }
163
+ bytes.push(parseInt(hexPair, 16));
164
+ }
165
+ const hexResult = bytes.map(b => b.toString(16).padStart(2, '0')).join('');
166
+ return pad(`0x${hexResult}`, { dir: 'left', size: 32 });
167
+ }
168
+ export function getChannelSessionKeyAuthMetadataHashV1(version, assets, expiresAt) {
169
+ const packed = encodeAbiParameters([
170
+ { type: 'uint64' },
171
+ { type: 'string[]' },
172
+ { type: 'uint64' },
173
+ ], [version, assets, expiresAt]);
174
+ return keccak256(packed);
175
+ }
176
+ export function packChannelKeyStateV1(sessionKey, metadataHash) {
177
+ return encodeAbiParameters([
178
+ { type: 'address' },
179
+ { type: 'bytes32' },
180
+ ], [sessionKey, metadataHash]);
181
+ }
@@ -0,0 +1,9 @@
1
+ export { Client, DEFAULT_CHALLENGE_PERIOD, type StateSigner, type TransactionSigner } from './client';
2
+ export { EthereumMsgSigner, EthereumRawSigner, ChannelDefaultSigner, ChannelSessionKeyStateSigner, createSigners, } from './signers';
3
+ export { type Config, DefaultConfig, type Option, withHandshakeTimeout, withErrorHandler, withBlockchainRPC } from './config';
4
+ export { ClientAssetStore } from './asset_store';
5
+ export * from './utils';
6
+ export * from './core';
7
+ export * from './app';
8
+ export * from './blockchain';
9
+ export * from './rpc';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { Client, DEFAULT_CHALLENGE_PERIOD } from './client';
2
+ export { EthereumMsgSigner, EthereumRawSigner, ChannelDefaultSigner, ChannelSessionKeyStateSigner, createSigners, } from './signers';
3
+ export { DefaultConfig, withHandshakeTimeout, withErrorHandler, withBlockchainRPC } from './config';
4
+ export { ClientAssetStore } from './asset_store';
5
+ export * from './utils';
6
+ export * from './core';
7
+ export * from './app';
8
+ export * from './blockchain';
9
+ export * from './rpc';