forked from totallyswede/cosmos-stake-bot
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvote.ts
233 lines (181 loc) · 8.26 KB
/
vote.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
import { E6,IAccountConfiguration, IChainConfiguration, GenerateFee} from "./common";
import { cosmosclient, rest, proto } from 'cosmos-client';
import { AccAddress } from 'cosmos-client/cjs/types';
import {
QueryClient, setupGovExtension, setupBankExtension, SigningStargateClient, BankExtension, GovExtension
} from "@cosmjs/stargate";
import { DirectSecp256k1HdWallet, Registry } from "@cosmjs/proto-signing";
import { HdPath, stringToPath } from "@cosmjs/crypto";
import { setBech32NetworkPrefix } from 'cosmos-client/esm/types/address/config'
import { Tendermint34Client } from '@cosmjs/tendermint-rpc';
import { coins, Secp256k1HdWallet } from '@cosmjs/launchpad'
const statusVoting = 2; //Voting Period
const VOTE_OPTION_UNSPECIFIED = 0; //no-op
const VOTE_OPTION_YES = 1; //YES
const VOTE_OPTION_ABSTAIN = 2;//abstain
const VOTE_OPTION_NO = 3;//NO
const VOTE_OPTION_NO_WITH_VETO = 4;//No with veto
interface IClientInfos {
rest : cosmosclient.CosmosSDK,
rpc : SigningStargateClient,
restAddress: AccAddress
}
const chainConfigs = require('./chainConfigs.json') as IChainConfiguration[];
const accountConfigs = require('./accountConfigs.json') as IAccountConfiguration[];
async function getQueryClient(rpcEndpoint:string) {
const tendermint34Client = await Tendermint34Client.connect(rpcEndpoint);
const queryClient = QueryClient.withExtensions(
tendermint34Client,
setupBankExtension,
setupGovExtension
);
return queryClient;
}
function hasVoted(client: any, proposalId:string, address:string) {
return new Promise(async (resolve) => {
client.gov.vote(proposalId, address).then(res => {
resolve(res)
}).catch(err => {
resolve(false)
})
})
}
async function voteProposal(client:any, config:IChainConfiguration, proposalId:string, address:string, option:number, acountName:string) {
let ops = [];
let msg = {
typeUrl: "/cosmos.gov.v1beta1.MsgVote",
value: {
proposalId: proposalId,
voter: address,
option: option
},
};
ops.push(msg);
let min_tx_fee = "0";
if(config.tokenDenom == "uhuahua") {
min_tx_fee = config.min_tx_fee;
}
const fee = {
amount: coins(min_tx_fee, config.tokenDenom),
gas: "" + config.gas,
};
console.log(`${acountName}==>${address} is ready to vote on ${config.chainName} proposal #${proposalId}`);
let result = await client.signAndBroadcast(address, ops, fee, '');
if (result.code == 0) {
console.log(`${acountName}==>${address} voted ${config.chainName} proposal #${proposalId}`);
} else {
console.log(`${acountName}==>${address} failed to vote on ${config.chainName} proposal #${proposalId}`);
}
}
async function start(accountConfig :IAccountConfiguration, config: IChainConfiguration) {
const rpcEndpoint = config.rpcEndpoint;
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(accountConfig.mnemonic, { prefix: config.walletPrefix, hdPaths: config.customDerivationPath ? [stringToPath(config.customDerivationPath)] : undefined });
setBech32NetworkPrefix( config.walletPrefix );
// const wallet = await Secp256k1HdWallet.fromMnemonic(
// mnemonic,
// {
// prefix: chain.prefix
// }
// );
const [account] = await wallet.getAccounts();
const client = await SigningStargateClient.connectWithSigner(rpcEndpoint, wallet);
const queryClient = await getQueryClient(rpcEndpoint);
// let balance = await queryClient.bank.balance(account.address, config.tokenDenom);
const stakingBalance = TokenStakeAmounts[accountConfig.accountName + "_" + config.tokenDenom];
if (stakingBalance / E6 > 1) {
console.log(accountConfig.accountName + "_" + config.tokenDenom + "_" + String(stakingBalance));
const proposalsVoting = await queryClient.gov.proposals(statusVoting, "", "");
// console.log(proposalsVoting);
for (let proposal of proposalsVoting.proposals) {
let proposalId = proposal.proposalId.toString();
let voted = await hasVoted(queryClient, proposalId, account.address);
try {
if (!voted) {
await voteProposal(client, config, proposalId, account.address, VOTE_OPTION_YES, accountConfig.accountName);
}
} catch( error : any ) {
console.error(accountConfig.accountName)
if(error.message !== undefined)
console.error(accountConfig.accountName + "==>" + error.message);
else
console.error( error );
}
}
}
}
// let keys = process.env.MNEMONICS.split(',');
// for (const [k, chain] of Object.entries(chainMap)) {
// for (let key of keys) {
// start(key, chain);
// }
// }
const TokenStakeAmounts : Record<string, number> = {};
async function InitClients( config : IChainConfiguration,accountConfig :IAccountConfiguration) : Promise<IClientInfos> {
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(accountConfig.mnemonic, { prefix: config.walletPrefix, hdPaths: config.customDerivationPath ? [stringToPath(config.customDerivationPath)] : undefined });
const [account] = await wallet.getAccounts();
// console.log(account.address);
setBech32NetworkPrefix( config.walletPrefix );
const rpcClient = await SigningStargateClient.connectWithSigner(
config.rpcEndpoint,
wallet
);
const restClient = new cosmosclient.CosmosSDK(config.restEndpoint, config.networkName );
const privKey = new proto.cosmos.crypto.secp256k1.PrivKey({
key: await cosmosclient.generatePrivKeyFromMnemonic(accountConfig.mnemonic),
});
const pubKey = privKey.pubKey();
const address = cosmosclient.AccAddress.fromPublicKey(pubKey);
// console.log( `\nUsing wallet address ${address.toString()}`)
return {rest:restClient, rpc: rpcClient, restAddress: address };
}
//获取每个账户质押的token数量
async function GetStakingBalance(clients : IClientInfos, accountName: string) {
const delegations = await rest.staking
.delegatorDelegations( clients.rest, clients.restAddress )
.then( res => res.data.delegation_responses );
for(let item of delegations) {
TokenStakeAmounts[accountName + "_" + item.balance.denom] = Number(item.balance.amount);
}
}
async function main(){
try {
//query staking token amount
for( let accountConfig of accountConfigs ){
const chainNames = accountConfig.chainNames.split(',');
let index = 0;
for( let chainName of chainNames ){
const filteredConfigs = chainConfigs.filter( (c : IChainConfiguration) => c.chainName == chainName );
if(filteredConfigs === undefined || filteredConfigs.length == 0)
{
console.log(`\nCould not find configuration for chain by given name '${chainName}'! Continuing...`);
continue;
}
const config = filteredConfigs[0];
// const clients = await InitClients( config, parameters , accountConfig);
const clients = await InitClients( config, accountConfig);
await GetStakingBalance(clients, accountConfig.accountName);
}
}
console.log(TokenStakeAmounts);
for( let accountConfig of accountConfigs ){
// console.log(accountConfig.accountName);
const chainNames = accountConfig.chainNames.split(',');
for( let chainName of chainNames ){
const filteredConfigs = chainConfigs.filter( (c : IChainConfiguration) => c.chainName == chainName );
if(filteredConfigs === undefined || filteredConfigs.length == 0)
{
console.log(`\nCould not find configuration for chain by given name '${chainName}'! Continuing...`);
continue;
}
const config = filteredConfigs[0];
start(accountConfig, config);
}
}
}catch( error : any ) {
if(error.message !== undefined)
console.error(error.message);
else
console.error( error );
}
}
main();