or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdbalance-tracking.mdconstants-utilities.mdevent-testing.mdindex.mdrevert-testing.mdtime-manipulation.md

constants-utilities.mddocs/

0

# Constants and Utilities

1

2

Common Ethereum constants and utility functions for conversions, interface IDs, and transaction sending. Essential building blocks for smart contract testing.

3

4

## Capabilities

5

6

### Ethereum Constants

7

8

Common constants used in Ethereum smart contract development.

9

10

```javascript { .api }

11

const constants = {

12

/**

13

* Zero address - commonly used as null address

14

* @type {string}

15

*/

16

ZERO_ADDRESS: '0x0000000000000000000000000000000000000000',

17

18

/**

19

* Zero bytes32 value - commonly used as null bytes32

20

* @type {string}

21

*/

22

ZERO_BYTES32: '0x0000000000000000000000000000000000000000000000000000000000000000',

23

24

/**

25

* Maximum uint256 value (2^256 - 1)

26

* @type {BN}

27

*/

28

MAX_UINT256: BN,

29

30

/**

31

* Maximum int256 value (2^255 - 1)

32

* @type {BN}

33

*/

34

MAX_INT256: BN,

35

36

/**

37

* Minimum int256 value (-2^255)

38

* @type {BN}

39

*/

40

MIN_INT256: BN,

41

};

42

```

43

44

**Usage Examples:**

45

46

```javascript

47

const { constants, expectRevert } = require('@openzeppelin/test-helpers');

48

49

// Test zero address validation

50

await expectRevert(

51

token.transfer(constants.ZERO_ADDRESS, 100),

52

'ERC20: transfer to the zero address'

53

);

54

55

// Test maximum values

56

await token.approve(spender, constants.MAX_UINT256);

57

58

// Test with zero bytes32

59

await myContract.setData(constants.ZERO_BYTES32);

60

```

61

62

### Ether Conversion

63

64

Convert ether amounts to wei for precise calculations.

65

66

```javascript { .api }

67

/**

68

* Convert ether amount to wei as BigNumber

69

* @param {string|number} n - Amount in ether

70

* @returns {BN} - Amount in wei as BigNumber

71

*/

72

function ether(n);

73

```

74

75

**Usage Examples:**

76

77

```javascript

78

const { ether, BN } = require('@openzeppelin/test-helpers');

79

80

// Convert ether to wei

81

const oneEther = ether('1');

82

console.log(oneEther.toString()); // "1000000000000000000"

83

84

// Use in transactions

85

await contract.deposit({ value: ether('0.5') });

86

87

// Compare with BN

88

const halfEther = new BN('500000000000000000');

89

expect(ether('0.5')).to.be.bignumber.equal(halfEther);

90

91

// Use in calculations

92

const totalValue = ether('1.5').add(ether('2.3'));

93

expect(totalValue).to.be.bignumber.equal(ether('3.8'));

94

```

95

96

### Interface ID Generation

97

98

Generate interface IDs for ERC165 and ERC1820 standards.

99

100

```javascript { .api }

101

/**

102

* Generate ERC165 interface ID from function signatures

103

* @param {string[]} functionSignatures - Array of function signature strings

104

* @returns {string} - 4-byte interface ID as hex string

105

*/

106

function makeInterfaceId.ERC165(functionSignatures = []);

107

108

/**

109

* Generate ERC1820 interface hash from interface name

110

* @param {string} interfaceName - Name of the interface

111

* @returns {string} - 32-byte interface hash as hex string

112

*/

113

function makeInterfaceId.ERC1820(interfaceName);

114

```

115

116

**Usage Examples:**

117

118

```javascript

119

const { makeInterfaceId } = require('@openzeppelin/test-helpers');

120

121

// Generate ERC165 interface ID for ERC721

122

const ERC721InterfaceId = makeInterfaceId.ERC165([

123

'balanceOf(address)',

124

'ownerOf(uint256)',

125

'approve(address,uint256)',

126

'getApproved(uint256)',

127

'setApprovalForAll(address,bool)',

128

'isApprovedForAll(address,address)',

129

'transferFrom(address,address,uint256)',

130

'safeTransferFrom(address,address,uint256)',

131

'safeTransferFrom(address,address,uint256,bytes)',

132

]);

133

134

console.log('ERC721 Interface ID:', ERC721InterfaceId); // "0x80ac58cd"

135

136

// Test interface support

137

const supportsInterface = await nft.supportsInterface(ERC721InterfaceId);

138

expect(supportsInterface).to.equal(true);

139

140

// Generate ERC1820 interface hash

141

const ERC777TokensRecipientHash = makeInterfaceId.ERC1820('ERC777TokensRecipient');

142

console.log('ERC777TokensRecipient Hash:', ERC777TokensRecipientHash);

143

```

144

145

### Transaction Sending Utilities

146

147

Low-level transaction sending utilities for custom scenarios.

148

149

```javascript { .api }

150

/**

151

* Send ether from one address to another

152

* @param {string} from - Sender address

153

* @param {string} to - Recipient address

154

* @param {BN|string|number} value - Amount to send in wei

155

* @returns {Promise<TransactionReceipt>} - Transaction receipt

156

*/

157

async function send.ether(from, to, value);

158

159

/**

160

* Send a transaction to call a contract function

161

* @param {ContractInstance} target - Contract instance to call

162

* @param {string} name - Function name to call

163

* @param {string} argsTypes - Comma-separated argument types

164

* @param {any[]} argsValues - Array of argument values

165

* @param {object} opts - Transaction options (from, gas, etc.)

166

* @returns {Promise<TransactionReceipt>} - Transaction receipt

167

*/

168

async function send.transaction(target, name, argsTypes, argsValues, opts = {});

169

```

170

171

**Usage Examples:**

172

173

```javascript

174

const { send, ether } = require('@openzeppelin/test-helpers');

175

176

// Send ether between accounts

177

await send.ether(sender, recipient, ether('1'));

178

179

// Call contract function with encoded parameters

180

await send.transaction(

181

myContract,

182

'transfer',

183

'address,uint256',

184

[recipient, ether('100')],

185

{ from: sender }

186

);

187

188

// Advanced transaction with custom gas

189

await send.transaction(

190

complexContract,

191

'complexFunction',

192

'uint256[],string,bool',

193

[[1, 2, 3], 'hello', true],

194

{ from: sender, gas: 200000 }

195

);

196

```

197

198

## Practical Examples

199

200

### Testing ERC165 Interface Support

201

202

```javascript

203

const { makeInterfaceId } = require('@openzeppelin/test-helpers');

204

205

contract('MyNFT', function () {

206

it('should support required interfaces', async function () {

207

// ERC165

208

const ERC165InterfaceId = makeInterfaceId.ERC165(['supportsInterface(bytes4)']);

209

expect(await this.nft.supportsInterface(ERC165InterfaceId)).to.equal(true);

210

211

// ERC721

212

const ERC721InterfaceId = makeInterfaceId.ERC165([

213

'balanceOf(address)',

214

'ownerOf(uint256)',

215

'approve(address,uint256)',

216

'getApproved(uint256)',

217

'setApprovalForAll(address,bool)',

218

'isApprovedForAll(address,address)',

219

'transferFrom(address,address,uint256)',

220

'safeTransferFrom(address,address,uint256)',

221

'safeTransferFrom(address,address,uint256,bytes)',

222

]);

223

expect(await this.nft.supportsInterface(ERC721InterfaceId)).to.equal(true);

224

});

225

});

226

```

227

228

### Testing with Maximum Values

229

230

```javascript

231

const { constants, expectRevert, ether } = require('@openzeppelin/test-helpers');

232

233

contract('Token', function ([owner, user]) {

234

it('should handle maximum approvals', async function () {

235

// Approve maximum amount

236

await this.token.approve(user, constants.MAX_UINT256, { from: owner });

237

238

const allowance = await this.token.allowance(owner, user);

239

expect(allowance).to.be.bignumber.equal(constants.MAX_UINT256);

240

});

241

242

it('should reject zero address operations', async function () {

243

await expectRevert(

244

this.token.transfer(constants.ZERO_ADDRESS, ether('1')),

245

'ERC20: transfer to the zero address'

246

);

247

248

await expectRevert(

249

this.token.approve(constants.ZERO_ADDRESS, ether('1')),

250

'ERC20: approve to the zero address'

251

);

252

});

253

});

254

```

255

256

### Custom Transaction Scenarios

257

258

```javascript

259

const { send, ether, expectEvent } = require('@openzeppelin/test-helpers');

260

261

contract('PaymentSplitter', function ([owner, beneficiary1, beneficiary2]) {

262

it('should handle direct ether transfers', async function () {

263

// Send ether directly to contract

264

const receipt = await send.ether(

265

owner,

266

this.splitter.address,

267

ether('1')

268

);

269

270

// Check for payment received event

271

await expectEvent.inTransaction(

272

receipt.transactionHash,

273

this.splitter,

274

'PaymentReceived',

275

{ from: owner, amount: ether('1') }

276

);

277

});

278

});

279

```

280

281

## Constants Reference

282

283

### Numeric Constants

284

285

```javascript

286

// All constants are BigNumber instances

287

constants.MAX_UINT256.toString(); // "115792089237316195423570985008687907853269984665640564039457584007913129639935"

288

constants.MAX_INT256.toString(); // "57896044618658097711785492504343953926634992332820282019728792003956564819967"

289

constants.MIN_INT256.toString(); // "-57896044618658097711785492504343953926634992332820282019728792003956564819968"

290

```

291

292

### String Constants

293

294

```javascript

295

constants.ZERO_ADDRESS; // "0x0000000000000000000000000000000000000000"

296

constants.ZERO_BYTES32; // "0x0000000000000000000000000000000000000000000000000000000000000000"

297

```