Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support proxied contract calls #3184

Closed
wants to merge 9 commits into from
64 changes: 63 additions & 1 deletion packages/fuel-gauge/src/contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@ import {
Predicate,
PolicyType,
buildFunctionResult,
ReceiptType,
} from 'fuels';
import type { ScriptTransactionRequest, TransferParams } from 'fuels';
import type { ScriptTransactionRequest, TransactionResultCallReceipt, TransferParams } from 'fuels';
import { expectToThrowFuelError, ASSET_A, ASSET_B, launchTestNode } from 'fuels/test-utils';
import type { DeployContractConfig } from 'fuels/test-utils';

import {
CallTestContract,
CallTestContractFactory,
CoverageContract,
CoverageContractFactory,
ProxySrc14Contract,
ProxySrc14ContractFactory,
StorageTestContract,
StorageTestContractFactory,
} from '../test/typegen/contracts';
Expand Down Expand Up @@ -1111,4 +1116,61 @@ describe('Contract', () => {
expect(scriptGasLimit?.toNumber()).toBe(gasLimit);
expect(bn(maxFeePolicy?.data).toNumber()).toBe(maxFee);
});

it('can proper set a proxy contract and use it to call a target contract', async () => {
using launch = await launchTestNode({
contractsConfigs: [{ factory: CoverageContractFactory }],
});

const {
wallets: [wallet],
contracts: [coverageContract],
} = launch;

const proxyFactory = await ProxySrc14ContractFactory.deploy(wallet, {
storageSlots: ProxySrc14Contract.storageSlots,
});

const { contract: proxyContract } = await proxyFactory.waitForResult();

// Setting the contract target at the proxy
const call = await proxyContract.functions
.set_proxy_target({ bits: coverageContract.id.toB256() })
.call();

await call.waitForResult();

const proxyId = proxyContract.id;
const echoValuesId = coverageContract.id;

const proxiedConverageContract = new Contract(
echoValuesId,
CoverageContract.abi,
wallet,
proxyId
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we could just read this value from the SRC14 storage? Then we could just pass some { proxy: true } config and the user only needs to be aware of one contract ID that doesn't change.

Only issue is in the contract call, we'd first need to read the value, with a function call to proxy_target using the existing contract ID. Then, we'd perform the user dictated function call against the received contract ID.

Copy link
Contributor

@danielbate danielbate Sep 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could then possibly use the proxy flag to modify the Interface and merge the passed ABI with an SRC14 interface ABI?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@danielbate I was planning to solve this with Typegen. Since the flag [proxy] is available in the Forc file, then we could use it. So when connecting with the contract or deploying it, if the flag is present we can already handle things on the fly.

With that, I believe we solve the problem of having the user manually inform the proxy contract ID and avoid executing the call to read the target contract at the proxy contract, which would represent an additional dryRun since it is a read call.

About modifying the proxy contract Interface, I made a couple of tries but didn't succeed. Maybe I am missing something.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typegen is a good idea, will we still need a way for users to connect that haven't used a typegen factory though? Just a standard new Contract()?

Even with typegen though, how do we know the ID of the target contract without the dryRun, if it hasn't been deployed by us?

About modifying the proxy contract Interface, I made a couple of tries but didn't succeed. Maybe I am missing something.

Lets see if we can solve this later, not a massive deal as the user will ideally just want to call the target contract functions anyways.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even with typegen though, how do we know the ID of the target contract without the dryRun, if it hasn't been deployed by us?

@danielbate It seems the solution you idealize for this is different from the one that I am approaching. In the context described here, the user would have only in its hands the contract Proxy ID and wants to execute a contract call for the target proxy, and they do not have the ID of the deployed target contract, right?

This is why you are suggesting a way to modify the proxy contract interface using the target contract interface. Therefore the user would use just the proxy contract ID to execute the call, then, behind the scenes, we would:

1 - Instantiate the Proxy contract, using also the target contract JSON ABI to have all its existent functions.

2 - Execute a read only call to the Proxy contract to get the target contract ID

3 - Build the script for the contract with the Proxy contract ID and execute the actual contract call specified by the user.

Is that your proposal?

Copy link
Contributor

@danielbate danielbate Sep 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes exactly, well summarised. What do you think?

);

const echoAmount = 10;

const proxiedCall = await proxiedConverageContract.functions
.echo_u8(echoAmount)
.addContracts([proxyContract])
.call();

const {
value,
transactionResult: { receipts },
} = await proxiedCall.waitForResult();

const callReceipt = receipts.filter(
(receipt) => receipt.type === ReceiptType.Call
) as TransactionResultCallReceipt[];

// Ensure called contract was the proxy contract
expect(callReceipt.length).toBe(1);
expect(callReceipt[0].to).toBe(proxyId.toB256());

// Ensure returned value is the expected one
expect(value).toBe(echoAmount);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ members = [
"script-raw-slice",
"script-std-lib-string",
"script-str-slice",
"proxy-src14-contract",
"script-with-array",
"script-with-configurable",
"script-with-vector",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[project]
authors = ["Fuel Labs <contact@fuel.sh>"]
entry = "main.sw"
license = "Apache-2.0"
name = "proxy-src14-contract"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this have the proxy flag?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@danielbate Good catch.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From my investigation, I actually think the flag goes on the target contract. Not the SRC14 compliant contract.

[dependencies]
standards = { git = "https://github.com/FuelLabs/sway-standards", tag = "v0.6.1" }
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
contract;

use std::execution::run_external;
use standards::{src14::SRC14};

pub enum ProxyErrors {
TargetNotSet: (),
}

configurable {
INITIAL_TARGET: ContractId = ContractId::zero(),
}

storage {
SRC14 {
target: Option<ContractId> = None,
},
}

impl SRC14 for Contract {
#[storage(read, write)]
fn set_proxy_target(new_target: ContractId) {
storage::SRC14.target.write(Some(new_target));
}

#[storage(read)]
fn proxy_target() -> Option<ContractId> {
Some(storage::SRC14.target.read().unwrap_or(INITIAL_TARGET))
}
}

#[fallback]
#[storage(read)]
fn fallback() {
let target = storage::SRC14.target.read().unwrap_or(INITIAL_TARGET);
require(target.bits() != b256::zero(), ProxyErrors::TargetNotSet);
run_external(target)
}
1 change: 1 addition & 0 deletions packages/interfaces/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export abstract class AbstractProgram {

export abstract class AbstractContract extends AbstractProgram {
abstract id: AbstractAddress;
abstract proxyContractId?: AbstractAddress;
}

/**
Expand Down
4 changes: 3 additions & 1 deletion packages/program/src/contract-call-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,14 @@ export const getContractCallScript = (
const encodedArgs = arrayify(call.data);
let gasForwardedOffset = 0;

const contractId = call.proxyContractId || call.contractId;

// 1. Amount
scriptData.push(new BigNumberCoder('u64').encode(call.amount || 0));
// 2. Asset ID
scriptData.push(new B256Coder().encode(call.assetId?.toString() || ZeroBytes32));
// 3. Contract ID
scriptData.push(call.contractId.toBytes());
scriptData.push(contractId.toBytes());
// 4. Function selector offset
scriptData.push(new BigNumberCoder('u64').encode(encodedSelectorOffset));
// 5. Encoded argument offset
Expand Down
11 changes: 10 additions & 1 deletion packages/program/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ export default class Contract implements AbstractContract {
*/
id!: AbstractAddress;

/**
* Proxy contract identifier.
*/
proxyContractId?: AbstractAddress;

/**
* The provider for interacting with the contract.
*/
Expand Down Expand Up @@ -47,10 +52,14 @@ export default class Contract implements AbstractContract {
constructor(
id: string | AbstractAddress,
abi: JsonAbi | Interface,
accountOrProvider: Account | Provider
accountOrProvider: Account | Provider,
proxyContractId?: string | AbstractAddress
) {
this.interface = abi instanceof Interface ? abi : new Interface(abi);
this.id = Address.fromAddressOrString(id);
if (proxyContractId) {
this.proxyContractId = Address.fromAddressOrString(proxyContractId);
}

/**
Instead of using `instanceof` to compare classes, we instead check
Expand Down
5 changes: 4 additions & 1 deletion packages/program/src/functions/base-invocation-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ function createContractCall(funcScope: InvocationScopeLike): ContractCall {

return {
contractId: (program as AbstractContract).id,
proxyContractId: (program as AbstractContract).proxyContractId,
fnSelectorBytes: func.selectorBytes,
data,
assetId: forward?.assetId,
Expand Down Expand Up @@ -119,7 +120,9 @@ export class BaseInvocationScope<TReturn = any> {
protected updateContractInputAndOutput() {
const calls = this.calls;
calls.forEach((c) => {
if (c.contractId) {
if (c.proxyContractId) {
this.transactionRequest.addContractInputAndOutput(c.proxyContractId);
} else if (c.contractId) {
this.transactionRequest.addContractInputAndOutput(c.contractId);
}
if (c.externalContractsAbis) {
Expand Down
11 changes: 6 additions & 5 deletions packages/program/src/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ export const extractInvocationResult = <T>(
if (functionScopes.length === 1 && mainCallConfig && 'bytes' in mainCallConfig.program) {
return callResultToInvocationResult<T>({ receipts }, mainCallConfig, logs);
}
const encodedResults = decodeContractCallScriptResult(
{ receipts },
(mainCallConfig?.program as AbstractContract).id,
logs
);

const contractId =
(mainCallConfig?.program as AbstractContract).proxyContractId ||
(mainCallConfig?.program as AbstractContract).id;

const encodedResults = decodeContractCallScriptResult({ receipts }, contractId, logs);

const decodedResults = encodedResults.map((encodedResult, i) => {
const { func } = functionScopes[i].getCallConfig();
Expand Down
1 change: 1 addition & 0 deletions packages/program/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type { FunctionInvocationScope } from './functions/invocation-scope';
*/
export type ContractCall = {
contractId: AbstractAddress;
proxyContractId?: AbstractAddress;
data: BytesLike;
fnSelectorBytes: Uint8Array;
amount?: BigNumberish;
Expand Down
Loading