-
Notifications
You must be signed in to change notification settings - Fork 1
/
NolusWallet.ts
365 lines (313 loc) · 12.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
import stargate, { DeliverTxResponse, isDeliverTxFailure, StdFee, calculateFee } 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';
/**
* 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, 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 = calculateFee(gas, ChainConstants.GAS_PRICE);
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 | 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 = calculateFee(gas, ChainConstants.GAS_PRICE);
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,
};
}
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);
}
}