# Contract interactions

The Toucan SDK provides you with several useful tools to quickly redeem and retire carbon credits programmatically. In case you can't find the function that you need with the Toucan SDK, you can also directly interact with the [contracts](https://github.com/ToucanProtocol/contracts).

## OffsetHelper related methods

The OffsetHelper combines these steps in each of the following "auto offset" methods to allow carbon credit retirement (offsetting) within one transaction:

1. Obtain a pool token such as NCT (by performing a token swap)
2. Redeem the pool token for a TCO2 token
3. Retire the TCO2 token

### autoOffsetPoolToken

The `autoOffsetPoolToken` retires carbon credits using the lowest quality (oldest) TCO2 tokens available from the specified carbon pool. This method does not include a token swap — the user must already hold reference tokens. All provided reference tokens are consumed for offsetting.

This method may take up to 1 minute to return a result. It returns the redeem transaction.

{% hint style="info" %}
When automatically redeeming pool tokens for the lowest quality TCO2s there are no fees — you receive exactly 1 TCO2 token for 1 reference token.

Also, note that "Pool Token" in the method name refers to "[carbon reference token](https://docs.toucan.earth/toucan/carbon-pools#so-what-is-a-carbon-pool)".
{% endhint %}

```typescript
function autoOffsetPoolToken(
  pool: PoolSymbol,
  amount: BigNumber
): Promise<ContractReceipt>;
```

#### Params

| Name     | Type         | Description                                                     |
| -------- | ------------ | --------------------------------------------------------------- |
| `pool`   | `PoolSymbol` | symbol of the carbon reference token to offset with, e.g. `NCT` |
| `amount` | `BigNumber`  | amount of TCO2 tokens to redeem and retire                      |

### autoOffsetExactInToken

The `autoOffsetExactInToken` extends the functionality described in `autoOffsetPoolToken` by including a step to swap another token, like USDC, WETH or WMATIC, for the carbon reference tokens.

{% hint style="info" %}
This method allows you to specify exactly how many tokens you want to use to swap and retire — i.e. how many USDC, WETH or WMATIC tokens you want to spend.

The `autoOffsetExactOutToken` allows you to specify exactly how many carbon reference tokens you want to swap for, redeem and retire. The amount of `swapTokens` needed will be found using calculation methods described below.

* With `autoOffsetExactInToken`, you know how much you'll spend, but not how many TCO2 tokens will be retired
* With `autoOffsetExactOutToken`, you know how many TCO2 tokens will be retired, but not how much you'll spend
  {% endhint %}

After the swap is completed, subsequent steps are the same as above. This method may take up to 1 minute to return a result. It returns the redeem transaction.

```typescript
function autoOffsetExactInToken(
  swapToken: string,
  pool: PoolSymbol,
  amount: BigNumber
): Promise<ContractReceipt>;
```

#### Params

| Name        | Type                                  | Description                                                                                             |
| ----------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `swapToken` | `string` — `WETH`, `WMATIC` or `USDC` | The ticker for the token to swap into carbon reference tokens                                           |
| `pool`      | `PoolSymbol` e.g. `NCT`               | symbol of the carbon reference token to use                                                             |
| `amount`    | `BigNumber`                           | the amount of ERC20 token to swap into carbon reference token. Full amount will be used for offsetting. |

### autoOffsetExactOutToken

The `autoOffsetExactOutToken` retires a specified amount of carbon credits using the lowest quality (oldest) TCO2 tokens available from the specified token pool by sending ERC20 tokens (cUSD, USDC, WETH, WMATIC). This method may take up to 1 minute to return a result. It returns the offset transaction.

```typescript
function autoOffsetExactOutToken(
  swapToken: string,
  pool: PoolSymbol,
  amount: BigNumber
): Promise<ContractReceipt>;
```

#### Params

| Name        | Type                                  | Description                                                                            |
| ----------- | ------------------------------------- | -------------------------------------------------------------------------------------- |
| `swapToken` | `string` — `WETH`, `WMATIC` or `USDC` | The ticker for the token to swap into pool tokens (only accepts WETH, WMATIC and USDC) |
| `pool`      | `PoolSymbol` e.g. `NCT`               | Symbol of the carbon reference token to use                                            |
| `amount`    | `BigNumber`                           | Amount of TCO2 tokens to retire                                                        |

### autoOffsetExactInETH

Same as `autoOffsetExactInToken`, but the `autoOffsetExactInETH` swaps the blockchain's native token for carbon reference tokens, instead of allowing you to specify the `swapToken`.

{% hint style="info" %}
**Note:** While this method refers to "ETH", it actually will use WMATIC on Polygon. The function is not currently available on Celo.
{% endhint %}

This method may take up to 1 minute to return a result. It returns the offset transaction.

```typescript
function autoOffsetExactInETH(
  pool: PoolSymbol,
  amount: BigNumber
): Promise<ContractReceipt>;
```

#### Params

| Name     | Type                    | Description                                                                                                                                               |
| -------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pool`   | `PoolSymbol` e.g. `NCT` | Ticker symbol of the carbon reference token to acquire and redeem                                                                                         |
| `amount` | `BigNumber`             | The amount of native tokens e.g., MATIC to swap into Toucan carbon reference tokens. The full amount of redeemed TCO2 tokens will be used for offsetting. |

### autoOffsetExactOutETH

Same as `autoOffsetExactOutToken`, but the `autoOffsetExactOutETH` swaps the blockchain's native token for carbon reference tokens, instead of allowing you to specify the `swapToken`.

{% hint style="info" %}
Note that while this method refers to "ETH", it actually will use WMATIC on Polygon. The function is not currently available on Celo.
{% endhint %}

This method may take up to 1 minute to return a result. It returns the offset transaction.

```typescript
function autoOffsetExactInETH(
  pool: PoolSymbol,
  amount: BigNumber
): Promise<ContractReceipt>;
```

#### Params

| Name     | Type                    | Description                                                       |
| -------- | ----------------------- | ----------------------------------------------------------------- |
| `pool`   | `PoolSymbol` e.g. `NCT` | Ticker symbol of the carbon reference token to acquire and redeem |
| `amount` | `BigNumber`             | The amount of TCO2 tokens to retire                               |

### calculateExpectedPoolTokenForToken

Calculates and returns the expected amount of carbon references tokens that can be acquired by swapping the provided amount of ERC20 token.

```typescript
function calculateExpectedPoolTokenForToken(
  swapToken: string,
  pool: PoolSymbol,
  amount: BigNumber
): Promise<BigNumber>;
```

#### Params

| Name        | Type                                  | Description                                      |
| ----------- | ------------------------------------- | ------------------------------------------------ |
| `swapToken` | `string` — `WETH`, `WMATIC` or `USDC` | The ERC20 token used for the swap                |
| `pool`      | `PoolSymbol` e.g. `NCT`               | Symbol of the carbon reference token to swap for |
| `amount`    | `BigNumber`                           | The amount of ERC20 token to swap                |

### calculateExpectedPoolTokenForETH

Calculates and returns the expected amount of carbon references tokens that can be acquired by swapping the provided amount of native token.

{% hint style="info" %}
Note that while this method refers to "ETH", it actually will use WMATIC on Polygon. The function is not currently available on Celo.
{% endhint %}

```typescript
function calculateExpectedPoolTokenForETH(
  pool: PoolSymbol,
  amount: BigNumber
): Promise<BigNumber>;
```

#### Params

| Name     | Type                    | Description                                       |
| -------- | ----------------------- | ------------------------------------------------- |
| `pool`   | `PoolSymbol` e.g. `NCT` | Symbol of the carbon reference token to swap for  |
| `amount` | `BigNumber`             | Amount of native tokens to swap for, e.g., WMATIC |

### calculateNeededTokenAmount

Calculates how much of the specified ERC20 token is required in order to swap for the desired amount of a specified carbon reference token.

```typescript
function calculateNeededTokenAmount(
  swapToken: string,
  pool: PoolSymbol,
  amount: BigNumber
): Promise<BigNumber>;
```

#### Params

| Name        | Type                                  | Description                                             |
| ----------- | ------------------------------------- | ------------------------------------------------------- |
| `swapToken` | `string` — `WETH`, `WMATIC` or `USDC` | The ERC20 token used for the swap                       |
| `pool`      | `PoolSymbol` e.g. `NCT`               | Symbol of the pool token to swap for                    |
| `amount`    | `BigNumber`                           | The desired amount of carbon reference token to receive |

### calculateNeededETHAmount

Calculates the amount of native tokens (e.g, MATIC) required to swap for the desired amount of a carbon reference token, e.g., NCT.

```typescript
function calculateNeededETHAmount(
  pool: PoolSymbol,
  amount: BigNumber
): Promise<BigNumber>;
```

#### Params

| Name     | Type                    | Description                                              |
| -------- | ----------------------- | -------------------------------------------------------- |
| `pool`   | `PoolSymbol` e.g. `NCT` | Symbol of the pool token to swap for                     |
| `amount` | `BigNumber`             | The desired amount of carbon reference tokens to receive |

## TCO2 related methods

### retire

The `retire` function retires an amount of TCO2 tokens and returns the retirement transaction.

```typescript
function retire(
  amount: BigNumber,
  tco2Address: string
): Promise<ContractReceipt>;
```

#### Params

| Name          | Type        | Description                         |
| ------------- | ----------- | ----------------------------------- |
| `amount`      | `BigNumber` | Amount of TCO2 tokens to retire     |
| `tco2Address` | `string`    | Address of the TCO2 token to retire |

### retireFrom

The `retireFrom` function retires an amount of TCO2 tokens from a different address/wallet. The function requires approval from the address you're trying to retire from. If you don't own any TCO2s you need to buy pool tokens, e.g., NCTs on a DEX and redeem these first. It returns the retirement transaction.

```typescript
function retireFrom(
  amount: BigNumber,
  address: string,
  tco2Address: string
): Promise<ContractReceipt>;
```

#### Params

| Name          | Type        | Description                                  |
| ------------- | ----------- | -------------------------------------------- |
| `amount`      | `BigNumber` | Amount of TCO2 tokens to retire              |
| `address`     | `string`    | Address of the account to retire from        |
| `tco2Address` | `string`    | Contract address of the TCO2 token to retire |

### retireAndMintCertificate

The `retireAndMintCertificate` function retires an amount of TCO2s & mints the NFT `RetirementCertificate` for it within the same transaction. If you don't own any TCO2s you need to buy pool tokens, e.g., NCTs on a DEX and redeem these first. It returns the retirement transaction.

```typescript
function retireAndMintCertificate(
  retirementEntityName: string,
  beneficiaryAddress: string,
  beneficiaryName: string,
  retirementMessage: string,
  amount: BigNumber,
  tco2Address: string
): Promise<ContractReceipt>;
```

#### Params

| Name                   | Type        | Description                                                           |
| ---------------------- | ----------- | --------------------------------------------------------------------- |
| `retirementEntityName` | `string`    | Name of the entity that does the retirement (i.e. you)                |
| `beneficiaryAddress`   | `string`    | Address of the beneficiary (in case you're retiring for someone else) |
| `beneficiaryName`      | `string`    | Name of the beneficiary                                               |
| `retirementMessage`    | `string`    | Retirement message                                                    |
| `amount`               | `BigNumber` | Amount of TCO2 tokens to retire                                       |
| `tco2Address`          | `string`    | Contract address of the TCO2 token to retire                          |

### getDepositCap

The `getDepositCap` function gets the cap for TCO2s based on `totalVintageQuantity`.

```typescript
function getDepositCap(tco2Address: string): Promise<BigNumber>;
```

#### Params

| Name          | Type     | Description                        |
| ------------- | -------- | ---------------------------------- |
| `tco2Address` | `string` | Contract address of the TCO2 token |

### getAttributes

The `getAttributes` function retrieves the attributes of the TCO2 token. It returns an array of attributes including vintage and project details.

```typescript
function getAttributes(tco2Address: string): Promise<Attributes>;
```

#### Params

| Name          | Type     | Description                        |
| ------------- | -------- | ---------------------------------- |
| `tco2Address` | `string` | Contract address of the TCO2 token |

Return values are described in the [smart contract docs for the `getAttributes` function ->](https://docs.toucan.earth/smart-contracts/tco2#getattributes)

### getTCO2Remaining

The `getTCO2Remaining` function gets the remaining space in TCO2 contract before hitting the deposit cap. It returns a `BigNumber` representing the remaining space.

```typescript
function getTCO2Remaining(tco2Address: string): Promise<BigNumber>;
```

#### Params

| Name          | Type     | Description                        |
| ------------- | -------- | ---------------------------------- |
| `tco2Address` | `string` | Contract address of the TCO2 token |

## Pool related methods

### depositTCO2

The `depositTCO2` function deposits TCO2 tokens from a user's account into a carbon pool and mints and deposits an equivalent number of the pool's reference tokens back into the user's account. It returns returns the deposit transaction.

```typescript
function depositTCO2(
  pool: PoolSymbol,
  amount: BigNumber,
  tco2Address: string
): Promise<ContractReceipt>;
```

#### Params

| Name          | Type                    | Description                        |
| ------------- | ----------------------- | ---------------------------------- |
| `pool`        | `PoolSymbol` e.g. `NCT` | Symbol of the pool (token) to use  |
| `amount`      | `BigNumber`             | Amount of TCO2 tokens to deposit   |
| `tco2Address` | `string`                | Contract address of the TCO2 token |

### checkEligible

The `checkEligible` function checks if a TCO2 is eligible for pool. It returns a boolean.

```typescript
function checkEligible(pool: PoolSymbol, tco2Address: string): Promise<boolean>;
```

#### Params

| Name          | Type                    | Description                                 |
| ------------- | ----------------------- | ------------------------------------------- |
| `pool`        | `PoolSymbol` e.g. `NCT` | Symbol of the pool to check against         |
| `tco2Address` | `string`                | Contract address of the TCO2 token to check |

## redeemAuto

The `redeemAuto` function automatically redeems TCO2 tokens from the pool up to the deposit cap. It returns the redemption transaction, which returns an array containing TCO2 contract addresses (`string`) and amounts (`BigNumber`).

```typescript
function redeemAuto(
  pool: PoolSymbol,
  amount: BigNumber
): Promise<ContractReceipt>;
```

#### Params

| Name     | Type                    | Description                                 |
| -------- | ----------------------- | ------------------------------------------- |
| `pool`   | `PoolSymbol` e.g. `NCT` | Symbol of the pool redeem from              |
| `amount` | `BigNumber`             | Amount of carbon reference tokens to redeem |

## redeemAuto2 \[deprecated]

```typescript
function redeemAuto2(
  pool: PoolSymbol,
  amount: BigNumber
): Promise<ContractReceipt>;
```

This function is deprecated. Use `redeemAuto` instead.

#### Params

| Name     | Type                    | Description                                 |
| -------- | ----------------------- | ------------------------------------------- |
| `pool`   | `PoolSymbol` e.g. `NCT` | Symbol of the pool to redeem from           |
| `amount` | `BigNumber`             | Amount of carbon reference tokens to redeem |

### redeemMany

The `redeemMany` function redeems carbon reference tokens for specified TCO2 tokens in specified amounts in a single transaction. It returns the redeem transaction.

```typescript
function redeemMany(
  pool: PoolSymbol,
  tco2Addresses: string[],
  amounts: BigNumber[]
): Promise<ContractReceipt>;
```

#### Params

| Name            | Type                    | Description                                        |
| --------------- | ----------------------- | -------------------------------------------------- |
| `pool`          | `PoolSymbol` e.g. `NCT` | Symbol of the pool to redeem from                  |
| `tco2Addresses` | `string[]`              | Array of TCO2 contract addresses                   |
| `amounts`       | `BigNumber[]`           | Array of amounts of TCO2 tokens to redeem for each |

{% hint style="success" %}
The `tco2Addresses` and `amounts` arrays must be of equal length, and align based on index, i.e. "Redeem `amounts[4]` tokens from TCO2 contract address `tco2Addresses[4]`."
{% endhint %}

### calculateRedeemFees

The `calculateRedeemFees` function calculates the fees to selectively redeem carbon reference tokens for TCO2s. It returns amount (`BigNumber`) of fees it will cost to redeem. [Fees](https://docs.toucan.earth/toucan/carbon-pools/char-carbon-pool#pool-health-fee) are levied in the pool's reference token.

```typescript
function calculateRedeemFees(
  pool: PoolSymbol,
  tco2Addresses: string[],
  amounts: BigNumber[]
): Promise<FeeCalculationResult>;
```

#### Params

| Name            | Type                    | Description                               |
| --------------- | ----------------------- | ----------------------------------------- |
| `pool`          | `PoolSymbol` e.g. `NCT` | Symbol of the pool (token) to use         |
| `tco2Addresses` | `string[]`              | Array of TCO2 contract addresses          |
| `amounts`       | `BigNumber[]`           | Array of amounts of TCO2 tokens to redeem |

### getPoolRemaining

The `getPoolRemaining` function gets the remaining space in pool contract before hitting the cap, i.e. `supplyCap - totalSupply`. It returns `BigNumber` representing the remaining space in the pool.

```typescript
function getPoolRemaining(pool: PoolSymbol): Promise<BigNumber>;
```

#### Params

| Name   | Type                    | Description                         |
| ------ | ----------------------- | ----------------------------------- |
| `pool` | `PoolSymbol` e.g. `NCT` | Symbol of the pool (token) to check |

### getScoredTCO2s

The `getScoredTCO2s` function gets an array of TCO2s ordered by score for a specific pool; `scoredTCO2s[0]` is lowest ranked. It returns an array of TCO2 addresses by rank.

```typescript
function getScoredTCO2s(pool: PoolSymbol): Promise<string[]>;
```

#### Params

| Name   | Type                    | Description                       |
| ------ | ----------------------- | --------------------------------- |
| `pool` | `PoolSymbol` e.g. `NCT` | Symbol of the pool (token) to use |

## Contract registry related methods

### checkIfTCO2

The `checkIfTCO2` function checks if an address represents a TCO2. It returns a `boolean`.

```typescript
function checkIfTCO2(address: string): Promise<boolean>;
```

#### Params

| Name      | Type     | Description                            |
| --------- | -------- | -------------------------------------- |
| `address` | `string` | Contract address of the token to check |

## Interact directly with Toucan's contracts

If you need to interact with a method of our [contracts](https://github.com/ToucanProtocol/contracts) that hasn't been implemented in the SDK yet, you can also connect directly to the contract and call the specific function. Learn more about smart contract functions in [Carbon pool contracts](https://docs.toucan.earth/developers/smart-contracts/pool-contracts), [TCO2 Contracts](https://docs.toucan.earth/developers/smart-contracts/tco2) and the [OffsetHelper](https://docs.toucan.earth/developers/smart-contracts/offset-helper) docs.

{% hint style="info" %}
It's important to note that if you want to use write methods you need to have a `signer` set in the Toucan Client!
{% endhint %}

### getPoolAddress

The `getPoolAddress` function returns the address of a Toucan pool.

```typescript
function getPoolAddress(pool: PoolSymbol): string;
```

#### Params

| Name   | Type                    | Description        |
| ------ | ----------------------- | ------------------ |
| `pool` | `PoolSymbol` e.g. `NCT` | Symbol of the pool |

### getPoolContract

The `getPoolContract` function retrieves an `ethers.Contract` object based on the pool symbol.

```typescript
function getPoolContract(pool: PoolSymbol): IToucanPoolToken;
```

#### Params

| Name   | Type                    | Description                       |
| ------ | ----------------------- | --------------------------------- |
| `pool` | `PoolSymbol` e.g. `NCT` | Symbol of the pool (token) to use |

### getTCO2Contract

The `getTCO2Contract` function retrieves an `ethers.Contract` object based on the TCO2 contract address.

```typescript
function getTCO2Contract(tco2Address: string): IToucanCarbonOffsets;
```

#### Params

| Name          | Type     | Description                                                             |
| ------------- | -------- | ----------------------------------------------------------------------- |
| `tco2Address` | `string` | Address of TCO2 contract to instantiate an `ethers.Contract` object for |

### getRegistryContract

The `getRegistryContract` function retrieves an `ethers.Contract` to interact with the contract registry.

```typescript
function getRegistryContract(): IToucanContractRegistry;
```

### Examples

You can always access any method or property of pool and TCO2 contracts by first getting and storing them in a variable, like this:

```typescript
toucan.setSigner(signer);

const nct = await toucan.getPoolContract("NCT");
const tco2 = await toucan.getTCO2Contract(tco2Address);
const registry = await toucan.getRegistryContract();
const remainingTCO2 = await nct.tokenBalances(tco2Address);
```
