-
Notifications
You must be signed in to change notification settings - Fork 1
/
gnosisSafe.js
275 lines (223 loc) · 9.32 KB
/
gnosisSafe.js
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
/*
- get an estimate for needed gas with safe.requiredTxGas() | can be skipped for the demo (hardcoded gas)
- get nonce with safe.nonce()
- get txHash with safe.getTransactionHash()
- get signatures
- sort signers alphabetically (TODO: case sensitive?)
- sign txHash
- return sigs concatenated (r,s,v), 0x prefixed
- execute with safe.execTransaction()
*/
const path = require('path');
const fs = require('fs');
// const Tx = require('ethereumjs-tx');
// const config = require('./config');
// const safeAbi = require('./GnosisSafe_abi');
const configLogDebug = true;
function logDebug(message) {
if (configLogDebug) {
console.log(message);
}
}
async function sendTx(web3, toAddress, encodedAbi, card) {
// Prepare the raw transaction information
const rawTx = {
// nonce: nonceHex,
gasPrice: web3.utils.toHex('100000000000'),
gas: '0x6691B7', // <- Ganache hardcoded gas limit
data: encodedAbi,
from: await card.getAddress(),
to: toAddress,
};
// const signature = await card.signTransaction(web3, rawTx, 1);
// logDebug(signature.toString('hex'));
// const txResult = await web3.eth.sendSignedTransaction(signature.toString('hex'));
const txResult = await web3.eth.sendTransaction(rawTx);
console.log('Transaction sent!');
return txResult;
}
async function deployContract(web3, contractName, card) {
const cardKeyIndex = 1;
// It will read the ABI & byte code contents from the JSON file in ./build/contracts/ folder
const jsonOutputName = `${path.parse(contractName).name}.json`;
const jsonFile = `./contracts/build/${jsonOutputName}`;
// Read the JSON file contents
const contractJsonContent = fs.readFileSync(jsonFile, 'utf8');
const jsonOutput = JSON.parse(contractJsonContent);
// Retrieve the ABI
const { abi } = jsonOutput;
// Retrieve the byte code
const { bytecode } = jsonOutput;
const contract = new web3.eth.Contract(abi);
const deployedContract = contract.deploy({ data: bytecode });
const encodedData = deployedContract.encodeABI();
const address = await card.getAddress(cardKeyIndex);
const nonceHex = web3.utils.toHex(await web3.eth.getTransactionCount(address));
logDebug(`nonceHex:${nonceHex}`);
// Prepare the raw transaction information
const rawTx = {
nonce: nonceHex,
gasPrice: web3.utils.toHex('100000000000'),
gas: '0x6691B7', // <- Ganache hardcoded gas limit
data: encodedData,
from: address,
};
// const signature = await card.signTransaction(web3, rawTx, cardKeyIndex);
// logDebug(signature.toString('hex'));
// const txResult = await web3.eth.sendSignedTransaction(signature.toString('hex'));
const txResult = await web3.eth.sendTransaction(rawTx);
logDebug('Contract deployed:');
logDebug(txResult);
logDebug('contract address:');
logDebug(txResult.contractAddress);
contract.address = txResult.contractAddress;
return contract;
}
function trim0x(hexStringInput) {
let hexString = hexStringInput;
if (hexString.startsWith('0x')) {
hexString = hexString.substring(2, hexString.length);
}
return hexString;
}
function fixLengthTo32Bytes(hexStringInput) {
let hexString = hexStringInput;
while (hexString.length > 64) {
if (hexString.startsWith('00')) {
hexString = hexString.substring(2, hexString.length);
} else {
throw Error(`unable to fix hexstring to length 32: ${hexString}`);
}
}
while (hexString.length < 64) {
hexString += '00';
}
return hexString;
}
function createGnosisSafeObject(web3, gnosisSafeAddress) {
const contractName = 'GnosisSafe';
const jsonOutputName = `${path.parse(contractName).name}.json`;
const jsonFile = `./contracts/build/${jsonOutputName}`;
// Read the JSON file contents
const contractJsonContent = fs.readFileSync(jsonFile, 'utf8');
const jsonOutput = JSON.parse(contractJsonContent);
// logDebug(jsonOutput);
// Retrieve the ABI
const { abi } = jsonOutput;
return new web3.eth.Contract(abi, gnosisSafeAddress);
}
module.exports = {
async deployNewSafe(web3, card) {
return deployContract(web3, 'GnosisSafe', card);
},
async setupSafe(web3, gnosisSafeAddress, addresses, numberOfRequiredAddresses, card) {
const gnosisSafeContract = createGnosisSafeObject(web3, gnosisSafeAddress);
const zeroAddress = '0x0000000000000000000000000000000000000000';
const setupEncodedAbi = gnosisSafeContract.methods.setup(
addresses, numberOfRequiredAddresses, zeroAddress/* to */, '0x0' /* data */,
zeroAddress /* address paymentToken */, '0x0' /* uint256 payment */,
zeroAddress, /* address payable paymentReceiver */
).encodeABI();
logDebug(`got encodedAbi for setup call: ${setupEncodedAbi}`);
const sendResult = await sendTx(web3, gnosisSafeAddress, setupEncodedAbi, card);
logDebug('got result: ');
logDebug(sendResult);
const ownerCall = await gnosisSafeContract.methods.getOwners().call();
logDebug('got owners:');
logDebug(ownerCall);
return sendResult;
},
async createGnosisSafeTransaction(web3, gnosisSafeAddress, toAddress, value) {
const gnosisSafe = createGnosisSafeObject(web3, gnosisSafeAddress);
const safeNonce = await gnosisSafe.methods.nonce().call();
console.log(`gnosisSafe Nonce:${safeNonce.toString('hex')}`);
const gnosisSafeTX = {
to: toAddress,
value,
data: '0x',
operation: 0,
safeTxGas: web3.utils.toHex('50000'),
baseGas: web3.utils.toHex('300000'),
gasPrice: '0x0',
gasToken: '0x0000000000000000000000000000000000000000',
refundReceiver: '0x0000000000000000000000000000000000000000',
nonce: web3.utils.toHex(safeNonce),
};
// const txHash = await safe.methods.getTransactionHash.apply(null, Object.values(txObj)).call();
// console.log(`txHash ${txHash}`);
return gnosisSafeTX;
},
async getGnosisSafeTransactionHash(web3, gnosisSafeAddress, gnosisSafeTransaction) {
const gnosisSafe = createGnosisSafeObject(web3, gnosisSafeAddress);
// console.log(gnosisSafeTransaction);
// console.log(gnosisSafeAddress);
const result = await gnosisSafe.methods.getTransactionHash(
gnosisSafeTransaction.to, gnosisSafeTransaction.value, gnosisSafeTransaction.data,
gnosisSafeTransaction.operation, gnosisSafeTransaction.safeTxGas,
gnosisSafeTransaction.baseGas, gnosisSafeTransaction.gasPrice,
gnosisSafeTransaction.gasToken, gnosisSafeTransaction.refundReceiver,
gnosisSafeTransaction.nonce,
).call();
return result;
},
async sendMultisigTransaction(
web3, card, gnosisSafeAddress,
multisigTransaction, multisigTransactionHash,
multisigCollected,
) {
console.log('sending multisig transaction.');
const safe = createGnosisSafeObject(web3, gnosisSafeAddress);
// console.log('gnosis safe created');
const signers = Object.keys(multisigCollected);
const sortedSigners = signers.sort();
// console.log(`signers (sorted): ${sortedSigners}`);
console.log(`Signers: ${JSON.stringify(signers)}`);
let sigString = '0x';
sortedSigners.forEach((address) => {
const sig = multisigCollected[address];
console.log(`appending signature from ${address}`);
// console.log(`type: ${typeof sig.r}`);
// console.log(sig.r);
// console.log(`r: ${sig.r.toString("hex")}, s: ${sig.s.toString("hex")}, v: ${sig.v.toString(16)}`);
//
const signaturePart = fixLengthTo32Bytes(trim0x(sig.r)) + fixLengthTo32Bytes(trim0x(sig.s)) + trim0x(sig.v);
console.log(`appending: ${signaturePart}`);
// r: 64 + s: 64 + v: 2 = 130 chars per signature.
if (signaturePart.length !== 130) {
throw Error('Expected string length of signature to be 130 (leading zero problem) ?');
}
sigString += signaturePart;
console.log(`sigString: ${sigString}`);
});
const execTxArgs = Object.values(multisigTransaction);
console.log(`before execTxArgs: ${execTxArgs}`);
// execTransaction doesn't need the last item (nonce), but instead needs the signatures
execTxArgs.splice(9, 1, sigString);
console.log(`after execTxArgs: ${execTxArgs}`);
// await safe.methods.execTransaction.apply(null, execTxArgs).send( { from: config.safe.executor.address } )
const execTxDataOld = safe.methods.execTransaction.apply(null, execTxArgs).encodeABI();
const execTxData = safe.methods.execTransaction(
multisigTransaction.to, multisigTransaction.value, multisigTransaction.data, multisigTransaction.operation,
multisigTransaction.safeTxGas, multisigTransaction.baseGas, multisigTransaction.gasPrice,
multisigTransaction.gasToken, multisigTransaction.refundReceiver, sigString,
).encodeABI();
if (execTxDataOld !== execTxData) {
console.error('Difference detected: ');
console.error(execTxData);
console.error(execTxDataOld);
}
const outerTxObj = {
// from: config.safe.executor.address,
to: gnosisSafeAddress,
data: execTxData,
gas: web3.utils.toHex('300000'),
gasPrice: web3.utils.toHex('100000000000'),
// chainId: 1 // if not set, it will fail for ganache due to eth_chainId not being supported
};
console.log(`Exec Data:${execTxData}`);
const execCallRet = await web3.eth.call(outerTxObj);
console.log(`execCallRet: ${execCallRet}`);
// console.log(`outerTxObj: ${JSON.stringify(outerTxObj, null, 2)}`);
return sendTx(web3, gnosisSafeAddress, execTxData, card);
},
};