-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNolusWallet.ts
478 lines (406 loc) · 16.8 KB
/
NolusWallet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import stargate, { DeliverTxResponse, isDeliverTxFailure, StdFee } from '@cosmjs/stargate';
import { SigningCosmWasmClient, SigningCosmWasmClientOptions } from '@cosmjs/cosmwasm-stargate';
import { Coin, EncodeObject, OfflineSigner } from '@cosmjs/proto-signing';
import { CometClient } from '@cosmjs/tendermint-rpc';
import { ExecuteResult } from '@cosmjs/cosmwasm-stargate/build/signingcosmwasmclient';
import { toUtf8, toHex } from '@cosmjs/encoding';
import { MsgExecuteContract } from 'cosmjs-types/cosmwasm/wasm/v1/tx';
import { MsgSend } from 'cosmjs-types/cosmos/bank/v1beta1/tx';
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
import { ContractData } from '../contracts/types/ContractData';
import { encodeSecp256k1Pubkey } from '@cosmjs/amino';
import { ChainConstants } from '../constants';
import { sha256 } from '@cosmjs/crypto';
import { MsgTransfer } from 'cosmjs-types/ibc/applications/transfer/v1/tx';
import { MsgDelegate, MsgUndelegate } from 'cosmjs-types/cosmos/staking/v1beta1/tx';
import { MsgWithdrawDelegatorReward } from 'cosmjs-types/cosmos/distribution/v1beta1/tx';
import { QuerySmartContractStateRequest } from 'cosmjs-types/cosmwasm/wasm/v1/query';
import { claimRewardsMsg, getLenderRewardsMsg } from '../contracts';
import { MsgVote } from 'cosmjs-types/cosmos/gov/v1beta1/tx';
import { QueryParamsRequest, QueryParamsResponse } from '../messages';
/**
* Nolus Wallet service class.
*
* Usage:
*
* ```ts
* import { nolusOfflineSigner } from '@nolus/nolusjs/build/wallet/NolusWalletFactory';
*
* const nolusWallet = await nolusOfflineSigner(offlineSigner);
* nolusWallet.useAccount();
* ```
*/
export class NolusWallet extends SigningCosmWasmClient {
address?: string;
pubKey?: Uint8Array;
algo?: string;
protected offlineSigner: OfflineSigner;
constructor(tmClient: CometClient | undefined | any, signer: OfflineSigner, options: SigningCosmWasmClientOptions) {
super(tmClient, signer, options);
this.offlineSigner = signer;
}
getOfflineSigner() {
return this.offlineSigner;
}
async simulateTx(msg: MsgSend | MsgExecuteContract | MsgTransfer | MsgDelegate | MsgUndelegate | MsgVote | MsgWithdrawDelegatorReward, msgTypeUrl: string, memo = '') {
const pubkey = encodeSecp256k1Pubkey(this.pubKey as Uint8Array);
const msgAny = {
typeUrl: msgTypeUrl,
value: msg,
};
const sequence = await this.sequence();
const { gasInfo } = await this.forceGetQueryClient().tx.simulate([this.registry.encodeAsAny(msgAny)], memo, pubkey, sequence);
const gas = Math.round(Number(gasInfo?.gasUsed ?? 0) * ChainConstants.GAS_MULTIPLIER);
const usedFee = await this.selectDynamicFee(gas, [{ msg: msg, msgTypeUrl: msgTypeUrl }]);
const txRaw = await this.sign(this.address as string, [msgAny], usedFee, memo);
const txBytes = Uint8Array.from(TxRaw.encode(txRaw).finish());
const txHash = toHex(sha256(txBytes));
return {
txHash,
txBytes,
usedFee,
};
}
private async simulateMultiTx(messages: { msg: MsgSend | MsgExecuteContract | MsgTransfer | MsgDelegate | MsgUndelegate | MsgVote | MsgWithdrawDelegatorReward; msgTypeUrl: string }[], memo = '') {
const pubkey = encodeSecp256k1Pubkey(this.pubKey as Uint8Array);
const encodedMSGS = [];
const msgs = [];
for (const item of messages) {
const msgAny = {
typeUrl: item.msgTypeUrl,
value: item.msg,
};
encodedMSGS.push(this.registry.encodeAsAny(msgAny));
msgs.push(msgAny);
}
const sequence = await this.sequence();
const { gasInfo } = await this.forceGetQueryClient().tx.simulate(encodedMSGS, memo, pubkey, sequence);
const gas = Math.round(Number(gasInfo?.gasUsed ?? 0) * ChainConstants.GAS_MULTIPLIER);
const usedFee = await this.selectDynamicFee(gas, messages);
const txRaw = await this.sign(this.address as string, msgs, usedFee, memo);
const txBytes = Uint8Array.from(TxRaw.encode(txRaw).finish());
const txHash = toHex(sha256(txBytes));
return {
txHash,
txBytes,
usedFee,
};
}
private getBalanceOut(msgs: { msg: MsgSend | MsgExecuteContract | MsgTransfer | MsgDelegate | MsgUndelegate | MsgVote | MsgWithdrawDelegatorReward; msgTypeUrl: string }[]) {
const coins: { [key: string]: bigint } = {};
for (const message of msgs) {
switch (message.msgTypeUrl) {
case MsgSend.typeUrl: {
this.parseCoins(coins, (message.msg as MsgSend).amount);
break;
}
case MsgExecuteContract.typeUrl: {
this.parseCoins(coins, (message.msg as MsgExecuteContract).funds);
break;
}
case MsgTransfer.typeUrl: {
this.parseCoins(coins, [(message.msg as MsgTransfer).token]);
break;
}
}
}
return coins;
}
private parseCoins(data: { [key: string]: bigint }, coins: Coin[]) {
for (const coin of coins) {
if (!data[coin.denom]) {
data[coin.denom] = BigInt(coin.amount);
} else {
data[coin.denom] += BigInt(coin.amount);
}
}
}
public async useAccount(): Promise<boolean> {
const accounts = await this.offlineSigner.getAccounts();
if (accounts.length === 0) {
throw new Error('Missing account');
}
this.address = accounts[0].address;
this.pubKey = accounts[0].pubkey;
this.algo = accounts[0].algo;
return true;
}
public async transferAmount(receiverAddress: string, amount: Coin[], fee: StdFee | 'auto' | number, memo?: string): Promise<DeliverTxResponse> {
if (!this.address) {
throw new Error('Sender address is missing');
}
return this.sendTokens(this.address, receiverAddress, amount, fee, memo);
}
public async executeContract(contractAddress: string, msg: Record<string, any>, fee: StdFee | 'auto' | number, memo?: string, funds?: Coin[]): Promise<ExecuteResult> {
if (!this.address) {
throw new Error('Sender address is missing');
}
return this.execute(this.address, contractAddress, msg, fee, memo, funds);
}
public async executeContractSubMsg(contractData: ContractData[], fee: StdFee | 'auto' | number, memo?: string, funds?: Coin[]): Promise<ExecuteResult> {
if (!this.address) {
throw new Error('Sender address is missing');
}
const executeContractMsg: EncodeObject[] = contractData.map((contractData) => {
return {
typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
value: MsgExecuteContract.fromPartial({
sender: this.address,
contract: contractData.contractAddress,
msg: toUtf8(JSON.stringify(contractData.msg)),
funds: [...(funds || [])],
}),
};
});
const result = await this.signAndBroadcast(this.address, executeContractMsg, fee, memo);
if (isDeliverTxFailure(result)) {
throw new Error(this.createDeliverTxResponseErrorMessage(result));
}
return {
logs: stargate.logs.parseRawLog(result.rawLog),
height: result.height,
transactionHash: result.transactionHash,
gasWanted: result.gasWanted,
gasUsed: result.gasUsed,
events: [],
};
}
/**
* Usage:
*
* ```ts
* const amount = coin(1, 'unls');
* const {
* txHash,
* txBytes,
* usedFee
* } = await wallet.simulateBankTransferTx('nolusAddress', [amount]);
* const item = await wallet.broadcastTx(txBytes);
*```
*/
public async simulateBankTransferTx(toAddress: string, amount: Coin[]) {
const msg = MsgSend.fromPartial({
fromAddress: this.address,
toAddress,
amount,
});
return await this.simulateTx(msg, '/cosmos.bank.v1beta1.MsgSend');
}
/**
* Usage:
*
* ```ts
* const downpayment = coin(1, 'ibc/....');
* const msg = {
* open_lease: {
* currency: 'OSMO',
* },
* };
* const {
* txHash,
* txBytes,
* usedFee
* } = await wallet.simulateExecuteContractTx('leaserAddress', msg, [downpayment]);
* const item = await wallet.broadcastTx(txBytes);
* ```
*/
public async simulateExecuteContractTx(contract: string, msgData: Record<string, any>, funds: Coin[] = []) {
const msg = MsgExecuteContract.fromPartial({
sender: this.address,
contract,
msg: toUtf8(JSON.stringify(msgData)),
funds,
});
return await this.simulateTx(msg, '/cosmwasm.wasm.v1.MsgExecuteContract');
}
public async simulateSendIbcTokensTx({ toAddress, amount, sourcePort, sourceChannel, memo = '' }: { toAddress: string; amount: Coin; sourcePort: string; sourceChannel: string; memo?: string }) {
const timeOut = Math.floor(Date.now() / 1000) + ChainConstants.IBC_TRANSFER_TIMEOUT;
const longTimeOut = BigInt(timeOut) * BigInt(1_000_000_000);
const msg = MsgTransfer.fromPartial({
sourcePort,
sourceChannel,
sender: this.address?.toString(),
receiver: toAddress,
token: amount,
timeoutHeight: undefined,
timeoutTimestamp: longTimeOut,
memo,
});
return await this.simulateTx(msg, '/ibc.applications.transfer.v1.MsgTransfer', '');
}
public async simulateDelegateTx(data: { validator: string; amount: Coin }[]) {
const msgs = [];
for (const item of data) {
const msg = MsgDelegate.fromPartial({
validatorAddress: item.validator,
delegatorAddress: this.address,
amount: item.amount,
});
msgs.push({
msg: msg,
msgTypeUrl: '/cosmos.staking.v1beta1.MsgDelegate',
});
}
return await this.simulateMultiTx(msgs, '');
}
public async simulateUndelegateTx(data: { validator: string; amount: Coin }[]) {
const msgs = [];
for (const item of data) {
const msg = MsgUndelegate.fromPartial({
validatorAddress: item.validator,
delegatorAddress: this.address,
amount: item.amount,
});
msgs.push({
msg: msg,
msgTypeUrl: '/cosmos.staking.v1beta1.MsgUndelegate',
});
}
return await this.simulateMultiTx(msgs, '');
}
public async simulateWithdrawRewardTx(data: { validator: string; delegator: string }[]) {
const msgs = [];
for (const item of data) {
const msg = MsgWithdrawDelegatorReward.fromPartial({
validatorAddress: item.validator,
delegatorAddress: this.address,
});
msgs.push({
msg: msg,
msgTypeUrl: '/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward',
});
}
return await this.simulateMultiTx(msgs, '');
}
public async simulateClaimRewards(data: { validator: string; delegator: string }[], lppContracts: string[]) {
const msgs = [];
for (const item of data) {
const msg = MsgWithdrawDelegatorReward.fromPartial({
validatorAddress: item.validator,
delegatorAddress: this.address,
});
msgs.push({
msg: msg,
msgTypeUrl: '/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward',
});
}
for (let lppContract of lppContracts) {
try {
const item = await this.queryContractSmart(lppContract, getLenderRewardsMsg(this.address as string));
if (Number(item.rewards.amount) > 0) {
const msg = MsgExecuteContract.fromPartial({
sender: this.address,
contract: lppContract,
msg: toUtf8(JSON.stringify(claimRewardsMsg(this.address))),
});
msgs.push({
msg: msg,
msgTypeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
});
}
} catch (error) {
console.log(error);
}
}
return await this.simulateMultiTx(msgs, '');
}
private async sequence() {
try {
const { sequence } = await this.getSequence(this.address as string);
return sequence;
} catch (error) {
throw new Error('Insufficient amount of NLS');
}
}
private createDeliverTxResponseErrorMessage(result: DeliverTxResponse) {
return `Error when broadcasting tx ${result.transactionHash} at height ${result.height}. Code: ${result.code}; Raw log: ${result.rawLog}`;
}
public async querySmartContract(contract: string, msg: object, height?: number) {
const data = QuerySmartContractStateRequest.encode({
address: contract,
queryData: toUtf8(JSON.stringify(msg)),
}).finish();
const query: {
path: string;
data: Uint8Array;
prove: boolean;
height?: number;
} = {
path: '/cosmwasm.wasm.v1.Query/SmartContractState',
data,
prove: true,
};
if ((height as number) > 0) {
query.height = height;
}
const client = this.getCometClient();
if (!client) {
throw 'Tendermint client not initialized';
}
const response = await client.abciQuery(query);
return QuerySmartContractStateRequest.decode(response.value);
}
public async getBalance(address: string, denom: string): Promise<Coin> {
const client = this.forceGetQueryClient();
return await client.bank.balance(address, denom);
}
async selectDynamicFee(
gasEstimate: number,
msgs: { msg: MsgSend | MsgExecuteContract | MsgTransfer | MsgDelegate | MsgUndelegate | MsgVote | MsgWithdrawDelegatorReward; msgTypeUrl: string }[],
): Promise<StdFee> {
const gasPrices = await this.gasPrices();
const feeCandidates: { fee: StdFee; denom: string }[] = [];
const out = this.getBalanceOut(msgs);
for (const denom in gasPrices) {
const feeAmount = Math.ceil(gasEstimate * gasPrices[denom]).toString();
feeCandidates.push({
fee: {
amount: [{ amount: feeAmount, denom }],
gas: gasEstimate.toString(),
},
denom,
});
}
const accountAddress = this.address;
if (!accountAddress) {
throw new Error('Account address is not set. Call useAccount() first.');
}
for (const candidate of feeCandidates) {
try {
const balance = await this.getBalance(accountAddress, candidate.denom);
if ((BigInt(balance.amount) - (out[balance.denom] ?? 0n)) >= BigInt(candidate.fee.amount[0].amount)) {
return candidate.fee;
}
} catch (error) {
console.error(`Error fetching balance for ${candidate.denom}:`, error);
}
}
throw new Error('Insufficient funds in any available fee currency.');
}
async gasPrices() {
const taxParams = await this.queryTaxParams();
const gasPrices: { [denom: string]: number } = {};
for (const item of taxParams.params?.dexFeeParams ?? []) {
for (const amount of item.acceptedDenomsMinPrices) {
gasPrices[amount.denom as string] = Number(amount.minPrice);
}
}
gasPrices[ChainConstants.COIN_MINIMAL_DENOM] = Number(ChainConstants.GAS_PRICE_NUMBER);
return gasPrices;
}
async queryTaxParams(): Promise<QueryParamsResponse> {
const client = this.getCometClient();
if (!client) {
throw 'Tendermint client not initialized';
}
const requestData = QueryParamsRequest.encode({}).finish();
const query = {
path: '/nolus.tax.v2.Query/Params',
data: requestData,
prove: true,
};
const response = await client.abciQuery(query);
const paramsResponse = QueryParamsResponse.decode(response.value);
return paramsResponse;
}
}