@arbiwallet/contracts 1.0.8 → 1.0.10
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/gen/custody.ts +169 -0
- package/gen/ledger.ts +370 -0
- package/gen/user.ts +57 -0
- package/gen/webhook.ts +65 -0
- package/package.json +1 -1
- package/proto/custody.proto +81 -0
- package/proto/ledger.proto +205 -0
- package/proto/user.proto +25 -0
- package/proto/webhook.proto +23 -0
package/gen/custody.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
|
2
|
+
// versions:
|
|
3
|
+
// protoc-gen-ts_proto v2.11.4
|
|
4
|
+
// protoc v7.34.0
|
|
5
|
+
// source: custody.proto
|
|
6
|
+
|
|
7
|
+
/* eslint-disable */
|
|
8
|
+
import { GrpcMethod, GrpcStreamMethod } from "@nestjs/microservices";
|
|
9
|
+
import { Observable } from "rxjs";
|
|
10
|
+
|
|
11
|
+
export const protobufPackage = "custody.v1";
|
|
12
|
+
|
|
13
|
+
/** Статус отслеживания депозита в рамках ответа GetDepositStatus (не полный on-chain индекс). */
|
|
14
|
+
export enum DepositTrackingStatus {
|
|
15
|
+
DEPOSIT_TRACKING_STATUS_UNSPECIFIED = 0,
|
|
16
|
+
/** DEPOSIT_TRACKING_STATUS_UNKNOWN - Адрес не найден / нет данных. */
|
|
17
|
+
DEPOSIT_TRACKING_STATUS_UNKNOWN = 1,
|
|
18
|
+
/** DEPOSIT_TRACKING_STATUS_PENDING - Адрес выдан, ожидание/не подтверждено в этом сервисе. */
|
|
19
|
+
DEPOSIT_TRACKING_STATUS_PENDING = 2,
|
|
20
|
+
/** DEPOSIT_TRACKING_STATUS_CONFIRMED - Подтверждено (если сервис отдаёт такой уровень детализации). */
|
|
21
|
+
DEPOSIT_TRACKING_STATUS_CONFIRMED = 3,
|
|
22
|
+
DEPOSIT_TRACKING_STATUS_FAILED = 4,
|
|
23
|
+
UNRECOGNIZED = -1,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface GetDepositAddressRequest {
|
|
27
|
+
/** Идентификатор пользователя (на wire при longs:String — строка). */
|
|
28
|
+
userId: number;
|
|
29
|
+
/** TRON | BSC и т.д. */
|
|
30
|
+
network: string;
|
|
31
|
+
/** По умолчанию USDT. */
|
|
32
|
+
asset: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface GetDepositAddressResponse {
|
|
36
|
+
userId: number;
|
|
37
|
+
network: string;
|
|
38
|
+
asset: string;
|
|
39
|
+
/** Депозитный адрес для пополнения. */
|
|
40
|
+
address: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CreateWithdrawalRequest {
|
|
44
|
+
/** Уникальный id заявки со стороны продукта (идемпотентность на уровне mpc/БД). */
|
|
45
|
+
withdrawRequestId: string;
|
|
46
|
+
userId: number;
|
|
47
|
+
network: string;
|
|
48
|
+
/** Сумма в decimal-строке. */
|
|
49
|
+
amount: string;
|
|
50
|
+
/** Адрес получателя в целевой сети. */
|
|
51
|
+
toAddress: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface CreateWithdrawalResponse {
|
|
55
|
+
withdrawRequestId: string;
|
|
56
|
+
/** Id трансфера в BitGo (исторически назывался fireblocks_tx_id). */
|
|
57
|
+
custodyTransferId: string;
|
|
58
|
+
/** Унифицированный статус вывода для внутренней логики (CREATED, BROADCASTING, …). */
|
|
59
|
+
mappedStatus: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface GetWithdrawalStatusRequest {
|
|
63
|
+
withdrawRequestId: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface GetWithdrawalStatusResponse {
|
|
67
|
+
withdrawRequestId: string;
|
|
68
|
+
custodyTransferId: string;
|
|
69
|
+
mappedStatus: string;
|
|
70
|
+
/** Сырой статус от BitGo. */
|
|
71
|
+
rawCustodyStatus: string;
|
|
72
|
+
txHash?: string | undefined;
|
|
73
|
+
errorCode?: string | undefined;
|
|
74
|
+
errorMessage?: string | undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface GetDepositStatusRequest {
|
|
78
|
+
userId: number;
|
|
79
|
+
network: string;
|
|
80
|
+
/** Ранее выданный депозитный адрес. */
|
|
81
|
+
address: string;
|
|
82
|
+
/** Опционально: подсказка по конкретной транзакции (информативно). */
|
|
83
|
+
txHash?: string | undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface GetDepositStatusResponse {
|
|
87
|
+
status: DepositTrackingStatus;
|
|
88
|
+
/** Человекочитаемое пояснение (например, куда смотреть дальше — Ledger). */
|
|
89
|
+
message: string;
|
|
90
|
+
txHash?: string | undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export const CUSTODY_V1_PACKAGE_NAME = "custody.v1";
|
|
94
|
+
|
|
95
|
+
/** CustodyService — операции с кастоди-кошельком от имени пользователя (без прямого доступа клиента к BitGo). */
|
|
96
|
+
|
|
97
|
+
export interface CustodyServiceClient {
|
|
98
|
+
/**
|
|
99
|
+
* Выдать существующий или создать новый депозитный адрес пользователя для пары (сеть, актив).
|
|
100
|
+
* При создании адрес регистрируется в Ledger через исходящий gRPC mpc → ledger.
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
getOrCreateDepositAddress(request: GetDepositAddressRequest): Observable<GetDepositAddressResponse>;
|
|
104
|
+
|
|
105
|
+
/** Инициировать вывод средств на указанный on-chain адрес; возвращает id трансфера в custody и унифицированный статус. */
|
|
106
|
+
|
|
107
|
+
createWithdrawal(request: CreateWithdrawalRequest): Observable<CreateWithdrawalResponse>;
|
|
108
|
+
|
|
109
|
+
/** Получить текущий статус ранее созданного вывода по внешнему id заявки (withdraw_request_id). */
|
|
110
|
+
|
|
111
|
+
getWithdrawalStatus(request: GetWithdrawalStatusRequest): Observable<GetWithdrawalStatusResponse>;
|
|
112
|
+
|
|
113
|
+
/** Упрощённый статус «депозита по адресу» на стороне custody (выдача адреса / ожидание on-chain — без полного трекинга в этой БД). */
|
|
114
|
+
|
|
115
|
+
getDepositStatus(request: GetDepositStatusRequest): Observable<GetDepositStatusResponse>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** CustodyService — операции с кастоди-кошельком от имени пользователя (без прямого доступа клиента к BitGo). */
|
|
119
|
+
|
|
120
|
+
export interface CustodyServiceController {
|
|
121
|
+
/**
|
|
122
|
+
* Выдать существующий или создать новый депозитный адрес пользователя для пары (сеть, актив).
|
|
123
|
+
* При создании адрес регистрируется в Ledger через исходящий gRPC mpc → ledger.
|
|
124
|
+
*/
|
|
125
|
+
|
|
126
|
+
getOrCreateDepositAddress(
|
|
127
|
+
request: GetDepositAddressRequest,
|
|
128
|
+
): Promise<GetDepositAddressResponse> | Observable<GetDepositAddressResponse> | GetDepositAddressResponse;
|
|
129
|
+
|
|
130
|
+
/** Инициировать вывод средств на указанный on-chain адрес; возвращает id трансфера в custody и унифицированный статус. */
|
|
131
|
+
|
|
132
|
+
createWithdrawal(
|
|
133
|
+
request: CreateWithdrawalRequest,
|
|
134
|
+
): Promise<CreateWithdrawalResponse> | Observable<CreateWithdrawalResponse> | CreateWithdrawalResponse;
|
|
135
|
+
|
|
136
|
+
/** Получить текущий статус ранее созданного вывода по внешнему id заявки (withdraw_request_id). */
|
|
137
|
+
|
|
138
|
+
getWithdrawalStatus(
|
|
139
|
+
request: GetWithdrawalStatusRequest,
|
|
140
|
+
): Promise<GetWithdrawalStatusResponse> | Observable<GetWithdrawalStatusResponse> | GetWithdrawalStatusResponse;
|
|
141
|
+
|
|
142
|
+
/** Упрощённый статус «депозита по адресу» на стороне custody (выдача адреса / ожидание on-chain — без полного трекинга в этой БД). */
|
|
143
|
+
|
|
144
|
+
getDepositStatus(
|
|
145
|
+
request: GetDepositStatusRequest,
|
|
146
|
+
): Promise<GetDepositStatusResponse> | Observable<GetDepositStatusResponse> | GetDepositStatusResponse;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function CustodyServiceControllerMethods() {
|
|
150
|
+
return function (constructor: Function) {
|
|
151
|
+
const grpcMethods: string[] = [
|
|
152
|
+
"getOrCreateDepositAddress",
|
|
153
|
+
"createWithdrawal",
|
|
154
|
+
"getWithdrawalStatus",
|
|
155
|
+
"getDepositStatus",
|
|
156
|
+
];
|
|
157
|
+
for (const method of grpcMethods) {
|
|
158
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
159
|
+
GrpcMethod("CustodyService", method)(constructor.prototype[method], method, descriptor);
|
|
160
|
+
}
|
|
161
|
+
const grpcStreamMethods: string[] = [];
|
|
162
|
+
for (const method of grpcStreamMethods) {
|
|
163
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
164
|
+
GrpcStreamMethod("CustodyService", method)(constructor.prototype[method], method, descriptor);
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export const CUSTODY_SERVICE_NAME = "CustodyService";
|
package/gen/ledger.ts
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
|
2
|
+
// versions:
|
|
3
|
+
// protoc-gen-ts_proto v2.11.4
|
|
4
|
+
// protoc v7.34.0
|
|
5
|
+
// source: ledger.proto
|
|
6
|
+
|
|
7
|
+
/* eslint-disable */
|
|
8
|
+
import { GrpcMethod, GrpcStreamMethod } from "@nestjs/microservices";
|
|
9
|
+
import { Observable } from "rxjs";
|
|
10
|
+
|
|
11
|
+
export const protobufPackage = "ledger.v1";
|
|
12
|
+
|
|
13
|
+
export interface RegisterDepositAddressRequest {
|
|
14
|
+
/** Идентификатор пользователя (строка, часто decimal bigint). */
|
|
15
|
+
userId: string;
|
|
16
|
+
/** On-chain адрес приёма. */
|
|
17
|
+
address: string;
|
|
18
|
+
/** Код актива, напр. USDT. */
|
|
19
|
+
asset: string;
|
|
20
|
+
/** Сеть, напр. TRON, BSC. */
|
|
21
|
+
network: string;
|
|
22
|
+
/** Опционально: id кошелька/аккаунта в custody. */
|
|
23
|
+
custodyWalletId?: string | undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface RegisterDepositAddressResponse {
|
|
27
|
+
/** Id записи адреса в ledger. */
|
|
28
|
+
id: string;
|
|
29
|
+
userId: string;
|
|
30
|
+
address: string;
|
|
31
|
+
asset: string;
|
|
32
|
+
network: string;
|
|
33
|
+
custodyWalletId?:
|
|
34
|
+
| string
|
|
35
|
+
| undefined;
|
|
36
|
+
/** ISO 8601. */
|
|
37
|
+
createdAt: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface CreditUserBalanceRequest {
|
|
41
|
+
userId: string;
|
|
42
|
+
asset: string;
|
|
43
|
+
network: string;
|
|
44
|
+
/** Десятичная строка (фиксированная точность по правилам сервиса). */
|
|
45
|
+
amount: string;
|
|
46
|
+
/** Идентификатор транзакции в сети или суррогат для идемпотентности. */
|
|
47
|
+
txHash: string;
|
|
48
|
+
/** Внешний id операции (custody, провайдер). */
|
|
49
|
+
externalOperationId: string;
|
|
50
|
+
/** Ключ идемпотентности вызова. */
|
|
51
|
+
idempotencyKey: string;
|
|
52
|
+
/** Опционально: число подтверждений на момент зачисления. */
|
|
53
|
+
confirmations?: number | undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface CreditUserBalanceResponse {
|
|
57
|
+
/** Id созданной/найденной записи депозита. */
|
|
58
|
+
depositId: string;
|
|
59
|
+
/** Id ledger-операции. */
|
|
60
|
+
ledgerOperationId: string;
|
|
61
|
+
/** Доступно после операции. */
|
|
62
|
+
available: string;
|
|
63
|
+
reserved: string;
|
|
64
|
+
total: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface RegisterWithdrawalRequest {
|
|
68
|
+
userId: string;
|
|
69
|
+
asset: string;
|
|
70
|
+
network: string;
|
|
71
|
+
amount: string;
|
|
72
|
+
/** Адрес получателя в сети. */
|
|
73
|
+
destinationAddress: string;
|
|
74
|
+
/** Внешний id заявки (idempotency с точки зрения продукта). */
|
|
75
|
+
requestId: string;
|
|
76
|
+
/** Id трансфера в custody (BitGo), если уже известен. */
|
|
77
|
+
externalWithdrawalId?:
|
|
78
|
+
| string
|
|
79
|
+
| undefined;
|
|
80
|
+
/** Комиссия сервиса, строка decimal. */
|
|
81
|
+
serviceFee: string;
|
|
82
|
+
/** Сетевая комиссия, строка decimal. */
|
|
83
|
+
networkFee: string;
|
|
84
|
+
/** Ключ идемпотентности вызова RegisterWithdrawal. */
|
|
85
|
+
idempotencyKey: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface RegisterWithdrawalResponse {
|
|
89
|
+
/** Внутренний id вывода в ledger. */
|
|
90
|
+
withdrawalId: string;
|
|
91
|
+
/** Текущий статус (enum строкой, см. реализацию). */
|
|
92
|
+
status: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface ReserveFundsRequest {
|
|
96
|
+
userId: string;
|
|
97
|
+
asset: string;
|
|
98
|
+
network: string;
|
|
99
|
+
amount: string;
|
|
100
|
+
/** Внутренний id вывода, под который резервируются средства. */
|
|
101
|
+
withdrawalId: string;
|
|
102
|
+
idempotencyKey: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ReserveFundsResponse {
|
|
106
|
+
ledgerOperationId: string;
|
|
107
|
+
available: string;
|
|
108
|
+
reserved: string;
|
|
109
|
+
total: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface ReleaseFundsRequest {
|
|
113
|
+
withdrawalId: string;
|
|
114
|
+
/** Причина снятия резерва (аудит). */
|
|
115
|
+
reason: string;
|
|
116
|
+
idempotencyKey: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface ReleaseFundsResponse {
|
|
120
|
+
ledgerOperationId: string;
|
|
121
|
+
available: string;
|
|
122
|
+
reserved: string;
|
|
123
|
+
total: string;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface FinalizeWithdrawalRequest {
|
|
127
|
+
withdrawalId: string;
|
|
128
|
+
txHash: string;
|
|
129
|
+
/** ISO 8601 время финализации. */
|
|
130
|
+
finalizedAt: string;
|
|
131
|
+
idempotencyKey: string;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface FinalizeWithdrawalResponse {
|
|
135
|
+
ledgerOperationId: string;
|
|
136
|
+
available: string;
|
|
137
|
+
reserved: string;
|
|
138
|
+
total: string;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface UpdateWithdrawalStatusRequest {
|
|
142
|
+
/** Внутренний id вывода в ledger. */
|
|
143
|
+
withdrawalId?:
|
|
144
|
+
| string
|
|
145
|
+
| undefined;
|
|
146
|
+
/** Id в custody (например BitGo transfer id). */
|
|
147
|
+
externalWithdrawalId?:
|
|
148
|
+
| string
|
|
149
|
+
| undefined;
|
|
150
|
+
/** Целевой статус (строка enum Prisma/ledger). */
|
|
151
|
+
newStatus: string;
|
|
152
|
+
txHash?:
|
|
153
|
+
| string
|
|
154
|
+
| undefined;
|
|
155
|
+
/** Сырой JSON от custody/webhook для аудита. */
|
|
156
|
+
rawPayloadJson?: string | undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface UpdateWithdrawalStatusResponse {
|
|
160
|
+
withdrawalId: string;
|
|
161
|
+
status: string;
|
|
162
|
+
/** Была ли выполнена финализация в рамках этого вызова. */
|
|
163
|
+
finalized: boolean;
|
|
164
|
+
/** Был ли снят резерв (отмена/ошибка). */
|
|
165
|
+
released: boolean;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface GetBalanceRequest {
|
|
169
|
+
userId: string;
|
|
170
|
+
asset: string;
|
|
171
|
+
network: string;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export interface GetBalanceResponse {
|
|
175
|
+
userId: string;
|
|
176
|
+
asset: string;
|
|
177
|
+
network: string;
|
|
178
|
+
available: string;
|
|
179
|
+
reserved: string;
|
|
180
|
+
total: string;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export interface GetBalancesRequest {
|
|
184
|
+
userId: string;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export interface BalanceRow {
|
|
188
|
+
userId: string;
|
|
189
|
+
asset: string;
|
|
190
|
+
network: string;
|
|
191
|
+
available: string;
|
|
192
|
+
reserved: string;
|
|
193
|
+
total: string;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export interface GetBalancesResponse {
|
|
197
|
+
balances: BalanceRow[];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export interface TransactionFeedItem {
|
|
201
|
+
id: string;
|
|
202
|
+
/** Тип события ленты (строка, см. TransactionFeedType в реализации). */
|
|
203
|
+
type: string;
|
|
204
|
+
asset: string;
|
|
205
|
+
network: string;
|
|
206
|
+
amount?: string | undefined;
|
|
207
|
+
referenceType?: string | undefined;
|
|
208
|
+
referenceId?: string | undefined;
|
|
209
|
+
title?: string | undefined;
|
|
210
|
+
createdAt: string;
|
|
211
|
+
/** JSON-строка с доп. полями. */
|
|
212
|
+
metadataJson?: string | undefined;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface GetTransactionFeedRequest {
|
|
216
|
+
userId: string;
|
|
217
|
+
limit: number;
|
|
218
|
+
/** Курсор для следующей страницы. */
|
|
219
|
+
cursorId?: string | undefined;
|
|
220
|
+
offset?: number | undefined;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export interface GetTransactionFeedResponse {
|
|
224
|
+
items: TransactionFeedItem[];
|
|
225
|
+
nextCursorId?:
|
|
226
|
+
| string
|
|
227
|
+
| undefined;
|
|
228
|
+
/** Число элементов в этом ответе. */
|
|
229
|
+
totalReturned: number;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export const LEDGER_V1_PACKAGE_NAME = "ledger.v1";
|
|
233
|
+
|
|
234
|
+
export interface LedgerServiceClient {
|
|
235
|
+
/** Регистрация депозитного адреса: привязка on-chain адреса к пользователю, активу и сети (до зачисления средств). */
|
|
236
|
+
|
|
237
|
+
registerDepositAddress(request: RegisterDepositAddressRequest): Observable<RegisterDepositAddressResponse>;
|
|
238
|
+
|
|
239
|
+
/** Зачисление средств на доступный баланс пользователя (подтверждённый депозит); идемпотентность по ключу и внешнему id операции. */
|
|
240
|
+
|
|
241
|
+
creditUserBalance(request: CreditUserBalanceRequest): Observable<CreditUserBalanceResponse>;
|
|
242
|
+
|
|
243
|
+
/** Создание записи о выводе в учёте (черновик заявки); дальнейшие шаги — резерв, смена статусов, финализация. */
|
|
244
|
+
|
|
245
|
+
registerWithdrawal(request: RegisterWithdrawalRequest): Observable<RegisterWithdrawalResponse>;
|
|
246
|
+
|
|
247
|
+
/** Блокировка (резерв) средств на балансе под конкретный вывод после прохождения проверок. */
|
|
248
|
+
|
|
249
|
+
reserveFunds(request: ReserveFundsRequest): Observable<ReserveFundsResponse>;
|
|
250
|
+
|
|
251
|
+
/** Снятие резерва (отмена вывода, ошибка custody и т.п.) с возвратом средств в available. */
|
|
252
|
+
|
|
253
|
+
releaseFunds(request: ReleaseFundsRequest): Observable<ReleaseFundsResponse>;
|
|
254
|
+
|
|
255
|
+
/** Фиксация успешного вывода в сеть: списание из резерва, сохранение tx hash. */
|
|
256
|
+
|
|
257
|
+
finalizeWithdrawal(request: FinalizeWithdrawalRequest): Observable<FinalizeWithdrawalResponse>;
|
|
258
|
+
|
|
259
|
+
/** Обновление статуса вывода по внутреннему id или внешнему id custody (BitGo transfer id); переходы валидируются по правилам ledger. */
|
|
260
|
+
|
|
261
|
+
updateWithdrawalStatus(request: UpdateWithdrawalStatusRequest): Observable<UpdateWithdrawalStatusResponse>;
|
|
262
|
+
|
|
263
|
+
/** Снимок баланса пользователя по одной паре (asset, network): available / reserved / total. */
|
|
264
|
+
|
|
265
|
+
getBalance(request: GetBalanceRequest): Observable<GetBalanceResponse>;
|
|
266
|
+
|
|
267
|
+
/** Все балансовые позиции пользователя по всем активам и сетям. */
|
|
268
|
+
|
|
269
|
+
getBalances(request: GetBalancesRequest): Observable<GetBalancesResponse>;
|
|
270
|
+
|
|
271
|
+
/** Постраничная лента операций пользователя (история для UI); курсор и offset — на усмотрение сервера. */
|
|
272
|
+
|
|
273
|
+
getTransactionFeed(request: GetTransactionFeedRequest): Observable<GetTransactionFeedResponse>;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export interface LedgerServiceController {
|
|
277
|
+
/** Регистрация депозитного адреса: привязка on-chain адреса к пользователю, активу и сети (до зачисления средств). */
|
|
278
|
+
|
|
279
|
+
registerDepositAddress(
|
|
280
|
+
request: RegisterDepositAddressRequest,
|
|
281
|
+
):
|
|
282
|
+
| Promise<RegisterDepositAddressResponse>
|
|
283
|
+
| Observable<RegisterDepositAddressResponse>
|
|
284
|
+
| RegisterDepositAddressResponse;
|
|
285
|
+
|
|
286
|
+
/** Зачисление средств на доступный баланс пользователя (подтверждённый депозит); идемпотентность по ключу и внешнему id операции. */
|
|
287
|
+
|
|
288
|
+
creditUserBalance(
|
|
289
|
+
request: CreditUserBalanceRequest,
|
|
290
|
+
): Promise<CreditUserBalanceResponse> | Observable<CreditUserBalanceResponse> | CreditUserBalanceResponse;
|
|
291
|
+
|
|
292
|
+
/** Создание записи о выводе в учёте (черновик заявки); дальнейшие шаги — резерв, смена статусов, финализация. */
|
|
293
|
+
|
|
294
|
+
registerWithdrawal(
|
|
295
|
+
request: RegisterWithdrawalRequest,
|
|
296
|
+
): Promise<RegisterWithdrawalResponse> | Observable<RegisterWithdrawalResponse> | RegisterWithdrawalResponse;
|
|
297
|
+
|
|
298
|
+
/** Блокировка (резерв) средств на балансе под конкретный вывод после прохождения проверок. */
|
|
299
|
+
|
|
300
|
+
reserveFunds(
|
|
301
|
+
request: ReserveFundsRequest,
|
|
302
|
+
): Promise<ReserveFundsResponse> | Observable<ReserveFundsResponse> | ReserveFundsResponse;
|
|
303
|
+
|
|
304
|
+
/** Снятие резерва (отмена вывода, ошибка custody и т.п.) с возвратом средств в available. */
|
|
305
|
+
|
|
306
|
+
releaseFunds(
|
|
307
|
+
request: ReleaseFundsRequest,
|
|
308
|
+
): Promise<ReleaseFundsResponse> | Observable<ReleaseFundsResponse> | ReleaseFundsResponse;
|
|
309
|
+
|
|
310
|
+
/** Фиксация успешного вывода в сеть: списание из резерва, сохранение tx hash. */
|
|
311
|
+
|
|
312
|
+
finalizeWithdrawal(
|
|
313
|
+
request: FinalizeWithdrawalRequest,
|
|
314
|
+
): Promise<FinalizeWithdrawalResponse> | Observable<FinalizeWithdrawalResponse> | FinalizeWithdrawalResponse;
|
|
315
|
+
|
|
316
|
+
/** Обновление статуса вывода по внутреннему id или внешнему id custody (BitGo transfer id); переходы валидируются по правилам ledger. */
|
|
317
|
+
|
|
318
|
+
updateWithdrawalStatus(
|
|
319
|
+
request: UpdateWithdrawalStatusRequest,
|
|
320
|
+
):
|
|
321
|
+
| Promise<UpdateWithdrawalStatusResponse>
|
|
322
|
+
| Observable<UpdateWithdrawalStatusResponse>
|
|
323
|
+
| UpdateWithdrawalStatusResponse;
|
|
324
|
+
|
|
325
|
+
/** Снимок баланса пользователя по одной паре (asset, network): available / reserved / total. */
|
|
326
|
+
|
|
327
|
+
getBalance(
|
|
328
|
+
request: GetBalanceRequest,
|
|
329
|
+
): Promise<GetBalanceResponse> | Observable<GetBalanceResponse> | GetBalanceResponse;
|
|
330
|
+
|
|
331
|
+
/** Все балансовые позиции пользователя по всем активам и сетям. */
|
|
332
|
+
|
|
333
|
+
getBalances(
|
|
334
|
+
request: GetBalancesRequest,
|
|
335
|
+
): Promise<GetBalancesResponse> | Observable<GetBalancesResponse> | GetBalancesResponse;
|
|
336
|
+
|
|
337
|
+
/** Постраничная лента операций пользователя (история для UI); курсор и offset — на усмотрение сервера. */
|
|
338
|
+
|
|
339
|
+
getTransactionFeed(
|
|
340
|
+
request: GetTransactionFeedRequest,
|
|
341
|
+
): Promise<GetTransactionFeedResponse> | Observable<GetTransactionFeedResponse> | GetTransactionFeedResponse;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function LedgerServiceControllerMethods() {
|
|
345
|
+
return function (constructor: Function) {
|
|
346
|
+
const grpcMethods: string[] = [
|
|
347
|
+
"registerDepositAddress",
|
|
348
|
+
"creditUserBalance",
|
|
349
|
+
"registerWithdrawal",
|
|
350
|
+
"reserveFunds",
|
|
351
|
+
"releaseFunds",
|
|
352
|
+
"finalizeWithdrawal",
|
|
353
|
+
"updateWithdrawalStatus",
|
|
354
|
+
"getBalance",
|
|
355
|
+
"getBalances",
|
|
356
|
+
"getTransactionFeed",
|
|
357
|
+
];
|
|
358
|
+
for (const method of grpcMethods) {
|
|
359
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
360
|
+
GrpcMethod("LedgerService", method)(constructor.prototype[method], method, descriptor);
|
|
361
|
+
}
|
|
362
|
+
const grpcStreamMethods: string[] = [];
|
|
363
|
+
for (const method of grpcStreamMethods) {
|
|
364
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
365
|
+
GrpcStreamMethod("LedgerService", method)(constructor.prototype[method], method, descriptor);
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export const LEDGER_SERVICE_NAME = "LedgerService";
|
package/gen/user.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
|
2
|
+
// versions:
|
|
3
|
+
// protoc-gen-ts_proto v2.11.4
|
|
4
|
+
// protoc v7.34.0
|
|
5
|
+
// source: user.proto
|
|
6
|
+
|
|
7
|
+
/* eslint-disable */
|
|
8
|
+
import { GrpcMethod, GrpcStreamMethod } from "@nestjs/microservices";
|
|
9
|
+
import { Observable } from "rxjs";
|
|
10
|
+
|
|
11
|
+
export const protobufPackage = "user";
|
|
12
|
+
|
|
13
|
+
export interface GetUserRequest {
|
|
14
|
+
id: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface UserResponse {
|
|
18
|
+
id: number;
|
|
19
|
+
email?: string | undefined;
|
|
20
|
+
phone?: string | undefined;
|
|
21
|
+
telegramId?: string | undefined;
|
|
22
|
+
telegramUsername?: string | undefined;
|
|
23
|
+
appleSub?: string | undefined;
|
|
24
|
+
registrationType: string;
|
|
25
|
+
firstName?: string | undefined;
|
|
26
|
+
lastName?: string | undefined;
|
|
27
|
+
avatar?: string | undefined;
|
|
28
|
+
createdAt: string;
|
|
29
|
+
updatedAt: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const USER_PACKAGE_NAME = "user";
|
|
33
|
+
|
|
34
|
+
export interface UserServiceClient {
|
|
35
|
+
getUser(request: GetUserRequest): Observable<UserResponse>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface UserServiceController {
|
|
39
|
+
getUser(request: GetUserRequest): Promise<UserResponse> | Observable<UserResponse> | UserResponse;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function UserServiceControllerMethods() {
|
|
43
|
+
return function (constructor: Function) {
|
|
44
|
+
const grpcMethods: string[] = ["getUser"];
|
|
45
|
+
for (const method of grpcMethods) {
|
|
46
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
47
|
+
GrpcMethod("UserService", method)(constructor.prototype[method], method, descriptor);
|
|
48
|
+
}
|
|
49
|
+
const grpcStreamMethods: string[] = [];
|
|
50
|
+
for (const method of grpcStreamMethods) {
|
|
51
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
52
|
+
GrpcStreamMethod("UserService", method)(constructor.prototype[method], method, descriptor);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const USER_SERVICE_NAME = "UserService";
|
package/gen/webhook.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
|
2
|
+
// versions:
|
|
3
|
+
// protoc-gen-ts_proto v2.11.4
|
|
4
|
+
// protoc v7.34.0
|
|
5
|
+
// source: webhook.proto
|
|
6
|
+
|
|
7
|
+
/* eslint-disable */
|
|
8
|
+
import { GrpcMethod, GrpcStreamMethod } from "@nestjs/microservices";
|
|
9
|
+
import { Observable } from "rxjs";
|
|
10
|
+
|
|
11
|
+
export const protobufPackage = "webhook.v1";
|
|
12
|
+
|
|
13
|
+
export interface ProcessWebhookRequest {
|
|
14
|
+
/**
|
|
15
|
+
* Полное тело webhook от BitGo в виде одной JSON-строки (как получено после парсинга HTTP, объекты сериализованы стандартно).
|
|
16
|
+
* Клиент (gateway) обязан передавать валидный JSON; mpc парсит и маппит поля transfer / state / data и т.д.
|
|
17
|
+
*/
|
|
18
|
+
jsonPayload: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ProcessWebhookResponse {
|
|
22
|
+
/** true, если обработка завершилась без фатальной ошибки. */
|
|
23
|
+
ok: boolean;
|
|
24
|
+
/** Стабильный id события (хеш, transfer id и т.п.) — для логов и ответа вызывающей стороне. */
|
|
25
|
+
eventId: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const WEBHOOK_V1_PACKAGE_NAME = "webhook.v1";
|
|
29
|
+
|
|
30
|
+
export interface WebhookServiceClient {
|
|
31
|
+
/**
|
|
32
|
+
* Обработка одного события webhook BitGo: разбор JSON, дедупликация по event_id, обновление custody-транзакций,
|
|
33
|
+
* при необходимости — gRPC в Ledger (статус вывода, зачисление депозита) и уведомления.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
processBitGoWebhook(request: ProcessWebhookRequest): Observable<ProcessWebhookResponse>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface WebhookServiceController {
|
|
40
|
+
/**
|
|
41
|
+
* Обработка одного события webhook BitGo: разбор JSON, дедупликация по event_id, обновление custody-транзакций,
|
|
42
|
+
* при необходимости — gRPC в Ledger (статус вывода, зачисление депозита) и уведомления.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
processBitGoWebhook(
|
|
46
|
+
request: ProcessWebhookRequest,
|
|
47
|
+
): Promise<ProcessWebhookResponse> | Observable<ProcessWebhookResponse> | ProcessWebhookResponse;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function WebhookServiceControllerMethods() {
|
|
51
|
+
return function (constructor: Function) {
|
|
52
|
+
const grpcMethods: string[] = ["processBitGoWebhook"];
|
|
53
|
+
for (const method of grpcMethods) {
|
|
54
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
55
|
+
GrpcMethod("WebhookService", method)(constructor.prototype[method], method, descriptor);
|
|
56
|
+
}
|
|
57
|
+
const grpcStreamMethods: string[] = [];
|
|
58
|
+
for (const method of grpcStreamMethods) {
|
|
59
|
+
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
|
|
60
|
+
GrpcStreamMethod("WebhookService", method)(constructor.prototype[method], method, descriptor);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const WEBHOOK_SERVICE_NAME = "WebhookService";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arbiwallet/contracts",
|
|
3
3
|
"descriptions": "Generate and manage smart contracts for ArbiWallet",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.10",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"generate": "protoc -I ./proto ./proto/*.proto --ts_proto_out=./gen --ts_proto_opt=nestJs=true,package=omit"
|
|
7
7
|
},
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
syntax = "proto3";
|
|
2
|
+
|
|
3
|
+
// Пакет gRPC публичного API custody-слоя (mpc_service): выдача депозитных адресов, выводы, статусы.
|
|
4
|
+
// Интеграция с BitGo; вызовы от gateway или внутренних сервисов с доверенной сети.
|
|
5
|
+
package custody.v1;
|
|
6
|
+
|
|
7
|
+
// CustodyService — операции с кастоди-кошельком от имени пользователя (без прямого доступа клиента к BitGo).
|
|
8
|
+
service CustodyService {
|
|
9
|
+
// Выдать существующий или создать новый депозитный адрес пользователя для пары (сеть, актив).
|
|
10
|
+
// При создании адрес регистрируется в Ledger через исходящий gRPC mpc → ledger.
|
|
11
|
+
rpc GetOrCreateDepositAddress(GetDepositAddressRequest) returns (GetDepositAddressResponse);
|
|
12
|
+
// Инициировать вывод средств на указанный on-chain адрес; возвращает id трансфера в custody и унифицированный статус.
|
|
13
|
+
rpc CreateWithdrawal(CreateWithdrawalRequest) returns (CreateWithdrawalResponse);
|
|
14
|
+
// Получить текущий статус ранее созданного вывода по внешнему id заявки (withdraw_request_id).
|
|
15
|
+
rpc GetWithdrawalStatus(GetWithdrawalStatusRequest) returns (GetWithdrawalStatusResponse);
|
|
16
|
+
// Упрощённый статус «депозита по адресу» на стороне custody (выдача адреса / ожидание on-chain — без полного трекинга в этой БД).
|
|
17
|
+
rpc GetDepositStatus(GetDepositStatusRequest) returns (GetDepositStatusResponse);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
message GetDepositAddressRequest {
|
|
21
|
+
int64 user_id = 1; // Идентификатор пользователя (на wire при longs:String — строка).
|
|
22
|
+
string network = 2; // TRON | BSC и т.д.
|
|
23
|
+
string asset = 3; // По умолчанию USDT.
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
message GetDepositAddressResponse {
|
|
27
|
+
int64 user_id = 1;
|
|
28
|
+
string network = 2;
|
|
29
|
+
string asset = 3;
|
|
30
|
+
string address = 4; // Депозитный адрес для пополнения.
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
message CreateWithdrawalRequest {
|
|
34
|
+
string withdraw_request_id = 1; // Уникальный id заявки со стороны продукта (идемпотентность на уровне mpc/БД).
|
|
35
|
+
int64 user_id = 2;
|
|
36
|
+
string network = 3;
|
|
37
|
+
string amount = 4; // Сумма в decimal-строке.
|
|
38
|
+
string to_address = 5; // Адрес получателя в целевой сети.
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
message CreateWithdrawalResponse {
|
|
42
|
+
string withdraw_request_id = 1;
|
|
43
|
+
string custody_transfer_id = 2; // Id трансфера в BitGo (исторически назывался fireblocks_tx_id).
|
|
44
|
+
string mapped_status = 3; // Унифицированный статус вывода для внутренней логики (CREATED, BROADCASTING, …).
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
message GetWithdrawalStatusRequest {
|
|
48
|
+
string withdraw_request_id = 1;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
message GetWithdrawalStatusResponse {
|
|
52
|
+
string withdraw_request_id = 1;
|
|
53
|
+
string custody_transfer_id = 2;
|
|
54
|
+
string mapped_status = 3;
|
|
55
|
+
string raw_custody_status = 4; // Сырой статус от BitGo.
|
|
56
|
+
optional string tx_hash = 5;
|
|
57
|
+
optional string error_code = 6;
|
|
58
|
+
optional string error_message = 7;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
message GetDepositStatusRequest {
|
|
62
|
+
int64 user_id = 1;
|
|
63
|
+
string network = 2;
|
|
64
|
+
string address = 3; // Ранее выданный депозитный адрес.
|
|
65
|
+
optional string tx_hash = 4; // Опционально: подсказка по конкретной транзакции (информативно).
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Статус отслеживания депозита в рамках ответа GetDepositStatus (не полный on-chain индекс).
|
|
69
|
+
enum DepositTrackingStatus {
|
|
70
|
+
DEPOSIT_TRACKING_STATUS_UNSPECIFIED = 0;
|
|
71
|
+
DEPOSIT_TRACKING_STATUS_UNKNOWN = 1; // Адрес не найден / нет данных.
|
|
72
|
+
DEPOSIT_TRACKING_STATUS_PENDING = 2; // Адрес выдан, ожидание/не подтверждено в этом сервисе.
|
|
73
|
+
DEPOSIT_TRACKING_STATUS_CONFIRMED = 3; // Подтверждено (если сервис отдаёт такой уровень детализации).
|
|
74
|
+
DEPOSIT_TRACKING_STATUS_FAILED = 4;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
message GetDepositStatusResponse {
|
|
78
|
+
DepositTrackingStatus status = 1;
|
|
79
|
+
string message = 2; // Человекочитаемое пояснение (например, куда смотреть дальше — Ledger).
|
|
80
|
+
optional string tx_hash = 3;
|
|
81
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
syntax = "proto3";
|
|
2
|
+
|
|
3
|
+
// Пакет gRPC API микросервиса Ledger (внутренний баланс, депозиты, выводы, лента операций).
|
|
4
|
+
// Реализация: ledger_microservice; клиенты: gateway, mpc_service и др.
|
|
5
|
+
package ledger.v1;
|
|
6
|
+
|
|
7
|
+
option csharp_namespace = "Ledger.V1";
|
|
8
|
+
option java_multiple_files = true;
|
|
9
|
+
option java_package = "com.arbiwallet.ledger.v1";
|
|
10
|
+
|
|
11
|
+
service LedgerService {
|
|
12
|
+
// Регистрация депозитного адреса: привязка on-chain адреса к пользователю, активу и сети (до зачисления средств).
|
|
13
|
+
rpc RegisterDepositAddress(RegisterDepositAddressRequest) returns (RegisterDepositAddressResponse);
|
|
14
|
+
// Зачисление средств на доступный баланс пользователя (подтверждённый депозит); идемпотентность по ключу и внешнему id операции.
|
|
15
|
+
rpc CreditUserBalance(CreditUserBalanceRequest) returns (CreditUserBalanceResponse);
|
|
16
|
+
// Создание записи о выводе в учёте (черновик заявки); дальнейшие шаги — резерв, смена статусов, финализация.
|
|
17
|
+
rpc RegisterWithdrawal(RegisterWithdrawalRequest) returns (RegisterWithdrawalResponse);
|
|
18
|
+
// Блокировка (резерв) средств на балансе под конкретный вывод после прохождения проверок.
|
|
19
|
+
rpc ReserveFunds(ReserveFundsRequest) returns (ReserveFundsResponse);
|
|
20
|
+
// Снятие резерва (отмена вывода, ошибка custody и т.п.) с возвратом средств в available.
|
|
21
|
+
rpc ReleaseFunds(ReleaseFundsRequest) returns (ReleaseFundsResponse);
|
|
22
|
+
// Фиксация успешного вывода в сеть: списание из резерва, сохранение tx hash.
|
|
23
|
+
rpc FinalizeWithdrawal(FinalizeWithdrawalRequest) returns (FinalizeWithdrawalResponse);
|
|
24
|
+
// Обновление статуса вывода по внутреннему id или внешнему id custody (BitGo transfer id); переходы валидируются по правилам ledger.
|
|
25
|
+
rpc UpdateWithdrawalStatus(UpdateWithdrawalStatusRequest) returns (UpdateWithdrawalStatusResponse);
|
|
26
|
+
// Снимок баланса пользователя по одной паре (asset, network): available / reserved / total.
|
|
27
|
+
rpc GetBalance(GetBalanceRequest) returns (GetBalanceResponse);
|
|
28
|
+
// Все балансовые позиции пользователя по всем активам и сетям.
|
|
29
|
+
rpc GetBalances(GetBalancesRequest) returns (GetBalancesResponse);
|
|
30
|
+
// Постраничная лента операций пользователя (история для UI); курсор и offset — на усмотрение сервера.
|
|
31
|
+
rpc GetTransactionFeed(GetTransactionFeedRequest) returns (GetTransactionFeedResponse);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
message RegisterDepositAddressRequest {
|
|
35
|
+
string user_id = 1; // Идентификатор пользователя (строка, часто decimal bigint).
|
|
36
|
+
string address = 2; // On-chain адрес приёма.
|
|
37
|
+
string asset = 3; // Код актива, напр. USDT.
|
|
38
|
+
string network = 4; // Сеть, напр. TRON, BSC.
|
|
39
|
+
optional string custody_wallet_id = 5; // Опционально: id кошелька/аккаунта в custody.
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
message RegisterDepositAddressResponse {
|
|
43
|
+
string id = 1; // Id записи адреса в ledger.
|
|
44
|
+
string user_id = 2;
|
|
45
|
+
string address = 3;
|
|
46
|
+
string asset = 4;
|
|
47
|
+
string network = 5;
|
|
48
|
+
optional string custody_wallet_id = 6;
|
|
49
|
+
string created_at = 7; // ISO 8601.
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
message CreditUserBalanceRequest {
|
|
53
|
+
string user_id = 1;
|
|
54
|
+
string asset = 2;
|
|
55
|
+
string network = 3;
|
|
56
|
+
string amount = 4; // Десятичная строка (фиксированная точность по правилам сервиса).
|
|
57
|
+
string tx_hash = 5; // Идентификатор транзакции в сети или суррогат для идемпотентности.
|
|
58
|
+
string external_operation_id = 6; // Внешний id операции (custody, провайдер).
|
|
59
|
+
string idempotency_key = 7; // Ключ идемпотентности вызова.
|
|
60
|
+
optional int32 confirmations = 8; // Опционально: число подтверждений на момент зачисления.
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
message CreditUserBalanceResponse {
|
|
64
|
+
string deposit_id = 1; // Id созданной/найденной записи депозита.
|
|
65
|
+
string ledger_operation_id = 2; // Id ledger-операции.
|
|
66
|
+
string available = 3; // Доступно после операции.
|
|
67
|
+
string reserved = 4;
|
|
68
|
+
string total = 5;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
message RegisterWithdrawalRequest {
|
|
72
|
+
string user_id = 1;
|
|
73
|
+
string asset = 2;
|
|
74
|
+
string network = 3;
|
|
75
|
+
string amount = 4;
|
|
76
|
+
string destination_address = 5; // Адрес получателя в сети.
|
|
77
|
+
string request_id = 6; // Внешний id заявки (idempotency с точки зрения продукта).
|
|
78
|
+
optional string external_withdrawal_id = 7; // Id трансфера в custody (BitGo), если уже известен.
|
|
79
|
+
string service_fee = 8; // Комиссия сервиса, строка decimal.
|
|
80
|
+
string network_fee = 9; // Сетевая комиссия, строка decimal.
|
|
81
|
+
string idempotency_key = 10; // Ключ идемпотентности вызова RegisterWithdrawal.
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
message RegisterWithdrawalResponse {
|
|
85
|
+
string withdrawal_id = 1; // Внутренний id вывода в ledger.
|
|
86
|
+
string status = 2; // Текущий статус (enum строкой, см. реализацию).
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
message ReserveFundsRequest {
|
|
90
|
+
string user_id = 1;
|
|
91
|
+
string asset = 2;
|
|
92
|
+
string network = 3;
|
|
93
|
+
string amount = 4;
|
|
94
|
+
string withdrawal_id = 5; // Внутренний id вывода, под который резервируются средства.
|
|
95
|
+
string idempotency_key = 6;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
message ReserveFundsResponse {
|
|
99
|
+
string ledger_operation_id = 1;
|
|
100
|
+
string available = 2;
|
|
101
|
+
string reserved = 3;
|
|
102
|
+
string total = 4;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
message ReleaseFundsRequest {
|
|
106
|
+
string withdrawal_id = 1;
|
|
107
|
+
string reason = 2; // Причина снятия резерва (аудит).
|
|
108
|
+
string idempotency_key = 3;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
message ReleaseFundsResponse {
|
|
112
|
+
string ledger_operation_id = 1;
|
|
113
|
+
string available = 2;
|
|
114
|
+
string reserved = 3;
|
|
115
|
+
string total = 4;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
message FinalizeWithdrawalRequest {
|
|
119
|
+
string withdrawal_id = 1;
|
|
120
|
+
string tx_hash = 2;
|
|
121
|
+
string finalized_at = 3; // ISO 8601 время финализации.
|
|
122
|
+
string idempotency_key = 4;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
message FinalizeWithdrawalResponse {
|
|
126
|
+
string ledger_operation_id = 1;
|
|
127
|
+
string available = 2;
|
|
128
|
+
string reserved = 3;
|
|
129
|
+
string total = 4;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
message UpdateWithdrawalStatusRequest {
|
|
133
|
+
oneof selector {
|
|
134
|
+
string withdrawal_id = 1; // Внутренний id вывода в ledger.
|
|
135
|
+
string external_withdrawal_id = 2; // Id в custody (например BitGo transfer id).
|
|
136
|
+
}
|
|
137
|
+
string new_status = 3; // Целевой статус (строка enum Prisma/ledger).
|
|
138
|
+
optional string tx_hash = 4;
|
|
139
|
+
optional string raw_payload_json = 5; // Сырой JSON от custody/webhook для аудита.
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
message UpdateWithdrawalStatusResponse {
|
|
143
|
+
string withdrawal_id = 1;
|
|
144
|
+
string status = 2;
|
|
145
|
+
bool finalized = 3; // Была ли выполнена финализация в рамках этого вызова.
|
|
146
|
+
bool released = 4; // Был ли снят резерв (отмена/ошибка).
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
message GetBalanceRequest {
|
|
150
|
+
string user_id = 1;
|
|
151
|
+
string asset = 2;
|
|
152
|
+
string network = 3;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
message GetBalanceResponse {
|
|
156
|
+
string user_id = 1;
|
|
157
|
+
string asset = 2;
|
|
158
|
+
string network = 3;
|
|
159
|
+
string available = 4;
|
|
160
|
+
string reserved = 5;
|
|
161
|
+
string total = 6;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
message GetBalancesRequest {
|
|
165
|
+
string user_id = 1;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
message BalanceRow {
|
|
169
|
+
string user_id = 1;
|
|
170
|
+
string asset = 2;
|
|
171
|
+
string network = 3;
|
|
172
|
+
string available = 4;
|
|
173
|
+
string reserved = 5;
|
|
174
|
+
string total = 6;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
message GetBalancesResponse {
|
|
178
|
+
repeated BalanceRow balances = 1;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
message TransactionFeedItem {
|
|
182
|
+
string id = 1;
|
|
183
|
+
string type = 2; // Тип события ленты (строка, см. TransactionFeedType в реализации).
|
|
184
|
+
string asset = 3;
|
|
185
|
+
string network = 4;
|
|
186
|
+
optional string amount = 5;
|
|
187
|
+
optional string reference_type = 6;
|
|
188
|
+
optional string reference_id = 7;
|
|
189
|
+
optional string title = 8;
|
|
190
|
+
string created_at = 9;
|
|
191
|
+
optional string metadata_json = 10; // JSON-строка с доп. полями.
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
message GetTransactionFeedRequest {
|
|
195
|
+
string user_id = 1;
|
|
196
|
+
int32 limit = 2;
|
|
197
|
+
optional string cursor_id = 3; // Курсор для следующей страницы.
|
|
198
|
+
optional int32 offset = 4;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
message GetTransactionFeedResponse {
|
|
202
|
+
repeated TransactionFeedItem items = 1;
|
|
203
|
+
optional string next_cursor_id = 2;
|
|
204
|
+
int32 total_returned = 3; // Число элементов в этом ответе.
|
|
205
|
+
}
|
package/proto/user.proto
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
syntax = "proto3";
|
|
2
|
+
package user;
|
|
3
|
+
|
|
4
|
+
service UserService {
|
|
5
|
+
rpc GetUser (GetUserRequest) returns (UserResponse);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
message GetUserRequest {
|
|
9
|
+
int32 id = 1;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
message UserResponse {
|
|
13
|
+
int32 id = 1;
|
|
14
|
+
optional string email = 2;
|
|
15
|
+
optional string phone = 3;
|
|
16
|
+
optional string telegram_id = 4;
|
|
17
|
+
optional string telegram_username = 5;
|
|
18
|
+
optional string apple_sub = 6;
|
|
19
|
+
string registration_type = 7;
|
|
20
|
+
optional string first_name = 8;
|
|
21
|
+
optional string last_name = 9;
|
|
22
|
+
optional string avatar = 10;
|
|
23
|
+
string created_at = 11;
|
|
24
|
+
string updated_at = 12;
|
|
25
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
syntax = "proto3";
|
|
2
|
+
|
|
3
|
+
// Пакет внутреннего gRPC для передачи событий BitGo в mpc_service без публичного HTTP на mpc.
|
|
4
|
+
// Типичный поток: WalletGateway принимает POST /webhooks/bitgo → вызывает ProcessBitGoWebhook с JSON телом.
|
|
5
|
+
// Та же бизнес-логика, что у HTTP-обработчика webhook в mpc (дедуп, обновление транзакций, вызовы Ledger/Notification).
|
|
6
|
+
package webhook.v1;
|
|
7
|
+
|
|
8
|
+
service WebhookService {
|
|
9
|
+
// Обработка одного события webhook BitGo: разбор JSON, дедупликация по event_id, обновление custody-транзакций,
|
|
10
|
+
// при необходимости — gRPC в Ledger (статус вывода, зачисление депозита) и уведомления.
|
|
11
|
+
rpc ProcessBitGoWebhook(ProcessWebhookRequest) returns (ProcessWebhookResponse);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
message ProcessWebhookRequest {
|
|
15
|
+
// Полное тело webhook от BitGo в виде одной JSON-строки (как получено после парсинга HTTP, объекты сериализованы стандартно).
|
|
16
|
+
// Клиент (gateway) обязан передавать валидный JSON; mpc парсит и маппит поля transfer / state / data и т.д.
|
|
17
|
+
string json_payload = 1;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
message ProcessWebhookResponse {
|
|
21
|
+
bool ok = 1; // true, если обработка завершилась без фатальной ошибки.
|
|
22
|
+
string event_id = 2; // Стабильный id события (хеш, transfer id и т.п.) — для логов и ответа вызывающей стороне.
|
|
23
|
+
}
|